def __init__(self, service_manager):
        # Client for all the services on a management node.
        self.service_manager = service_manager

        # Returns the service which provides support for generic functionality
        # which can be applied equally to all types of libraries
        self.library_service = Library(self.service_manager.stub_config)

        # Returns the service for managing local libraries
        self.local_library_service = LocalLibrary(self.service_manager.stub_config)

        # Returns the service for managing subscribed libraries
        self.subscribed_library_service = SubscribedLibrary(self.service_manager.stub_config)

        # Returns the service for managing library items
        self.library_item_service = Item(self.service_manager.stub_config)

        # Returns the service for managing sessions to update or delete content
        self.upload_service = UpdateSession(self.service_manager.stub_config)

        # Returns the service for managing files within an update session
        self.upload_file_service = UpdateSessionFile(self.service_manager.stub_config)

        # Returns the service for managing sessions to download content
        self.download_service = DownloadSession(self.service_manager.stub_config)

        # Returns the service for managing files within a download session
        self.download_file_service = DownloadSessionFile(self.service_manager.stub_config)

        # Returns the service for deploying virtual machines from OVF library items
        self.ovf_lib_item_service = LibraryItem(self.service_manager.stub_config)

        # Returns the service for mount and unmount of an iso file on a VM
        self.iso_service = Image(self.service_manager.stub_config)

        # Returns the service for managing subscribed library items
        self.subscribed_item_service = SubscribedItem(self.service_manager.stub_config)

        # Returns the service for managing library items containing virtual
        # machine templates
        self.vmtx_service = VmtxLibraryItem(self.service_manager.stub_config)

        # Returns the service for managing subscription information of
        # the subscribers of a published library.
        self.subscriptions = Subscriptions(self.service_manager.stub_config)

        # Creates the service that communicates with virtual machines
        self.vm_service = VM(self.service_manager.stub_config)

        # Returns the service for managing checkouts of a library item containing
        # a virtual machine template
        self.check_outs_service = CheckOuts(self.service_manager.stub_config)

        # Returns the service for managing the live versions of the virtual machine
        # templates contained in a library item
        self.versions_service = Versions(self.service_manager.stub_config)

        # Returns the service for managing the history of content changes made
        # to a library item
        self.changes_service = Changes(self.service_manager.stub_config)
Ejemplo n.º 2
0
    def _execute(self):

        # Find the cluster's resource pool moid
        cluster_obj = get_obj(self.servicemanager.content,
                              [vim.ClusterComputeResource], self.cluster_name)
        assert cluster_obj is not None
        print("Cluster Moref: {0}".format(cluster_obj))

        deployment_target = LibraryItem.DeploymentTarget(
            resource_pool_id=cluster_obj.resourcePool._GetMoId())

        # Find lib item id from given item name
        find_spec = Item.FindSpec()
        find_spec.name = self.lib_item_name
        item_ids = self.client.library_item_service.find(find_spec)
        assert (item_ids is not None and len(item_ids) > 0), (
            'No items found with name: {0}'.format(self.lib_item_name))
        lib_item_id = item_ids[0]

        ovf_summary = self.client.ovf_lib_item_service.filter(
            ovf_library_item_id=lib_item_id, target=deployment_target)
        print('Found an OVF template :{0} to deploy.'.format(ovf_summary.name))

        # Deploy the ovf template
        self.deploy_ovf_template(lib_item_id, ovf_summary, deployment_target)
Ejemplo n.º 3
0
    def _setup(self):
        if self.cl_name is None:
            self.cl_name = self.args.contentlibraryname
        assert self.cl_name is not None

        if self.datastore_name is None:
            self.datastore_name = self.args.datastorename
        assert self.datastore_name is not None

        if self.cluster_name is None:
            self.cluster_name = self.args.clustername
        assert self.cluster_name is not None

        if self.vm_name is None:
            self.vm_name = self.args.vmname
        assert self.vm_name is not None

        if self.servicemanager is None:
            self.servicemanager = self.get_service_manager()

        self.library_service = Library(self.servicemanager.stub_config)
        self.local_library_service = LocalLibrary(self.servicemanager.stub_config)
        self.library_item_service = Item(self.servicemanager.stub_config)
        self.upload_service = UpdateSession(self.servicemanager.stub_config)
        self.upload_file_service = UpdateSessionFile(self.servicemanager.stub_config)
        self.download_service = DownloadSession(self.servicemanager.stub_config)
        self.download_file_service = DownloadSessionFile(self.servicemanager.stub_config)
        self.ovf_lib_item_service = LibraryItem(self.servicemanager.stub_config)
Ejemplo n.º 4
0
    def __init__(self, service_manager):
        # Client for all the services on a management node.
        self.service_manager = service_manager

        # Returns the service which provides support for generic functionality
        # which can be applied equally to all types of libraries
        self.library_service = Library(self.service_manager.stub_config)

        # Returns the service for managing local libraries
        self.local_library_service = LocalLibrary(
            self.service_manager.stub_config)

        # Returns the service for managing subscribed libraries
        self.subscribed_library_service = SubscribedLibrary(
            self.service_manager.stub_config)

        # Returns the service for managing library items
        self.library_item_service = Item(self.service_manager.stub_config)

        # Returns the service for managing sessions to update or delete content
        self.upload_service = UpdateSession(self.service_manager.stub_config)

        # Returns the service for managing files within an update session
        self.upload_file_service = UpdateSessionFile(
            self.service_manager.stub_config)

        # Returns the service for managing sessions to download content
        self.download_service = DownloadSession(
            self.service_manager.stub_config)

        # Returns the service for managing files within a download session
        self.download_file_service = DownloadSessionFile(
            self.service_manager.stub_config)

        # Returns the service for deploying virtual machines from OVF library items
        self.ovf_lib_item_service = LibraryItem(
            self.service_manager.stub_config)

        # Returns the service for mount and unmount of an iso file on a VM
        self.iso_service = Image(self.service_manager.stub_config)

        # Returns the service for managing subscribed library items
        self.subscribed_item_service = SubscribedItem(
            self.service_manager.stub_config)

        # Returns the service for managing library items containing virtual
        # machine templates
        self.vmtx_service = VmtxLibraryItem(self.service_manager.stub_config)

        # Creates the service that communicates with virtual machines
        self.vm_service = VM(self.service_manager.stub_config)
Ejemplo n.º 5
0
    def get_library_item_by_name(self, name):
        """
        Returns the identifier of the library item with the given name.

        Args:
            name (str): The name of item to look for

        Returns:
            str: The item ID or None if the item is not found
        """
        find_spec = Item.FindSpec(name=name)
        item_ids = self.api_client.content.library.Item.find(find_spec)
        item_id = item_ids[0] if item_ids else None
        return item_id
Ejemplo n.º 6
0
    def get_item_id_by_name(self, name):
        """
        Returns the identifier of the item with the given name.

        Args:
            name (str): The name of item to look for

        Returns:
            str: The item ID or None if the item is not found
        """
        find_spec = Item.FindSpec(name=name)
        item_ids = self.client.library_item_service.find(find_spec)
        item_id = item_ids[0] if item_ids else None
        if item_id:
            print('Library item ID: {0}'.format(item_id))
        else:
            print("Library item with name '{0}' not found".format(name))
        return item_id
Ejemplo n.º 7
0
 def get_library_item_from_content_library_name(self, name,
                                                content_library_name):
     """
     Returns the identifier of the library item with the given name in the specified
     content library.
     Args:
         name (str): The name of item to look for
         content_library_name (str): The name of the content library to search in
     Returns:
         str: The item ID or None if the item is not found
     """
     cl_find_spec = self.api_client.content.Library.FindSpec(
         name=content_library_name)
     cl_item_ids = self.api_client.content.Library.find(cl_find_spec)
     cl_item_id = cl_item_ids[0] if cl_item_ids else None
     if cl_item_id:
         find_spec = Item.FindSpec(name=name, library_id=cl_item_id)
         item_ids = self.api_client.content.library.Item.find(find_spec)
         item_id = item_ids[0] if item_ids else None
         return item_id
     else:
         return None
    def deploy_ovf_template(self):

        # Build the deployment target with resource pool ID and folder ID
        rp_filter_spec = ResourcePool.FilterSpec(names=set([self.resourcepoolname]))
        resource_pool_summaries = self.client.vcenter.ResourcePool.list(rp_filter_spec)
        if not resource_pool_summaries:
            raise ValueError("Resource pool with name '{}' not found".
                             format(self.resourcepoolname))
        resource_pool_id = resource_pool_summaries[0].resource_pool
        print('Resource pool ID: {}'.format(resource_pool_id))

        folder_filter_spec = Folder.FilterSpec(names=set([self.foldername]))
        folder_summaries = self.client.vcenter.Folder.list(folder_filter_spec)
        if not folder_summaries:
            raise ValueError("Folder with name '{}' not found".
                             format(self.foldername))
        folder_id = folder_summaries[0].folder
        print('Folder ID: {}'.format(folder_id))

        deployment_target = LibraryItem.DeploymentTarget(
            resource_pool_id=resource_pool_id,
            folder_id=folder_id
        )

        # Find the library item
        find_spec = Item.FindSpec(name=self.lib_item_name)
        lib_item_ids = self.client.content.library.Item.find(find_spec)
        if not lib_item_ids:
            raise ValueError("Library item with name '{}' not found".
                             format(self.lib_item_name))
        lib_item_id = lib_item_ids[0]
        print('Library item ID: {}'.format(lib_item_id))
        ovf_summary = self.client.vcenter.ovf.LibraryItem.filter(
            ovf_library_item_id=lib_item_id,
            target=deployment_target)
        print('Found an OVF template: {} to deploy.'.format(ovf_summary.name))

        # Build the deployment spec
        deployment_spec = LibraryItem.ResourcePoolDeploymentSpec(
            name=self.vm_name,
            annotation=ovf_summary.annotation,
            accept_all_eula=True,
            network_mappings=None,
            storage_mappings=None,
            storage_provisioning=None,
            storage_profile_id=None,
            locale=None,
            flags=None,
            additional_parameters=None,
            default_datastore_id=None)

        # Deploy the ovf template
        result = self.client.vcenter.ovf.LibraryItem.deploy(
            lib_item_id,
            deployment_target,
            deployment_spec,
            client_token=generate_random_uuid())

        # The type and ID of the target deployment is available in the deployment result.
        if result.succeeded:
            print('Deployment successful. VM Name: "{}", ID: "{}"'
                  .format(self.vm_name, result.resource_id.id))
            self.vm_id = result.resource_id.id
            error = result.error
            if error is not None:
                for warning in error.warnings:
                    print('OVF warning: {}'.format(warning.message))

        else:
            print('Deployment failed.')
            for error in result.error.errors:
                print('OVF error: {}'.format(error.message))

        # Add an opaque network portgroup to the deployed VM
        if self.opaquenetworkname:
            filter = Network.FilterSpec(
                names=set([self.opaquenetworkname]),
                types=set([Network.Type.OPAQUE_NETWORK]))
            network_summaries = self.client.vcenter.Network.list(filter=filter)
            if not network_summaries:
                raise ValueError("Opaque network {} can not find".format(
                    self.opaquenetworkname))
            network = network_summaries[0].network

            nic_create_spec = Ethernet.CreateSpec(
                start_connected=True,
                mac_type=Ethernet.MacAddressType.GENERATED,
                backing=Ethernet.BackingSpec(
                    type=Ethernet.BackingType.OPAQUE_NETWORK,
                    network=network))
            print('vm.hardware.Ethernet.create({}, {}) -> {}'.format(
                self.vm_id, nic_create_spec, network))
            nic = self.client.vcenter.vm.hardware.Ethernet.create(
                self.vm_id, nic_create_spec)

            nic_info = self.client.vcenter.vm.hardware.Ethernet.get(self.vm_id, nic)
            print('vm.hardware.Ethernet.get({}, {}) -> {}'.format(
                self.vm_id, nic, pp(nic_info)))
Ejemplo n.º 9
0
    def deploy_kmip_node(self, spec, debug=False):
        # Check if we know about the deployment target yet
        if self.vcs_cluster_obj is None:
            # Find the cluster's resource pool moid
            print()
            print("Obtaining the cluster's resource pool moid...")
            self.vcs_cluster_obj = get_obj(self.service_manager.content,
                                           [vim.ClusterComputeResource],
                                           self.deploy_to_cluster)
            assert self.vcs_cluster_obj is not None
            if debug:
                print(" --> Cluster: {0}".format(self.vcs_cluster_obj))

        # Get a deployment target resource pool from the Cluster Object
        deployment_target = LibraryItem.DeploymentTarget(
            resource_pool_id=self.vcs_cluster_obj.resourcePool._GetMoId())
        if debug:
            print(" --> Resource Pool Moref: {0}".format(
                self.vcs_cluster_obj.resourcePool._GetMoId()))

        # Find lib item id from given item name
        find_spec = Item.FindSpec()
        find_spec.name = self.selected_item["name"]
        item_ids = self.sm_client.library_item_service.find(find_spec)
        assert (item_ids is not None and len(item_ids) > 0), (
            'No items found with name: {0}'.format(self.selected_item["name"]))
        lib_item_id = item_ids[0]

        ovf_summary = self.sm_client.ovf_lib_item_service.filter(
            ovf_library_item_id=lib_item_id, target=deployment_target)
        print()
        print('Deploying OVF template: {0} to cluster: {1}...'.format(
            ovf_summary.name, self.deploy_to_cluster))

        # Build the deployment spec
        deployment_spec = LibraryItem.ResourcePoolDeploymentSpec(
            name=spec.name,
            annotation=ovf_summary.annotation,
            accept_all_eula=True,
            network_mappings=None,
            storage_mappings=None,
            storage_provisioning=None,
            storage_profile_id=None,
            locale=None,
            flags=None,
            additional_parameters=None,
            default_datastore_id=None)

        # Deploy the ovf template
        print("Deploying HyTrust OVF Template -- please wait...")
        print()
        result = self.sm_client.ovf_lib_item_service.deploy(
            lib_item_id,
            deployment_target,
            deployment_spec,
            client_token=generate_random_uuid())

        # The type and ID of the target deployment is available in the deployment result.
        if result.succeeded:
            print('>>> Deployment successful.')
            if debug:
                print('Result resource: {0}, ID: {1}'.format(
                    result.resource_id.type, result.resource_id.id))

            error = result.error
            #    if error is not None:
            #        for warning in error.warnings:
            #            print('OVF warning: {}'.format(warning.message))

            # Get the vm object
            if spec.is_primary():
                self.primary_node_id = result.resource_id.id
                self.primary_node_obj = get_obj_by_moId(
                    self.service_manager.content, [vim.VirtualMachine],
                    self.primary_node_id)
                assert self.primary_node_obj is not None
                vm_obj = self.primary_node_obj
                vm_id = self.primary_node_id
            else:
                self.secondary_node_id = result.resource_id.id
                self.secondary_node_obj = get_obj_by_moId(
                    self.service_manager.content, [vim.VirtualMachine],
                    self.secondary_node_id)
                assert self.secondary_node_obj is not None
                vm_obj = self.secondary_node_obj
                vm_id = self.secondary_node_id

            # Invoke the SmartConnect() method by supplying the host name, user name, and password.
            self.service_instance_stub = SmartConnect(host=self.web_svcs_host,
                                                      user=self.sso_user,
                                                      pwd=self.sso_pass)
            atexit.register(connect.Disconnect, self.service_instance_stub)
            content = self.service_instance_stub.RetrieveContent()
            if debug:
                print("VM UUID: {0}".format(vm_obj.summary.config.uuid))

            if spec.is_primary():
                self.primary_node_vm = content.searchIndex.FindByUuid(
                    None, vm_obj.summary.config.uuid, True)
                vm = self.primary_node_vm
            else:
                self.secondary_node_vm = content.searchIndex.FindByUuid(
                    None, vm_obj.summary.config.uuid, True)
                vm = self.secondary_node_vm

            print()
            print("Setting vApp Options on the VM...")
            vapp_spec_list = list()

            # Domain Name
            vapp_domainName = vim.vApp.PropertyInfo()
            vapp_domainName.key = 0
            vapp_domainName.value = spec.domain
            vapp_spec1 = vim.vApp.PropertySpec()
            vapp_spec1.info = vapp_domainName
            vapp_spec1.operation = 'edit'
            vapp_spec_list.append(vapp_spec1)

            # Netmask
            vapp_netmask = vim.vApp.PropertyInfo()
            vapp_netmask.key = 1
            vapp_netmask.value = spec.subnet
            vapp_spec2 = vim.vApp.PropertySpec()
            vapp_spec2.info = vapp_netmask
            vapp_spec2.operation = 'edit'
            vapp_spec_list.append(vapp_spec2)

            # KCMaster
            vapp_kcmaster = vim.vApp.PropertyInfo()
            vapp_kcmaster.key = 2
            if spec.is_primary():
                vapp_kcmaster.value = ''
            else:
                vapp_kcmaster.userConfigurable = True
                vapp_kcmaster.value = self.primary_node_spec.ip
            vapp_spec3 = vim.vApp.PropertySpec()
            vapp_spec3.info = vapp_kcmaster
            vapp_spec3.operation = 'edit'
            vapp_spec_list.append(vapp_spec3)

            # Console Password
            vapp_consolepw = vim.vApp.PropertyInfo()
            vapp_consolepw.key = 3
            vapp_consolepw.userConfigurable = True
            vapp_consolepw.value = spec.consolepw
            vapp_spec4 = vim.vApp.PropertySpec()
            vapp_spec4.info = vapp_consolepw
            vapp_spec4.operation = 'edit'
            vapp_spec_list.append(vapp_spec4)

            # HTKC Hostname
            vapp_htkcHostname = vim.vApp.PropertyInfo()
            vapp_htkcHostname.key = 4
            vapp_htkcHostname.value = spec.name
            vapp_spec5 = vim.vApp.PropertySpec()
            vapp_spec5.info = vapp_htkcHostname
            vapp_spec5.operation = 'edit'
            vapp_spec_list.append(vapp_spec5)

            # DNS Servers
            vapp_dns = vim.vApp.PropertyInfo()
            vapp_dns.key = 5
            vapp_dns.value = spec.dns
            vapp_spec6 = vim.vApp.PropertySpec()
            vapp_spec6.info = vapp_dns
            vapp_spec6.operation = 'edit'
            vapp_spec_list.append(vapp_spec6)

            # HTKC IP Address
            vapp_htkcIP = vim.vApp.PropertyInfo()
            vapp_htkcIP.key = 6
            vapp_htkcIP.value = spec.ip
            vapp_spec7 = vim.vApp.PropertySpec()
            vapp_spec7.info = vapp_htkcIP
            vapp_spec7.operation = 'edit'
            vapp_spec_list.append(vapp_spec7)

            # NTP Servers
            vapp_ntp = vim.vApp.PropertyInfo()
            vapp_ntp.key = 7
            vapp_ntp.value = '0.us.pool.ntp.org, 1.us.pool.ntp.org'
            vapp_spec8 = vim.vApp.PropertySpec()
            vapp_spec8.info = vapp_ntp
            vapp_spec8.operation = 'edit'
            vapp_spec_list.append(vapp_spec8)

            # Gateway
            vapp_gateway = vim.vApp.PropertyInfo()
            vapp_gateway.key = 8
            vapp_gateway.value = spec.gateway
            vapp_spec9 = vim.vApp.PropertySpec()
            vapp_spec9.info = vapp_gateway
            vapp_spec9.operation = 'edit'
            vapp_spec_list.append(vapp_spec9)

            # KC Cluster Password
            vapp_kcpw = vim.vApp.PropertyInfo()
            vapp_kcpw.key = 9
            vapp_kcpw.userConfigurable = True
            vapp_kcpw.value = spec.clusterpw
            vapp_spec10 = vim.vApp.PropertySpec()
            vapp_spec10.info = vapp_kcpw
            vapp_spec10.operation = 'edit'
            vapp_spec_list.append(vapp_spec10)

            # Make the modifications
            config_spec = vim.vm.ConfigSpec()
            config_spec.vAppConfig = vim.vApp.VmConfigSpec()
            config_spec.vAppConfig.property = vapp_spec_list
            reconfig_task = vm.ReconfigVM_Task(config_spec)
            task.wait_for_task(reconfig_task)
            print("Successfully modified VM:[{0}] properties".format(
                spec.name))

            # Add the KMS tag to the VM
            print()
            print('Tagging the KMS VM :: {0}...'.format(spec.name))
            kms_tag_attached = self.tag_vm(vm_id, self.kms_tag_id)
            assert kms_tag_attached
            if debug:
                print('Tagged KMS vm: {0}'.format(vm_id))

            # Power on the VM and wait for the power on operation to be completed
            print()
            print("Powering on the KMS Server: {0} ...".format(spec.name))
            poweron_vm(self.service_manager.content, vm_obj)

            while vm.runtime.powerState != vim.VirtualMachinePowerState.poweredOn:
                print("Waiting for VM [{0}] to power on...".format(spec.name))
                time.sleep(3)

            # Get a WebKMS ticket so we can manipulate the console if we need to
            if spec.is_primary():
                self.primary_node_ticket = vm.AcquireTicket("webmks")
                ticket = self.primary_node_ticket
            else:
                self.secondary_node_ticket = vm.AcquireTicket("webmks")
                ticket = self.secondary_node_ticket
            print("WebMKS Ticket: {0}".format(ticket))
            print("WMKS URL: wss://{0}:{1}/ticket/{2}".format(
                ticket.host, ticket.port, ticket.ticket))
        else:
            print('Deployment failed.')
            for error in result.error.errors:
                print('OVF error: {}'.format(error.message))
Ejemplo n.º 10
0
    def deploy_ovf_template(self):

        # Build the deployment target with resource pool ID
        filter_spec = ResourcePool.FilterSpec(
            names=set([self.resourcepoolname]))
        resource_pool_summaries = self.client.vcenter.ResourcePool.list(
            filter_spec)
        if not resource_pool_summaries:
            raise ValueError("Resource pool with name '{}' not found".format(
                self.resourcepoolname))
        resource_pool_id = resource_pool_summaries[0].resource_pool
        print('Resource pool ID: {}'.format(resource_pool_id))
        deployment_target = LibraryItem.DeploymentTarget(
            resource_pool_id=resource_pool_id)

        # Find the library item
        find_spec = Item.FindSpec(name=self.lib_item_name)
        lib_item_ids = self.client.content.library.Item.find(find_spec)
        if not lib_item_ids:
            raise ValueError("Library item with name '{}' not found".format(
                self.lib_item_name))
        lib_item_id = lib_item_ids[0]
        print('Library item ID: {}'.format(lib_item_id))
        ovf_summary = self.client.vcenter.ovf.LibraryItem.filter(
            ovf_library_item_id=lib_item_id, target=deployment_target)
        print('Found an OVF template: {} to deploy.'.format(ovf_summary.name))

        # Build the deployment spec
        deployment_spec = LibraryItem.ResourcePoolDeploymentSpec(
            name=self.vm_name,
            annotation=ovf_summary.annotation,
            accept_all_eula=True,
            network_mappings=None,
            storage_mappings=None,
            storage_provisioning=None,
            storage_profile_id=None,
            locale=None,
            flags=None,
            additional_parameters=None,
            default_datastore_id=None)

        # Deploy the ovf template
        result = self.client.vcenter.ovf.LibraryItem.deploy(
            lib_item_id,
            deployment_target,
            deployment_spec,
            client_token=generate_random_uuid())

        # The type and ID of the target deployment is available in the deployment result.
        if result.succeeded:
            print('Deployment successful. Result resource: {}, ID: {}'.format(
                result.resource_id.type, result.resource_id.id))
            self.vm_id = result.resource_id.id
            error = result.error
            if error is not None:
                for warning in error.warnings:
                    print('OVF warning: {}'.format(warning.message))

        else:
            print('Deployment failed.')
            for error in result.error.errors:
                print('OVF error: {}'.format(error.message))
Ejemplo n.º 11
0
class ContentLibraryWorkflow(SampleBase):
    """
    Demonstrates content library workflow
    Step 1: Retrieve datastores vAPI UUID by using its name.
    Step 2: Create a published content library backed by vc ds using vAPIs.
    Step 3: Create a content library item.
    Step 4: Upload a VM template to the published CL.
    Step 5: Download the template files from the CL to make sure the upload went OK.
    Step 6: Deploy a VM using the uploaded template on a given cluster using OVF importer.
    Step 7: Power on the VM and wait for the power on operation to complete.
    Additional steps when clearData flag is set to TRUE:
    Step 8: Power off the VM and wait for the power off operation to complete.
    Step 9: Delete the VM.
    Step 10: Delete the CL item.
    Step 11: Delete the CL.
    Note: the workflow needs an existing VC DS with available storage and a cluster with resources for creating the VM
    """

    def __init__(self, platformservicecontroller):
        SampleBase.__init__(self, self.__doc__, platformservicecontroller)
        self.servicemanager = None
        self.datastore_name = None
        self.datastore_id = None
        self.cl_name = None
        self.cluster_name = None
        self.vm_name = None
        self.lib_description = 'published content library'

        self.library_service = None
        self.local_library_service = None
        self.library_item_service = None
        self.upload_service = None
        self.upload_file_service = None
        self.download_service = None
        self.download_file_service = None
        self.ovf_lib_item_service = None

        self.published_library = None
        self.library_item_id = None
        self.vm_id = None
        self.vm_obj = None

    def _options(self):
        self.argparser.add_argument('-contentlibraryname', '--contentlibraryname', help='The name of the content library to be created.')
        self.argparser.add_argument('-datastorename', '--datastorename', help='The name of the data store.')
        self.argparser.add_argument('-clustername', '--clustername', help='The name of the cluster where the vm gets created from the uploaded template.')
        self.argparser.add_argument('-vmname', '--vmname', help='The name of the vm to be created in the cluster.')

    def _setup(self):
        if self.cl_name is None:
            self.cl_name = self.args.contentlibraryname
        assert self.cl_name is not None

        if self.datastore_name is None:
            self.datastore_name = self.args.datastorename
        assert self.datastore_name is not None

        if self.cluster_name is None:
            self.cluster_name = self.args.clustername
        assert self.cluster_name is not None

        if self.vm_name is None:
            self.vm_name = self.args.vmname
        assert self.vm_name is not None

        if self.servicemanager is None:
            self.servicemanager = self.get_service_manager()

        self.library_service = Library(self.servicemanager.stub_config)
        self.local_library_service = LocalLibrary(self.servicemanager.stub_config)
        self.library_item_service = Item(self.servicemanager.stub_config)
        self.upload_service = UpdateSession(self.servicemanager.stub_config)
        self.upload_file_service = UpdateSessionFile(self.servicemanager.stub_config)
        self.download_service = DownloadSession(self.servicemanager.stub_config)
        self.download_file_service = DownloadSessionFile(self.servicemanager.stub_config)
        self.ovf_lib_item_service = LibraryItem(self.servicemanager.stub_config)

    def _execute(self):
        # Find the data store by the given data store name using property collector
        self.datastore_id = get_datastore_id(service_manager=self.servicemanager, datastore_name=self.datastore_name)
        assert self.datastore_id is not None
        logger.info('DataStore: {0} ID: {1}'.format(self.datastore_name, self.datastore_id))
        visible_cls = self.library_service.list()
        if len(visible_cls) > 0:
            for visible_cl in visible_cls:
                get_visible_cl = self.library_service.get(visible_cl)
                logger.info('Visible content library: {0} with id: {1}'.format(get_visible_cl.name, visible_cl))
        local_cls = self.local_library_service.list()
        if len(local_cls) > 0:
            for local_cl in local_cls:
                get_local_cl = self.local_library_service.get(local_cl)
                logger.info('Local content library: {0} with id: {1}'.format(get_local_cl.name, local_cl))
        logger.info('Creating Published Content Library')
        # Create a public (no auth) publish info
        publish_info = self.get_publish_info(published=True,
                                             publish_url=None,
                                             authentication=PublishInfo.AuthenticationMethod.NONE,
                                             publish_user_name=None,
                                             publish_password=None)

        # Create a published content library
        self.published_library = self.create_published_library(client_token=generate_random_uuid(),
                                                               cl_name=self.cl_name,
                                                               publish_info=publish_info,
                                                               ds_id=self.datastore_id)
        assert self.published_library is not None
        logger.info('Published Content Library created with name: {0} and id: {1}'.format
                    (self.published_library.name, self.published_library.id))
        publish_info = self.published_library.publish_info
        publish_url = publish_info.publish_url
        logger.info('Publish url: {0}'.format(publish_url))

        # create a new library item in the content library for uploading the files
        self.library_item_id = self.create_library_item(library_id=self.published_library.id,
                                                        item_name='simpleVmTemplate',
                                                        item_description='Sample simple VM template',
                                                        item_type='ovf')
        assert self.library_item_id is not None
        assert self.library_item_service.get(self.library_item_id) is not None
        logger.info('Library item created id: {0}'.format(self.library_item_id))

        # Upload a VM template to the published CL
        ovf_files_map = self.get_ovf_files_map()
        self.upload_files(library_item_id=self.library_item_id, ovf_files_map=ovf_files_map)
        logger.info('Uploaded ovf and vmdk files to library item {0}'.format(self.library_item_id))

        # download the library item from the CL
        temp_dir = tempfile.mkdtemp(prefix='simpleVmTemplate-')
        logger.info('Downloading library item {0} to directory {1}'.format(self.library_item_id, temp_dir))
        downloaded_files_map = self.download(library_item_id=self.library_item_id, directory=temp_dir)
        assert len(downloaded_files_map) == len(ovf_files_map)

        # deploy vm into the cluster's resource pool from the uploaded template
        self.vm_id = self.deploy_vm_from_cl()
        assert self.vm_id is not None
        logger.info('Vm created: {}'.format(self.vm_id))

        # power on the vm and wait for the power on operation to be completed
        self.vm_obj = get_obj_by_moId(self.servicemanager.content, [vim.VirtualMachine], self.vm_id)
        assert self.vm_obj is not None
        poweron_vm(self.servicemanager.content, self.vm_obj)

    def _cleanup(self):
        if self.vm_obj is not None:
            # power off the vm
            poweroff_vm(self.servicemanager.content, self.vm_obj)
            # delete the vm
            delete_object(self.servicemanager.content, self.vm_obj)

        if self.library_item_id is not None:
            self.library_item_service.delete(library_item_id=self.library_item_id)
            logger.info('Deleted Library Item: {0}'.format(self.library_item_id))

        if self.published_library is not None:
            self.local_library_service.delete(library_id=self.published_library.id)
            logger.info('Deleted Library Id: {0}'.format(self.published_library.id))

    def get_ovf_files_map(self):
        """Get vm template files"""
        ovf_files_map = {}
        ovf_dir = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../../../../../../resources/simpleVmTemplate'))
        for file_name in os.listdir(ovf_dir):
            if file_name.endswith('.ovf') or file_name.endswith('.vmdk'):
                ovf_files_map[file_name] = os.path.join(ovf_dir, file_name)
        return ovf_files_map

    def get_publish_info(self, published, publish_url, authentication, publish_user_name, publish_password):
        """Generate PublishInfo"""
        publish_info = PublishInfo()
        publish_info.published = published
        publish_info.authentication_method = authentication
        publish_info.publish_url = publish_url
        publish_info.user_name = publish_user_name
        publish_info.password = publish_password
        return publish_info

    def create_published_library(self, client_token, cl_name, publish_info, ds_id):
        """Creates publish library back up by vCenter data store (as is)"""
        library_model = LibraryModel()
        library_model.id = client_token
        library_model.name = cl_name
        library_model.description = self.lib_description
        library_model.type = library_model.LibraryType.LOCAL
        library_model.publish_info = publish_info
        storage_backings = []
        storage_backing = StorageBacking(type=StorageBacking.Type.DATASTORE, datastore_id=ds_id)
        storage_backings.append(storage_backing)
        library_model.storage_backings = storage_backings
        library_id = self.local_library_service.create(create_spec=library_model, client_token=client_token)
        library = self.local_library_service.get(library_id)
        return library

    def create_library_item(self, library_id, item_name, item_description, item_type):
        """Create a library item in the specified library"""
        lib_item_spec = self.get_libraryitem_spec(client_token=generate_random_uuid(),
                                                  name=item_name,
                                                  description=item_description,
                                                  library_id=library_id,
                                                  library_item_type=item_type)
        # Create a library item
        return self.library_item_service.create(create_spec=lib_item_spec, client_token=generate_random_uuid())

    def upload_files(self, library_item_id, ovf_files_map):
        """Upload a VM template to the published CL"""
        # create a new upload session for uploading the files
        session_id = self.upload_service.create(create_spec=UpdateSessionModel(library_item_id=library_item_id),
                                                client_token=generate_random_uuid())
        for f_name, f_path in ovf_files_map.items():
            file_spec = self.upload_file_service.AddSpec(name=f_name,
                                                         source_type=UpdateSessionFile.SourceType.PUSH,
                                                         size=os.path.getsize(f_path))
            file_info = self.upload_file_service.add(session_id, file_spec)
            # Upload the file content to the file upload URL
            with open(f_path, 'rb') as local_file:
                request = urllib2.Request(file_info.upload_endpoint.uri, local_file)
                request.add_header('Cache-Control', 'no-cache')
                request.add_header('Content-Length', '{0}'.format(os.path.getsize(f_path)))
                request.add_header('Content-Type', 'text/ovf')
                urllib2.urlopen(request)
        self.upload_service.complete(session_id)
        self.upload_service.delete(session_id)

    def get_libraryitem_spec(self, client_token, name, description, library_id, library_item_type):
        """Create library item spec"""
        lib_item_spec = ItemModel()
        lib_item_spec.id = client_token
        lib_item_spec.name = name
        lib_item_spec.description = description
        lib_item_spec.library_id = library_id
        lib_item_spec.type = library_item_type
        return lib_item_spec

    def download(self, library_item_id, directory):
        """Download vappTemplate files"""
        downloaded_files_map = {}
        # create a new download session for downloading the session files
        session_id = self.download_service.create(create_spec=DownloadSessionModel(library_item_id=library_item_id),
                                                  client_token=generate_random_uuid())
        file_infos = self.download_file_service.list(session_id)
        for file_info in file_infos:
            self.download_file_service.prepare(session_id, file_info.name)
            download_info = self.wait_for_prepare(session_id, file_info.name)
            response = urllib2.urlopen(download_info.download_endpoint.uri)
            file_path = os.path.join(directory, file_info.name)
            with open(file_path, 'wb') as local_file:
                local_file.write(response.read())
            downloaded_files_map[file_info.name] = file_path
        self.download_service.delete(session_id)
        return downloaded_files_map

    def wait_for_prepare(self, session_id, file_name, status_list=[DownloadSessionFile.PrepareStatus.PREPARED],
                         timeout=30, sleep_interval=1):
        """
        waits for a file part of a download session to reach a status in the status list (by default prepared)
        this method will either timeout or return the result of downloadSessionFile.get(session_id, file_name)
        """
        start_time = time.time()
        while (time.time() - start_time) < timeout:
            file_info = self.download_file_service.get(session_id, file_name)
            if file_info.status in status_list:
                return file_info
            else:
                time.sleep(sleep_interval)
        raise Exception('timed out after waiting {0} seconds for file {1} to reach a terminal state'.format(
            timeout, file_name))

    def deploy_vm_from_cl(self):
        """
        deploys vm into the cluster's resource pool from the uploaded template in the content library.
        Returns the deployed vm's moid
        """
        # Find the cluster's resource pool moid
        cluster_obj = get_obj(self.servicemanager.content, [vim.ClusterComputeResource], self.cluster_name)
        if cluster_obj is None:
            raise ValueError('Cannot find the cluster: {}'.format(self.cluster_name))

        deployment_target = LibraryItem.DeploymentTarget(resource_pool_id=cluster_obj.resourcePool._GetMoId())

        # Suppose the caller does not know much about the OVF descriptor, and would like to obtain
        # more information regarding network mapping, storage mapping, or the additional parameters
        # policies available for the target resource pool. To do so, caller may use filter()
        # and specifying the target resource pool as input. The result from filter() will give
        # the list of storage group sections and network sections defined in the OVF descriptor that
        # are also applicable for the target resource pool.
        ovf_summary = self.ovf_lib_item_service.filter(ovf_library_item_id=self.library_item_id, target=deployment_target)
        logger.info('OVF Name: {}'.format(ovf_summary.name))
        logger.info('OVF Annotation: {}'.format(ovf_summary.annotation))
        if ovf_summary.networks is not None:
            for network in ovf_summary.networks:
                logger.info('OVF Network section: {}'.format(network))
        if ovf_summary.storage_groups is not None:
            for storage_group in ovf_summary.storage_groups:
                logger.info('OVF Storage group section: {}'.format(storage_group))
        if ovf_summary.additional_params:
            for param in ovf_summary.additional_params:
                logger.info('OVF Additional possible parameter Type: {}'.format(param))

        deployment_spec = LibraryItem.ResourcePoolDeploymentSpec(
                     name=self.vm_name,
                     annotation=ovf_summary.annotation,
                     accept_all_eula=True,
                     network_mappings=None,
                     storage_mappings=None,
                     storage_provisioning=None,
                     storage_profile_id=None,
                     locale=None,
                     flags=None,
                     additional_parameters=None,
                     default_datastore_id=None)

        result = self.ovf_lib_item_service.deploy(self.library_item_id,
                                                  deployment_target,
                                                  deployment_spec,
                                                  client_token=generate_random_uuid())

        # The type and ID of the target deployment is available in the instantiate result.
        if result.succeeded is True:
            logger.info('Instantiate successful! Result resource {}, ID {}'.format(result.resource_id.type,
                                                                                   result.resource_id.id))
            error = result.error
            if error is not None:
                for warning in error.warnings:
                    logger.warn('OVF warning: {}'.format(warning.message))
                for info in error.information:
                    for message in info.messages:
                        logger.info('OVF information message: {}'.format(message))
        else:
            logger.error('Instantiate failed!')
            for error in result.error.errors:
                logger.error('OVF error: {}'.format(error.message))
            raise Exception('OVF Instantiate failed!')

        return result.resource_id.id
Ejemplo n.º 12
0
from pyVmomi import vim
from samples.vsphere.common.service_manager import ServiceManager
from samples.vsphere.contentlibrary.lib.cls_api_client import ClsApiClient
from samples.vsphere.common.vim.helpers.vim_utils import get_obj
from com.vmware.content.library_client import Item
from com.vmware.vcenter.ovf_client import LibraryItem

vm_name = ''
rp_name = ''
template_name = ''
esx_host = ''
api_host = ''
api_user = ''
api_pass = ''

service_manager = ServiceManager(api_host, api_user, api_pass, True)
service_manager.connect()
client = ClsApiClient(service_manager)
find_spec = Item.FindSpec(name=template_name)
ovf_template_id = client.library_item_service.find(find_spec)[0]
target = get_obj(service_manager.content, [vim.HostSystem], esx_host)
rp = get_obj(service_manager.content, [vim.ResourcePool], rp_name)
deployment_target = LibraryItem.DeploymentTarget(
    host_id=target._GetMoId(), resource_pool_id=rp._GetMoId())
deployment_spec = LibraryItem.ResourcePoolDeploymentSpec(name=template_name +
                                                         '_deployed',
                                                         accept_all_eula=True)
client.ovf_lib_item_service.deploy(ovf_template_id, deployment_target,
                                   deployment_spec)
Ejemplo n.º 13
0
    def deployVM(self,
                 sddcName=None,
                 templateName='centos_master',
                 vmName='centos',
                 datastoreName='WorkloadDatastore',
                 resourcePoolName='Compute-ResourcePool',
                 folderName='Workloads',
                 ipAddress='192.168.2.4',
                 subnetMask='255.255.255.0',
                 gateway='192.168.2.1'):

        if not sddcName:
            raise ValueError('You must supply an SDDC name')
        if not templateName:
            raise ValueError('You must supply a Template name')
        if not vmName:
            raise ValueError('You must supply a VM name')
        if not datastoreName:
            raise ValueError('You must supply a Datastore name')
        if not resourcePoolName:
            raise ValueError('You must supply a Resource Pool name')
        if not folderName:
            raise ValueError('You must supply a Folder name')

        #podNumber = re.sub(r'^[^0-9]*(.*)',r'\1',sddcName)
        datastore = self.getDatastore(datastoreName)._moId
        resourcePool = self.getResourcePool(resourcePoolName)._moId
        folder = self.getFolder(folderName)._moId

        deploymentTarget = LibraryItem.DeploymentTarget(
            resource_pool_id=resourcePool, folder_id=folder)
        findSpec = Item.FindSpec(name=templateName)
        libraryItemService = Item(self.stub_config)
        ovfLibraryItemService = LibraryItem(self.stub_config)
        itemIDs = libraryItemService.find(findSpec)
        libItemID = itemIDs[0] if itemIDs else None
        print('Library item ID: {0}'.format(libItemID))

        ovfSummary = ovfLibraryItemService.filter(
            ovf_library_item_id=libItemID, target=deploymentTarget)
        print('Found an OVF template: {0} to deploy.'.format(ovfSummary.name))

        adaptermap = vim.vm.customization.AdapterMapping()
        adaptermap.adapter = vim.vm.customization.IPSettings(
            ip=vim.vm.customization.FixedIp(ipAddress=ipAddress),
            subnetMask=subnetMask,
            gateway=gateway)
        globalip = vim.vm.customization.GlobalIPSettings(
            dnsServerList=self.org.config['WorkshopConfig']['DnsConfig'])
        ident = vim.vm.customization.LinuxPrep(
            domain='domain.local',
            hostName=vim.vm.customization.FixedName(name=vmName))
        customspec = vim.vm.customization.Specification(
            nicSettingMap=[adaptermap],
            globalIPSettings=globalip,
            identity=ident)

        deploymentSpec = LibraryItem.ResourcePoolDeploymentSpec(
            name='centos',
            annotation=ovfSummary.annotation,
            accept_all_eula=True,
            network_mappings=None,
            storage_mappings=None,
            storage_provisioning=None,
            storage_profile_id=None,
            locale=None,
            flags=None,
            additional_parameters=None,
            default_datastore_id=None)
        result = ovfLibraryItemService.deploy(libItemID,
                                              deploymentTarget,
                                              deploymentSpec,
                                              client_token=str(uuid.uuid4()))

        # The type and ID of the target deployment is available in the deployment result.
        if result.succeeded:
            print(
                'Deployment successful. Result resource: {0}, ID: {1}'.format(
                    result.resource_id.type, result.resource_id.id))
            vm_id = result.resource_id.id
            error = result.error
            if error is not None:
                for warning in error.warnings:
                    print('OVF warning: {}'.format(warning.message))

            # Power on the VM and wait for the power on operation to be completed
            vm_obj = None
            container = self.content.viewManager.CreateContainerView(
                self.content.rootFolder, [vim.VirtualMachine], True)
            for c in container.view:
                if c._GetMoId() == vm_id:
                    vm_obj = c
                    break

            assert vm_obj is not None
            self.wait_for_tasks(self.content,
                                [vm_obj.Customize(spec=customspec)])
            self.wait_for_tasks(self.content, [vm_obj.PowerOn()])

        else:
            print('Deployment failed.')
            for error in result.error.errors:
                print('OVF error: {}'.format(error.message))