def setup(self):
        parser = sample_cli.build_arg_parser()
        parser.add_argument('-n',
                            '--vm_name',
                            action='store',
                            help='Name of the testing vm')
        parser.add_argument('-clustername',
                            '--clustername',
                            help='The name of the cluster to be used.')
        parser.add_argument('-libitemname',
                            '--libitemname',
                            help='The name of the library item to deploy.'
                            'The library item should contain an OVF package.')
        args = sample_util.process_cli_args(parser.parse_args())
        self.lib_item_name = args.libitemname
        self.cluster_name = args.clustername
        self.vm_name = args.vm_name

        self.servicemanager = ServiceManager(args.server, args.username,
                                             args.password,
                                             args.skipverification)
        self.servicemanager.connect()
        atexit.register(self.servicemanager.disconnect)

        self.client = ClsApiClient(self.servicemanager)
        self.helper = ClsApiHelper(self.client, args.skipverification)

        # Default VM name
        self.vm_name = 'vm-' + str(generate_random_uuid())
示例#2
0
    def _setup(self):
        self.datastore_name = self.args.datastorename
        assert self.datastore_name is not None

        self.servicemanager = self.get_service_manager()
        self.client = ClsApiClient(self.servicemanager)
        self.helper = ClsApiHelper(self.client, self.skip_verification)
示例#3
0
    def _setup(self):
        # Required arguments
        self.vm_name = self.args.vmname
        self.datastore_name = self.args.datastorename

        # Optional arguments
        self.item_name = (self.args.itemname if self.args.itemname
                          else rand('vmtx-item-'))

        self.servicemanager = self.get_service_manager()
        self.client = ClsApiClient(self.servicemanager)
        self.helper = ClsApiHelper(self.client, self.skip_verification)
    def _setup(self):
        # Required arguments
        self.item_name = self.args.itemname
        self.datacenter_name = self.args.datacentername
        self.folder_name = self.args.foldername
        self.resource_pool_name = self.args.resourcepoolname
        self.datastore_name = self.args.datastorename

        # Optional arguments
        self.vm_name = self.args.vmname if self.args.vmname else rand('vm-')

        self.servicemanager = self.get_service_manager()
        self.client = ClsApiClient(self.servicemanager)
        self.helper = ClsApiHelper(self.client, self.skip_verification)
示例#5
0
    def _setup(self):
        self.datastore_name = self.args.datastorename
        assert self.datastore_name is not None

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

        self.servicemanager = self.get_service_manager()

        self.client = ClsApiClient(self.servicemanager)
        self.helper = ClsApiHelper(self.client, self.skip_verification)

        session = get_unverified_session() if self.skip_verification else None
        self.vsphere_client = create_vsphere_client(server=self.server,
                                                    username=self.username,
                                                    password=self.password,
                                                    session=session)
示例#6
0
    def _setup(self):
        # Required arguments
        self.datacenter_name = self.args.datacentername
        self.resource_pool_name = self.args.resourcepoolname
        self.item_name = self.args.itemname

        # Optional arguments
        self.vm_name = (self.args.vmname
                        if self.args.vmname else rand('checked-out-vm-'))

        self.servicemanager = self.get_service_manager()
        self.client = ClsApiClient(self.servicemanager)
        self.helper = ClsApiHelper(self.client, self.skip_verification)

        session = get_unverified_session() if self.skip_verification else None
        self.vsphere_client = create_vsphere_client(server=self.server,
                                                    username=self.username,
                                                    password=self.password,
                                                    session=session)
示例#7
0
    def _setup(self):
        self.cluster_name = self.args.clustername
        assert self.cluster_name is not None

        self.lib_item_name = self.args.libitemname
        assert self.lib_item_name is not None

        self.servicemanager = self.get_service_manager()
        self.client = ClsApiClient(self.servicemanager)
        self.helper = ClsApiHelper(self.client, self.skip_verification)
        # Default VM name
        self.vm_name = 'vm-' + str(generate_random_uuid())
    def setup(self):
        parser = sample_cli.build_arg_parser()
        parser.add_argument('-n',
                            '--vm_name',
                            action='store',
                            help='Name of the testing vm')
        parser.add_argument('-resourcepoolname',
                            '--resourcepoolname',
                            help='The name of the resource pool to be used.')
        parser.add_argument('-libitemname',
                            '--libitemname',
                            help='The name of the library item to deploy.'
                            'The library item should contain an OVF package.')
        parser.add_argument(
            '-vm_count',
            '--vm_count',
            help='Number of VMs to be created. By default is 1',
            type=int,
            default=1)
        args = sample_util.process_cli_args(parser.parse_args())
        self.lib_item_name = args.libitemname
        self.resource_pool_name = args.resourcepoolname
        self.vm_name = args.vm_name
        self.vm_count = args.vm_count

        self.servicemanager = ServiceManager(args.server, args.username,
                                             args.password,
                                             args.skipverification)
        self.servicemanager.connect()
        atexit.register(self.servicemanager.disconnect)

        self.client = ClsApiClient(self.servicemanager)
        self.helper = ClsApiHelper(self.client, args.skipverification)

        # Default VM name
        if not self.vm_name:
            self.vm_name = 'vm-' + str(generate_random_uuid())
    def _setup(self):
        self.datastore_name = self.args.datastorename
        self.cluster_name = self.args.clustername
        self.folder_name = self.args.foldername
        self.datacenter_name = self.args.datacentername
        self.servicemanager = self.get_service_manager()

        self.datastore_id = get_datastore_id(
            service_manager=self.servicemanager,
            datastore_name=self.datastore_name)
        self.client = ClsApiClient(self.servicemanager)
        self.helper = ClsApiHelper(self.client, self.skip_verification)
        session = get_unverified_session() if self.skip_verification else None
        self.vsphere_client = create_vsphere_client(server=self.server,
                                                    username=self.username,
                                                    password=self.password,
                                                    session=session)
        self.folder_id = get_folder(self.vsphere_client, self.datacenter_name,
                                    self.folder_name)
        self.storage_backings = self.helper.create_storage_backings(
            self.servicemanager, self.datastore_name)
        cluster_obj = get_obj(self.servicemanager.content,
                              [vim.ClusterComputeResource], self.cluster_name)
        self.resource_pool_id = cluster_obj.resourcePool._GetMoId()
class VmtxPublish(SampleBase):
    """
    Demonstrates the VMTX push sync workflow to publish and subscribe VMTX items.
    Note: the workflow needs an existing VC datastore with available storage.
    """

    SYNC_TIMEOUT_SEC = 60

    def __init__(self):
        SampleBase.__init__(self, self.__doc__)

        self.servicemanager = None
        self.client = None
        self.helper = None
        self.datastore_name = None
        self.resource_pool_id = None
        self.folder_id = None

        self.pub_libs_to_clean = []
        self.sub_libs_to_clean = []
        self.vms_to_clean = []

    def _options(self):
        self.argparser.add_argument('-datacentername',
                                    '--datacentername',
                                    required=True,
                                    help='The name of the datacenter')
        self.argparser.add_argument('-datastorename',
                                    '--datastorename',
                                    required=True,
                                    help='The name of the datastore.')
        self.argparser.add_argument('-clustername',
                                    '--clustername',
                                    required=True,
                                    help='The name of the cluster to be used.')
        self.argparser.add_argument('-foldername',
                                    '--foldername',
                                    required=True,
                                    help='The name of the folder in the '
                                    'datacenter for creating a subscription')

    def _setup(self):
        self.datastore_name = self.args.datastorename
        self.cluster_name = self.args.clustername
        self.folder_name = self.args.foldername
        self.datacenter_name = self.args.datacentername
        self.servicemanager = self.get_service_manager()

        self.datastore_id = get_datastore_id(
            service_manager=self.servicemanager,
            datastore_name=self.datastore_name)
        self.client = ClsApiClient(self.servicemanager)
        self.helper = ClsApiHelper(self.client, self.skip_verification)
        session = get_unverified_session() if self.skip_verification else None
        self.vsphere_client = create_vsphere_client(server=self.server,
                                                    username=self.username,
                                                    password=self.password,
                                                    session=session)
        self.folder_id = get_folder(self.vsphere_client, self.datacenter_name,
                                    self.folder_name)
        self.storage_backings = self.helper.create_storage_backings(
            self.servicemanager, self.datastore_name)
        cluster_obj = get_obj(self.servicemanager.content,
                              [vim.ClusterComputeResource], self.cluster_name)
        self.resource_pool_id = cluster_obj.resourcePool._GetMoId()

    def _execute(self):
        self.create_new_subscription()
        self.create_subscription_from_existing_subscribed_library()

    def create_new_subscription(self):
        """
        Sample code for creating a new subscription for VMTX templates
        """

        # Create a published library and a new subscription
        pub_lib_name = "pub_lib_new_" + str(uuid.uuid4())
        pub_lib_id = self.create_published_library(pub_lib_name).id
        self.pub_libs_to_clean.append(pub_lib_id)
        sub_lib_name = "sub_lib_new_" + str(uuid.uuid4())
        subscription_id = self.create_subscription_new(pub_lib_id,
                                                       sub_lib_name)

        # Get the subscribed library associated with the subscription
        subscription_info = self.client.subscriptions.get(
            pub_lib_id, subscription_id)
        sub_lib = self.client.library_service.get(
            subscription_info.subscribed_library)
        self.sub_libs_to_clean.append(sub_lib.id)

        # - Create a VMTX item on the published library
        # - Push-synchronize the subscription and verify the sync
        vm_name = "sample_vm_new_" + str(uuid.uuid4())
        vmtx_item_name = "sample_vmtx_item_existing_" + str(uuid.uuid4())
        vmtx_item_id = self.create_vmtx_item(pub_lib_id, vm_name,
                                             vmtx_item_name)
        self.client.local_library_service.publish(pub_lib_id)
        assert self.verify_vmtx_sync(sub_lib, vmtx_item_id)

    def create_subscription_from_existing_subscribed_library(self):
        """
        Sample code for converting existing Subscribed library
        to use a VMTX subscription
        """

        # Create a published library and get its publish URL
        pub_lib_name = "pub_lib_existing_" + str(uuid.uuid4())
        pub_lib = self.create_published_library(pub_lib_name)
        self.pub_libs_to_clean.append(pub_lib.id)
        pub_lib_url = pub_lib.publish_info.publish_url

        # Create a subscribed library
        sub_lib_name = "sub_lib_existing_" + str(uuid.uuid4())
        sub_lib = self.create_subscribed_library(pub_lib_url, sub_lib_name)
        self.create_subscription_for_existing_subscribed_library(
            pub_lib.id, sub_lib.id)

        # - Create a VMTX item on the published library
        # - Push-synchronize the subscription and verify the sync
        vm_name = "sample_vm_existing_" + str(uuid.uuid4())
        vmtx_item_name = "sample_vmtx_item_existing_" + str(uuid.uuid4())
        vmtx_item_id = self.create_vmtx_item(pub_lib.id, vm_name,
                                             vmtx_item_name)
        self.client.local_library_service.publish(pub_lib.id)
        assert self.verify_vmtx_sync(sub_lib, vmtx_item_id)

    def create_vmtx_item(self, pub_lib_id, vm_name, vmtx_item_name):
        # Upload OVF, create a VM, and use that VM to create a VMTX item
        ovf_item_id = self.create_ovf_template_item(pub_lib_id)
        source_vmtx_vm_id = self.create_vm(ovf_item_id, vm_name)
        self.vms_to_clean.append(source_vmtx_vm_id)
        vmtx_item_id = self.create_vmtx_item_from_vm(pub_lib_id,
                                                     source_vmtx_vm_id,
                                                     vmtx_item_name)
        return vmtx_item_id

    def create_published_library(self, pub_lib_name):
        pub_info = PublishInfo()
        pub_info.published = True
        # VMTX sync needs the authentication to be turned off
        pub_info.authentication_method = PublishInfo.AuthenticationMethod.NONE
        pub_spec = LibraryModel()
        pub_spec.name = pub_lib_name
        pub_spec.description = "Sample Published library"
        pub_spec.publish_info = pub_info
        pub_spec.type = pub_spec.LibraryType.LOCAL
        pub_spec.storage_backings = self.storage_backings

        pub_lib_id = self.client.local_library_service.create(
            create_spec=pub_spec, client_token=generate_random_uuid())
        print("Published library created, id: {0}".format(pub_lib_id))

        pub_lib = self.client.library_service.get(pub_lib_id)
        return pub_lib

    def create_subscribed_library(self, pub_lib_url, sub_lib_name):
        # Build the subscription information using the publish URL of the published
        # library

        sub_info = SubscriptionInfo()
        sub_info.authentication_method = SubscriptionInfo.AuthenticationMethod.NONE
        # on_demand = False for library and item level publish
        # on_demand = True for only item level publish, the library level
        #             publish will only sync the item metadata
        sub_info.on_demand = False
        sub_info.automatic_sync_enabled = True
        sub_info.subscription_url = pub_lib_url

        # Build the specification for the subscribed library
        sub_spec = LibraryModel()
        sub_spec.name = sub_lib_name
        sub_spec.type = sub_spec.LibraryType.SUBSCRIBED
        sub_spec.subscription_info = sub_info
        sub_spec.storage_backings = self.storage_backings

        sub_lib_id = self.client.subscribed_library_service.create(
            create_spec=sub_spec, client_token=generate_random_uuid())
        self.sub_libs_to_clean.append(sub_lib_id)
        print("Subscribed library created, id: {0}".format(sub_lib_id))
        sub_lib = self.client.subscribed_library_service.get(sub_lib_id)
        return sub_lib

    def create_subscription_new(self, pub_lib_id, sub_lib_name):
        # Create a new subscription. Such subscription is created on the published
        # library, and can be later used for a push-sync
        #
        # spec
        #   +--subscribed_library
        #        +--target: CREATE_NEW
        #        +--subscribed_library: DO NOT SPECIFY as this is new
        #        +--new_subscribed_library
        #            +--name, description, automatic_sync_enabled, on_demand
        #        +--location: LOCAL/REMOTE
        #        +--subscribed_library_vcenter: (VcenterInfo) DO NOT SPECIFY for location=LOCAL
        #        +--placement:
        #             +--Resource pool and folder for the VM
        #             +--network for the VM

        client_token = str(uuid.uuid4())
        spec = Subscriptions.CreateSpec()
        subscribed_library = Subscriptions.CreateSpecSubscribedLibrary()
        subscribed_library.location = Subscriptions.Location.LOCAL

        subscribed_library.target = \
            Subscriptions.CreateSpecSubscribedLibrary.Target.CREATE_NEW
        new_subscribed_library = Subscriptions.CreateSpecNewSubscribedLibrary()
        new_subscribed_library.name = sub_lib_name
        new_subscribed_library.description = "Sample subscribed library"

        backing = StorageBacking(StorageBacking.Type.DATASTORE,
                                 self.datastore_id)
        new_subscribed_library.storage_backings = [backing]

        new_subscribed_library.automatic_sync_enabled = False
        # on_demand = False for library and item level publish
        # on_demand = True for only item level publish, the library level
        #             publish will only sync the item metadata
        new_subscribed_library.on_demand = False
        subscribed_library.new_subscribed_library = new_subscribed_library

        placement = Subscriptions.CreateSpecPlacement()
        placement.resource_pool = self.resource_pool_id
        placement.folder = self.folder_id

        # Setting network to null implies that the subscription will use the
        # same network as the source VM
        # Warning - this may lead to failure if the same network is not
        # available to the subscriber
        placement.network = None

        subscribed_library.placement = placement
        spec.subscribed_library = subscribed_library

        subscription_id = self.client.subscriptions.create(
            pub_lib_id, spec, client_token)
        print("Subscription created, id: {0}".format(subscription_id))
        return subscription_id

    def create_subscription_for_existing_subscribed_library(
            self, pub_lib_id, sub_lib_id):
        # Create a subscription for an existing subscribed library. This subscription
        # and can be later used for a push-sync to that subscribed library
        #
        # spec
        #   +--subscribed_library
        #        +--target: USE_EXISTING
        #        +--subscribed_library: ID of existing subscribed library
        #        +--new_subscribed_library: DO NOT SPECIFY for target=USE_EXISTING
        #        +--location: LOCAL/REMOTE
        #        +--subscribed_library_vcenter: (VcenterInfo) DO NOT SPECIFY from location=LOCAL
        #        +--placement:
        #             +--Resource pool and folder for the VM
        #             +--network for the VM

        client_token = str(uuid.uuid4())
        spec = Subscriptions.CreateSpec()
        subscribed_library = Subscriptions.CreateSpecSubscribedLibrary()

        subscribed_library.target = \
            Subscriptions.CreateSpecSubscribedLibrary.Target.USE_EXISTING
        subscribed_library.subscribed_library = sub_lib_id
        subscribed_library.location = "LOCAL"
        placement = Subscriptions.CreateSpecPlacement()
        placement.resource_pool = self.resource_pool_id
        placement.folder = self.folder_id

        # Setting network to null implies that the subscription will use the
        # same network as the source VM
        # Warning - this may lead to failure if the same network is not
        # available to the subscriber
        placement.network = None

        subscribed_library.placement = placement
        spec.subscribed_library = subscribed_library

        subscription_id = self.client.subscriptions.create(
            pub_lib_id, spec, client_token)
        print("Subscription created id: {0}".format(subscription_id))
        return subscription_id

    def create_ovf_template_item(self, library_id):
        # Create an OVF item
        ovf_item_id = self.helper.create_library_item(
            library_id=library_id,
            item_name='sample-ovf-item',
            item_description='Sample OVF template',
            item_type='ovf')
        print('Library item created id: {0}'.format(ovf_item_id))

        # Upload a VM template to the CL
        ovf_files_map = self.helper.get_ovf_files_map(
            ClsApiHelper.SIMPLE_OVF_RELATIVE_DIR)
        self.helper.upload_files(library_item_id=ovf_item_id,
                                 files_map=ovf_files_map)
        return ovf_item_id

    def create_vm(self, ovf_item_id, vm_name):
        # Deploy a VM using the given ovf template
        deployment_target = LibraryItem.DeploymentTarget(
            resource_pool_id=self.resource_pool_id)
        ovf_summary = self.client.ovf_lib_item_service.filter(
            ovf_library_item_id=ovf_item_id, target=deployment_target)
        vm_id = self.deploy_ovf_template(ovf_item_id, ovf_summary,
                                         deployment_target, vm_name)
        print("Virtual Machine created, id: {0}".format(vm_id))
        return vm_id

    def deploy_ovf_template(self, lib_item_id, ovf_summary, deployment_target,
                            vm_name):
        # Build the deployment spec
        deployment_spec = LibraryItem.ResourcePoolDeploymentSpec(
            name=vm_name,
            annotation=ovf_summary.annotation,
            accept_all_eula=True)

        # Deploy the ovf template
        result = self.client.ovf_lib_item_service.deploy(
            lib_item_id,
            deployment_target,
            deployment_spec,
            client_token=generate_random_uuid())
        if result.succeeded:
            vm_id = result.resource_id.id
            return vm_id
        else:
            print('Deployment failed.')
            for error in result.error.errors:
                print('OVF error: {}'.format(error.message))
            raise Exception('OVF deploy failed.')

    def create_vmtx_item_from_vm(self, library_id, source_vm_id,
                                 vmtx_item_name):
        # Create a VMTX item using the given VM as source
        create_spec = VmtxLibraryItem.CreateSpec()
        create_spec.source_vm = source_vm_id
        create_spec.library = library_id
        create_spec.name = vmtx_item_name
        create_spec.description = 'sample-vmtx-description'
        create_spec.placement = VmtxLibraryItem.CreatePlacementSpec()
        create_spec.placement.resource_pool = self.resource_pool_id
        vmtx_item_id = self.client.vmtx_service.create(create_spec)
        print("VMTX item created id: {0}".format(vmtx_item_id))
        return vmtx_item_id

    def verify_vmtx_sync(self, sub_lib, vmtx_item_id):
        # Wait until the VMTX item in the subscription is synchronized with
        # the one in the published library

        start_time = time.time()
        while time.time() - start_time < self.SYNC_TIMEOUT_SEC:
            sub_item_ids = self.client.library_item_service.list(sub_lib.id)
            # Only vmtx item will be synced using the push mechanism, so check
            # the length to be one
            if len(sub_item_ids) == 1:
                source_id = self.client.library_item_service.get(
                    sub_item_ids[0]).source_id
                # Verify that the source for the VMTX item in the subscribed
                # library is the VMTX item in the published library
                if source_id == vmtx_item_id:
                    return True
                else:
                    print("VMTX source item id mismatch")
                    return False
            # Give some more time for sync
            time.sleep(1)

        print("Timed out while waiting for sync")
        return False

    def _cleanup(self):
        for lib_id in self.pub_libs_to_clean:
            print("deleting published library: {0}".format(lib_id))
            self.client.local_library_service.delete(lib_id)
        for lib_id in self.sub_libs_to_clean:
            print("deleting subscribed library: {0}".format(lib_id))
            self.client.subscribed_library_service.delete(lib_id)
        for vm_id in self.vms_to_clean:
            vm_obj = get_obj_by_moId(self.servicemanager.content,
                                     [vim.VirtualMachine], vm_id)
            delete_object(self.servicemanager.content, vm_obj)
class DeployOvfTemplate:
    """
    Demonstrates the workflow to deploy an OVF library item to a resource pool.
    Note: the sample needs an existing library item with an OVF template
    and an existing cluster with resources for deploying the VM.
    """
    def __init__(self):
        self.servicemanager = None
        self.client = None
        self.helper = None
        self.resource_pool_name = None
        self.lib_item_name = None
        self.vm_obj = None
        self.vm_name = None
        self.vm_count = None

    def setup(self):
        parser = sample_cli.build_arg_parser()
        parser.add_argument('-n',
                            '--vm_name',
                            action='store',
                            help='Name of the testing vm')
        parser.add_argument('-resourcepoolname',
                            '--resourcepoolname',
                            help='The name of the resource pool to be used.')
        parser.add_argument('-libitemname',
                            '--libitemname',
                            help='The name of the library item to deploy.'
                            'The library item should contain an OVF package.')
        parser.add_argument(
            '-vm_count',
            '--vm_count',
            help='Number of VMs to be created. By default is 1',
            type=int,
            default=1)
        args = sample_util.process_cli_args(parser.parse_args())
        self.lib_item_name = args.libitemname
        self.resource_pool_name = args.resourcepoolname
        self.vm_name = args.vm_name
        self.vm_count = args.vm_count

        self.servicemanager = ServiceManager(args.server, args.username,
                                             args.password,
                                             args.skipverification)
        self.servicemanager.connect()
        atexit.register(self.servicemanager.disconnect)

        self.client = ClsApiClient(self.servicemanager)
        self.helper = ClsApiHelper(self.client, args.skipverification)

        # Default VM name
        if not self.vm_name:
            self.vm_name = 'vm-' + str(generate_random_uuid())

    def execute(self):

        # Find the resource pool's moid
        resource_pool_obj = get_obj(self.servicemanager.content,
                                    [vim.ResourcePool],
                                    self.resource_pool_name)
        assert resource_pool_obj is not None
        print("Resource Pool Moref: {0}".format(resource_pool_obj))

        deployment_target = LibraryItem.DeploymentTarget(
            resource_pool_id=resource_pool_obj._GetMoId())
        lib_item_id = self.helper.get_item_id_by_name(self.lib_item_name)
        assert lib_item_id
        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)

    def deploy_ovf_template(self, lib_item_id, ovf_summary, deployment_target):
        # 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.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. Result resource: {0}, ID: {1}'.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))

            # 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)

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

    def cleanup(self):
        if self.vm_obj is not None:
            # Power off the VM and wait for the power off operation to complete
            poweroff_vm(self.servicemanager.content, self.vm_obj)
            # Delete the VM
            delete_object(self.servicemanager.content, self.vm_obj)
示例#12
0
class CreateVmTemplate(SampleBase):
    """
    Demonstrates how to create a library item containing a virtual machine
    template from a virtual machine.

    Prerequisites:
        - A virtual machine
        - A datacenter
        - A resource pool
        - A datastore
    """
    def __init__(self):
        SampleBase.__init__(self, self.__doc__)
        self.servicemanager = None
        self.client = None
        self.helper = None
        self.vm_name = None
        self.datastore_name = None
        self.library_name = 'demo-vmtx-lib'
        self.item_name = None
        self.item_id = None

    def _options(self):
        self.argparser.add_argument('-vmname',
                                    '--vmname',
                                    required=True,
                                    help='The name of the source VM from '
                                    'which to create a library item')
        self.argparser.add_argument('-datacentername',
                                    '--datacentername',
                                    required=True,
                                    help='The name of the datacenter in which '
                                    'to place the VM template')
        self.argparser.add_argument('-resourcepoolname',
                                    '--resourcepoolname',
                                    required=True,
                                    help='The name of the resource pool in '
                                    'the datacenter in which to place '
                                    'the VM template')
        self.argparser.add_argument('-datastorename',
                                    '--datastorename',
                                    required=True,
                                    help='The name of the datastore in which '
                                    'to create a library and VM template')
        self.argparser.add_argument('-itemname',
                                    '--itemname',
                                    help='The name of the library item to '
                                    'create. The item will contain a '
                                    'VM template.')

    def _setup(self):
        # Required arguments
        self.vm_name = self.args.vmname
        self.datacenter_name = self.args.datacentername
        self.resource_pool_name = self.args.resourcepoolname
        self.datastore_name = self.args.datastorename

        # Optional arguments
        self.item_name = (self.args.itemname
                          if self.args.itemname else rand('vmtx-item-'))

        self.servicemanager = self.get_service_manager()
        self.client = ClsApiClient(self.servicemanager)
        self.helper = ClsApiHelper(self.client, self.skip_verification)

        session = get_unverified_session() if self.skip_verification else None
        self.vsphere_client = create_vsphere_client(server=self.server,
                                                    username=self.username,
                                                    password=self.password,
                                                    session=session)

    def _execute(self):
        # Get the identifiers
        vm_id = get_vm(self.vsphere_client, self.vm_name)
        assert vm_id
        resource_pool_id = get_resource_pool(self.vsphere_client,
                                             self.datacenter_name,
                                             self.resource_pool_name)
        assert resource_pool_id

        # Create a library
        storage_backings = self.helper.create_storage_backings(
            self.servicemanager, self.datastore_name)
        self.library_id = self.helper.create_local_library(
            storage_backings, self.library_name)

        # Build the create specification
        create_spec = VmtxLibraryItem.CreateSpec()
        create_spec.source_vm = vm_id
        create_spec.library = self.library_id
        create_spec.name = self.item_name
        create_spec.placement = VmtxLibraryItem.CreatePlacementSpec(
            resource_pool=resource_pool_id)

        # Create a new library item from the source VM
        self.item_id = self.client.vmtx_service.create(create_spec)
        print("Created VM template item '{0}' with ID: {1}".format(
            self.item_name, self.item_id))

        # Retrieve the library item info
        info = self.client.vmtx_service.get(self.item_id)
        print('VM template guest OS: {0}'.format(info.guest_os))

    def _cleanup(self):
        if self.library_id:
            self.client.local_library_service.delete(self.library_id)
            print('Deleted library ID: {0}'.format(self.library_id))
示例#13
0
class LibraryPublishSubscribe(SampleBase):
    """
    Demonstrates the basic sync workflow to publish and subscribe content libraries.
    Note: the workflow needs an existing VC datastore with available storage.
    """
    VCSP_USERNAME = '******'
    DEMO_PASSWORD = '******'
    SYNC_TIMEOUT_SEC = 60
    DEMO_FILENAME = 'test.iso'

    def __init__(self):
        SampleBase.__init__(self, self.__doc__)
        self.servicemanager = None
        self.client = None
        self.helper = None
        self.datastore_name = None
        self.pub_lib_name = "demo-publib"
        self.sub_lib_name = "demo-sublib"
        self.pub_lib_id = None
        self.sub_lib_id = None

    def _options(self):
        self.argparser.add_argument('-datastorename',
                                    '--datastorename',
                                    help='The name of the datastore.')

    def _setup(self):
        self.datastore_name = self.args.datastorename
        assert self.datastore_name is not None

        self.servicemanager = self.get_service_manager()
        self.client = ClsApiClient(self.servicemanager)
        self.helper = ClsApiHelper(self.client, self.skip_verification)

    def _execute(self):
        storage_backings = self.helper.create_storage_backings(
            self.servicemanager, self.datastore_name)

        # Create a published library backed the VC datastore using vAPIs
        self.pub_lib_id = self.create_published_library(storage_backings)
        assert self.pub_lib_id is not None
        print('Published library created: ID: {0}'.format(self.pub_lib_id))
        pub_lib = self.client.local_library_service.get(self.pub_lib_id)
        pub_lib_url = pub_lib.publish_info.publish_url
        assert pub_lib_url is not None
        print('Publish URL : {0}'.format(pub_lib_url))

        # Create a library item in the published library
        pub_lib_item_id = self.helper.create_iso_library_item(
            self.pub_lib_id, 'item_1', self.DEMO_FILENAME)
        assert self.client.library_item_service.get(
            pub_lib_item_id) is not None

        # Create the subscribed library
        sub_lib, sub_spec = self.create_subcribed_library(
            storage_backings, pub_lib_url)
        assert self.sub_lib_id is not None
        print('Subscribed library created: ID: {0}'.format(self.sub_lib_id))

        # It is not mandatory to verify sync, it is just for demonstrating the sample workflow.
        assert (ClsSyncHelper(self.client,
                              self.SYNC_TIMEOUT_SEC).verify_library_sync(
                                  self.pub_lib_id, sub_lib))
        sub_lib = self.client.subscribed_library_service.get(self.sub_lib_id)
        print('Subscribed library synced : {0}'.format(sub_lib.last_sync_time))

        sub_item_ids = self.client.library_item_service.list(self.sub_lib_id)
        assert len(sub_item_ids) == 1, 'Subscribed library must have one item'

        # Add another item to the published library
        self.helper.create_iso_library_item(self.pub_lib_id, 'item_2',
                                            self.DEMO_FILENAME)

        # Manually synchronize the subscribed library to get the latest changes immediately.
        self.client.subscribed_library_service.sync(self.sub_lib_id)
        # It is not mandatory to verify sync, it is just for demonstrating the sample workflow.
        assert (ClsSyncHelper(self.client,
                              self.SYNC_TIMEOUT_SEC).verify_library_sync(
                                  self.pub_lib_id, sub_lib))
        sub_lib = self.client.subscribed_library_service.get(self.sub_lib_id)
        print('Subscribed library synced : {0}'.format(sub_lib.last_sync_time))

        # List the subscribed items.
        sub_item_ids = self.client.library_item_service.list(self.sub_lib_id)
        assert len(sub_item_ids) == 2, 'Subscribed library must have two items'
        for sub_item_id in sub_item_ids:
            sub_item = self.client.library_item_service.get(sub_item_id)
            print('Subscribed item : {0}'.format(sub_item.name))

        # Change the subscribed library to be on-demand
        sub_spec.subscription_info.on_demand = True
        self.client.subscribed_library_service.update(self.sub_lib_id,
                                                      sub_spec)

        # Evict the cached content of the first subscribed library item
        self.client.subscribed_item_service.evict(sub_item_id)
        sub_item = self.client.library_item_service.get(sub_item_id)
        print('Subscribed item evicted : {0}'.format(sub_item.name))
        assert not sub_item.cached, 'Subscribed item must not be cached'

        # Force synchronize the subscribed library item to fetch and cache the content
        self.client.subscribed_item_service.sync(sub_item_id, True)
        # It is not mandatory to verify sync, it is just for demonstrating the sample workflow.
        assert (ClsSyncHelper(
            self.client, self.SYNC_TIMEOUT_SEC).verify_item_sync(sub_item_id))
        sub_item = self.client.library_item_service.get(sub_item_id)
        print('Subscribed item force sync : {0}'.format(sub_item.name))
        assert sub_item.cached, 'Subscribed item must be cached'

    def create_published_library(self, storage_backings):
        # Build the authenticated publish info.
        # Note: The username will be 'vcsp'.
        pub_info = PublishInfo()
        pub_info.published = True
        pub_info.authentication_method = PublishInfo.AuthenticationMethod.BASIC
        pub_info.password = self.DEMO_PASSWORD

        # Build the specification for the published library to be created
        pub_spec = LibraryModel()
        pub_spec.name = self.pub_lib_name
        pub_spec.description = "Published library backed by VC datastore"
        pub_spec.publish_info = pub_info
        pub_spec.type = pub_spec.LibraryType.LOCAL
        pub_spec.storage_backings = storage_backings

        pub_lib_id = self.client.local_library_service.create(
            create_spec=pub_spec, client_token=generate_random_uuid())

        return pub_lib_id

    def create_subcribed_library(self, storage_backings, pub_lib_url):
        # Build the subscription information using the publish URL of the published
        # library. The username must be 'vcsp'.
        sub_info = SubscriptionInfo()
        sub_info.authentication_method = SubscriptionInfo.AuthenticationMethod.BASIC
        sub_info.user_name = self.VCSP_USERNAME
        sub_info.password = self.DEMO_PASSWORD
        sub_info.on_demand = False
        sub_info.automatic_sync_enabled = True
        sub_info.subscription_url = pub_lib_url

        # Build the specification for the subscribed library
        sub_spec = LibraryModel()
        sub_spec.name = self.sub_lib_name
        sub_spec.type = sub_spec.LibraryType.SUBSCRIBED
        sub_spec.subscription_info = sub_info
        sub_spec.storage_backings = storage_backings

        self.sub_lib_id = self.client.subscribed_library_service.create(
            create_spec=sub_spec, client_token=generate_random_uuid())
        sub_lib = self.client.subscribed_library_service.get(self.sub_lib_id)
        return sub_lib, sub_spec

    def _cleanup(self):
        if self.sub_lib_id:
            self.client.subscribed_library_service.delete(self.sub_lib_id)
            print('Deleted subscribed library Id: {0}'.format(self.sub_lib_id))

        if self.pub_lib_id:
            self.client.local_library_service.delete(self.pub_lib_id)
            print('Deleted published library Id : {0}'.format(self.pub_lib_id))
    def _setup(self):
        self.servicemanager = self.get_service_manager()

        self.client = ClsApiClient(self.servicemanager)
        self.helper = ClsApiHelper(self.client, self.skip_verification)
class SignedOvaImport(SampleBase):
    """
    Demonstrates the workflow to import an OVA file into the content library,
    as an OVF library item.

    Note: the workflow needs an existing VC DS with available storage.
    """

    #SIGNED_OVA_FILENAME = 'nostalgia-signed.ova'
    #    SIGNED_OVA_FILENAME = 'IoTC_VA-2.0.2.12565-32613116_OVF10.ova'
    #    SIGNED_OVA_RELATIVE_DIR = '../resources/signedOvaWithCertWarning/'

    def __init__(self):
        SampleBase.__init__(self, self.__doc__)
        self.servicemanager = None
        self.client = None
        self.helper = None
        self.datastore_name = None
        #self.lib_name = 'Pulse_Content_sb'
        self.local_lib_id = None
        self.lib_item_name = None
        self.lib_item_id = None

    def _options(self):
        self.argparser.add_argument('-datastorename',
                                    '--datastorename',
                                    required=True,
                                    help='The name of the datastore.')
        self.argparser.add_argument(
            '-libitemname',
            '--libitemname',
            required=True,
            help='The name of the Library Item Inside Content Library.')
        self.argparser.add_argument(
            '-locallibid',
            '--locallibid',
            required=True,
            help='The ID of Local Library to which the OVA has to be linked.')
        self.argparser.add_argument('-ovaname',
                                    '--ovaname',
                                    required=True,
                                    help='Name of the OVA.')
        self.argparser.add_argument('-ovapath',
                                    '--ovapath',
                                    required=True,
                                    help='Path to the OVA.')

    def _setup(self):
        self.servicemanager = self.get_service_manager()

        self.client = ClsApiClient(self.servicemanager)
        self.helper = ClsApiHelper(self.client, self.skip_verification)

    def _execute(self):
        # Build the storage backing for the library to be created using given datastore name
        self.datastore_name = self.args.datastorename
        storage_backings = self.helper.create_storage_backings(
            service_manager=self.servicemanager,
            datastore_name=self.datastore_name)
        #Assigning Library Item Name
        self.lib_item_name = self.args.libitemname
        # Create a local content library backed by the VC datastore using vAPIs
        #self.local_lib_id = self.helper.create_local_library(storage_backings, self.lib_name)
        self.local_lib_id = self.args.locallibid

        # Create a new library item in the content library for uploading the files
        self.lib_item_id = self.helper.create_library_item(
            library_id=self.local_lib_id,
            item_name=self.lib_item_name,
            item_description='Pulse OVA',
            item_type='ovf')
        print('Library item created. ID: {0}'.format(self.lib_item_id))
        #Assigning OVA name and Path
        self.SIGNED_OVA_FILENAME = self.args.ovaname
        self.SIGNED_OVA_RELATIVE_DIR = self.args.ovapath

        ova_file_map = self.helper.get_ova_file_map(
            self.SIGNED_OVA_RELATIVE_DIR,
            local_filename=self.SIGNED_OVA_FILENAME)
        # Create a new upload session for uploading the files
        # To ignore expected warnings and skip preview info check,
        # you can set create_spec.warning_behavior during session creation
        session_id = self.client.upload_service.create(
            create_spec=UpdateSessionModel(library_item_id=self.lib_item_id),
            client_token=generate_random_uuid())
        self.helper.upload_files_in_session(ova_file_map, session_id)

        # Wait for terminal preview state and obtain preview warnings if any
        #self.wait_for_terminal_preview_state(session_id, AVAILABLE)
        self.wait_for_terminal_preview_state(session_id, AVAILABLE)
        session = self.client.upload_service.get(session_id)
        preview_info = session.preview_info

        # Collect generated preview warning types
        preview_warning_types = []
        print('Preview warnings for the session are the following:')
        for preview_warning in preview_info.warnings:
            print(preview_warning.message.default_message)
            preview_warning_types.append(preview_warning.type)

        # Ignore preview warnings on session
        ignore_warning_behaviors = []
        for warning_type in preview_warning_types:
            warning_behavior = WarningBehavior(type=warning_type, ignored=True)
            ignore_warning_behaviors.append(warning_behavior)
        self.client.upload_service.update(
            session_id,
            update_spec=UpdateSessionModel(
                warning_behavior=ignore_warning_behaviors))
        print(
            'All preview warnings are ignored, proceeding to complete the session'
        )

        self.client.upload_service.complete(session_id)
        self.client.upload_service.delete(session_id)
        print(
            'Uploaded ova file as an ovf template to library item {0}'.format(
                self.lib_item_id))

    def wait_for_terminal_preview_state(self,
                                        session_id,
                                        expected_terminal_preview_state,
                                        timeout_sec=300):
        """
        Periodically checks update session for preview state to reach a terminal state.

        :param session_id: ID of update session for which preview state is checked
        :param expected_terminal_preview_state: expected terminal preview state
        :param timeout_sec: number of seconds to wait before timing out
        """
        preview_state = None
        start_time = time.time()
        terminal_preview_state_list = [NOT_APPLICABLE, AVAILABLE]
        while (time.time() - start_time) < timeout_sec:
            session = self.client.upload_service.get(session_id)
            if session.state == 'ERROR':
                raise Exception(
                    'Session is in error state, error message: {}'.format(
                        session.error_message))
            preview_state = session.preview_info.state
            # check if preview state is in one of the terminal states
            if preview_state not in terminal_preview_state_list:
                time.sleep(1)
            else:
                break

        if preview_state != expected_terminal_preview_state:
            raise Exception(
                'Preview state did not reach expected {} state, actual preview state: '
                '{}'.format(expected_terminal_preview_state, preview_state))

    def _cleanup(self):
        if self.local_lib_id:
            self.client.local_library_service.delete(
                library_id=self.local_lib_id)
            print('Deleted library ID: {0}'.format(self.local_lib_id))
示例#16
0
class DeployVmTemplate(SampleBase):
    """
    Demonstrates how to deploy a virtual machine from a library item containing
    a virtual machine template.

    Prerequisites:
        - A library item containing a virtual machine template
        - A datacenter
        - A VM folder
        - A resource pool
        - A datastore
    """

    def __init__(self):
        SampleBase.__init__(self, self.__doc__)
        self.servicemanager = None
        self.client = None
        self.helper = None
        self.item_name = None
        self.datacenter_name = None
        self.folder_name = None
        self.resource_pool_name = None
        self.datastore_name = None
        self.vm_name = None
        self.vm_id = None
        self.vm = None

    def _options(self):
        self.argparser.add_argument('-itemname', '--itemname',
                                    required=True,
                                    help='The name of the library item '
                                         'containing a VM template to be '
                                         'deployed')
        self.argparser.add_argument('-datacentername', '--datacentername',
                                    required=True,
                                    help='The name of the datacenter in which '
                                         'to deploy a VM')
        self.argparser.add_argument('-foldername', '--foldername',
                                    required=True,
                                    help='The name of the VM folder in the '
                                         'datacenter in which to place the '
                                         'deployed VM')
        self.argparser.add_argument('-resourcepoolname', '--resourcepoolname',
                                    required=True,
                                    help='The name of the resource pool in '
                                         'the datacenter in which to place '
                                         'the deployed VM')
        self.argparser.add_argument('-datastorename', '--datastorename',
                                    required=True,
                                    help='The name of the datastore to store '
                                         'the deployed VM home and disks')
        self.argparser.add_argument('-vmname', '--vmname',
                                    help='The name of the deployed VM')

    def _setup(self):
        # Required arguments
        self.item_name = self.args.itemname
        self.datacenter_name = self.args.datacentername
        self.folder_name = self.args.foldername
        self.resource_pool_name = self.args.resourcepoolname
        self.datastore_name = self.args.datastorename

        # Optional arguments
        self.vm_name = self.args.vmname if self.args.vmname else rand('vm-')

        self.servicemanager = self.get_service_manager()
        self.client = ClsApiClient(self.servicemanager)
        self.helper = ClsApiHelper(self.client, self.skip_verification)

        session = get_unverified_session() if self.skip_verification else None
        self.vsphere_client = create_vsphere_client(server=self.server,
                                                    username=self.username,
                                                    password=self.password,
                                                    session=session)

    def _execute(self):
        # Get the identifiers of the resources used for deployment
        item_id = self.helper.get_item_id_by_name(self.item_name)
        assert item_id
        folder_id = get_folder(self.vsphere_client,
                               self.datacenter_name,
                               self.folder_name)
        assert folder_id
        resource_pool_id = get_resource_pool(self.vsphere_client,
                                             self.datacenter_name,
                                             self.resource_pool_name)
        assert resource_pool_id
        datastore_id = get_datastore_id(self.servicemanager,
                                        self.datastore_name)
        assert datastore_id

        # Build the deployment specification
        placement_spec = VmtxLibraryItem.DeployPlacementSpec(
            folder=folder_id,
            resource_pool=resource_pool_id)
        vm_home_storage_spec = VmtxLibraryItem.DeploySpecVmHomeStorage(
            datastore=datastore_id)
        disk_storage_spec = VmtxLibraryItem.DeploySpecDiskStorage(
            datastore=datastore_id)
        deploy_spec = VmtxLibraryItem.DeploySpec(
            name=self.vm_name,
            placement=placement_spec,
            vm_home_storage=vm_home_storage_spec,
            disk_storage=disk_storage_spec)

        # Deploy a virtual machine from the VM template item
        self.vm_id = self.client.vmtx_service.deploy(item_id, deploy_spec)
        self.vm = get_obj_by_moId(self.servicemanager.content,
                                  [vim.VirtualMachine], self.vm_id)
        print("Deployed VM '{0}' with ID: {1}".format(self.vm.name,
                                                      self.vm_id))

        # Print a summary of the deployed VM
        vm_summary = self.vm.summary.config
        print('Guest OS: {0}'.format(vm_summary.guestId))
        print('{0} CPU(s)'.format(vm_summary.numCpu))
        print('{0} MB memory'.format(vm_summary.memorySizeMB))
        print('{0} disk(s)'.format(vm_summary.numVirtualDisks))
        print('{0} network adapter(s)'.format(vm_summary.numEthernetCards))

    def _cleanup(self):
        if self.vm:
            delete_object(self.servicemanager.content, self.vm)
示例#17
0
class CaptureVMTemplateToContentLibrary(SampleBase):
    """
    Demonstrates the workflow to capture a virtual machine into a content library.

    Note: The sample needs an existing virtual machine to capture.
    """
    def __init__(self):
        SampleBase.__init__(self, self.__doc__)
        self.servicemanager = None
        self.datastore_name = None
        self.datastore_id = None
        self.cl_name = "LocalLibraryToCapture"
        self.vm_name = None
        self.vm_template_name = 'CapturedOvf'
        self.vm_template_description = 'Captured OVF description'
        self.deployable_resource_type = 'VirtualMachine'  # Substitute 'VirtualApp' for vApp

        self.content_library = None
        self.library_item_id = None

    def _options(self):
        self.argparser.add_argument('-datastorename',
                                    '--datastorename',
                                    required=True,
                                    help='The name of the datastore for'
                                    ' content library backing (of type vmfs)')
        self.argparser.add_argument('-vmname',
                                    '--vmname',
                                    required=True,
                                    help='Name of the VM to be captured')

    def _setup(self):
        self.datastore_name = self.args.datastorename
        assert self.datastore_name is not 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.client = ClsApiClient(self.servicemanager)
        self.helper = ClsApiHelper(self.client, self.skip_verification)

        session = get_unverified_session() if self.skip_verification else None
        self.vsphere_client = create_vsphere_client(server=self.server,
                                                    username=self.username,
                                                    password=self.password,
                                                    session=session)

    def _execute(self):
        storage_backings = self.helper.create_storage_backings(
            self.servicemanager, self.datastore_name)

        print('Creating Content Library')
        # Create a content library
        library_id = self.helper.create_local_library(storage_backings,
                                                      self.cl_name)
        self.content_library = self.client.local_library_service.get(
            library_id)

        vm_id = get_vm(self.vsphere_client, self.vm_name)
        assert vm_id is not None

        param = self.create_capture_param(self.content_library,
                                          self.vm_template_name,
                                          self.vm_template_description)
        self.library_item_id = self.capture_source_vm(vm_id, param)
        assert self.library_item_id is not None
        assert self.client.library_item_service.get(
            self.library_item_id) is not None
        print(
            'The VM id : {0} is captured as vm template library item id : {1}'.
            format(vm_id, self.library_item_id))

    def capture_source_vm(self, vm_id, param):
        source = LibraryItem.DeployableIdentity(self.deployable_resource_type,
                                                vm_id)
        result = self.client.ovf_lib_item_service.create(
            source,
            param["target"],
            param["spec"],
            client_token=generate_random_uuid())
        return result.ovf_library_item_id

    def create_capture_param(self, library, name, description):
        spec = LibraryItem.CreateSpec(name=name, description=description)
        target = LibraryItem.CreateTarget(library_id=library.id,
                                          library_item_id=None)
        return {"target": target, "spec": spec}

    def _cleanup(self):
        # delete the local library.
        if self.content_library is not None:
            self.client.local_library_service.delete(
                library_id=self.content_library.id)
            print('Deleted Library Id: {0}'.format(self.content_library.id))
示例#18
0
class ContentUpdate(SampleBase):
    """
    Demonstrates the workflow of updating a content library item.

    Note: the workflow needs an existing datastore (of type vmfs) with available storage.
    """

    ISO_FILE_1 = 'test.iso'
    ISO_FILE_2 = 'test-2.iso'
    ISO_ITEM_NAME = 'test'

    def __init__(self):
        SampleBase.__init__(self, self.__doc__)
        self.servicemanager = None
        self.client = None
        self.helper = None
        self.datastore_name = None
        self.lib_name = "demo-lib"
        self.local_library = None

    def _options(self):
        self.argparser.add_argument('-datastorename',
                                    '--datastorename',
                                    help='The name of the datastore where '
                                    'the library will be created.')

    def _setup(self):
        self.datastore_name = self.args.datastorename
        assert self.datastore_name is not None

        self.servicemanager = self.get_service_manager()
        self.client = ClsApiClient(self.servicemanager)
        self.helper = ClsApiHelper(self.client, self.skip_verification)

    def _execute(self):
        storage_backings = self.helper.create_storage_backings(
            self.servicemanager, self.datastore_name)

        library_id = self.helper.create_local_library(storage_backings,
                                                      self.lib_name)
        self.local_library = self.client.local_library_service.get(library_id)
        self.delete_and_upload_scenario(library_id)
        self.replace_scenario(library_id)

    def replace_scenario(self, library_id):
        """
        :param library_id: the Iso item will be created, and then replaced in this library
        :return: None

        Content update scenario 2:
        Update ISO library item by creating an update session for the
        item, then adding the new ISO file using the same session file
        name into the update session, which will replace the existing
        ISO file upon session complete.
        """

        iso_item_id = self.helper.create_library_item(
            library_id=library_id,
            item_name=self.ISO_ITEM_NAME,
            item_description='Sample iso file',
            item_type='iso')
        print('ISO Library item version (on creation) {0}:'.format(
            self.get_item_version(iso_item_id)))

        iso_files_map = self.helper.get_iso_file_map(
            item_filename=self.ISO_FILE_1, disk_filename=self.ISO_FILE_1)
        self.helper.upload_files(library_item_id=iso_item_id,
                                 files_map=iso_files_map)
        original_version = self.get_item_version(iso_item_id)
        print('ISO Library item version (on original content upload) {0}:'.
              format(original_version))

        session_id = self.client.upload_service.create(
            create_spec=UpdateSessionModel(library_item_id=iso_item_id),
            client_token=generate_random_uuid())
        # Use the same item filename (update endpoint, as it's a replace scenario)
        iso_files_map = self.helper.get_iso_file_map(
            item_filename=self.ISO_FILE_1, disk_filename=self.ISO_FILE_2)

        self.helper.upload_files_in_session(iso_files_map, session_id)
        self.client.upload_service.complete(session_id)
        self.client.upload_service.delete(session_id)
        updated_version = self.get_item_version(iso_item_id)
        print('ISO Library item version (after content update): {0}'.format(
            updated_version))
        assert updated_version > original_version, 'content update should increase the version'

    def delete_and_upload_scenario(self, library_id):
        """
        :param library_id: the OVF item will be created and updated in this library
        :return: None

        Content update scenario 1:
        Update OVF library item by creating an update session for the
        OVF item, removing all existing files in the session, then
        adding all new files into the same update session, and completing
        the session to finish the content update.
        """

        # Create a new library item in the content library for uploading the files
        ovf_item_id = self.helper.create_library_item(
            library_id=library_id,
            item_name='demo-ovf-item',
            item_description='Sample simple VM template',
            item_type='ovf')
        assert ovf_item_id is not None
        print('Library item created id: {0}'.format(ovf_item_id))
        print('OVF Library item version (at creation) {0}:'.format(
            self.get_item_version(ovf_item_id)))

        # Upload a VM template to the CL
        ovf_files_map = self.helper.get_ovf_files_map(
            ClsApiHelper.SIMPLE_OVF_RELATIVE_DIR)
        self.helper.upload_files(library_item_id=ovf_item_id,
                                 files_map=ovf_files_map)
        print('Uploaded ovf and vmdk files to library item {0}'.format(
            ovf_item_id))
        original_version = self.get_item_version(ovf_item_id)
        print('OVF Library item version (on original content upload): {0}'.
              format(original_version))

        # Create a new session and perform content update
        session_id = self.client.upload_service.create(
            create_spec=UpdateSessionModel(library_item_id=ovf_item_id),
            client_token=generate_random_uuid())
        existing_files = self.client.upload_file_service.list(session_id)
        for file in existing_files:
            print('deleting {0}'.format(file.name))
            self.client.upload_file_service.remove(session_id, file.name)
        ovf_files_map = self.helper.get_ovf_files_map(
            ovf_location=ClsApiHelper.PLAIN_OVF_RELATIVE_DIR)
        self.helper.upload_files_in_session(ovf_files_map, session_id)
        self.client.upload_service.complete(session_id)
        self.client.upload_service.delete(session_id)
        updated_version = self.get_item_version(ovf_item_id)
        print('OVF Library item version (after content update): {0}'.format(
            updated_version))
        assert updated_version > original_version, 'content update should increase the version'

    def get_item_version(self, item_id):
        ovf_item_model = self.client.library_item_service.get(item_id)
        pre_update_version = ovf_item_model.content_version
        return pre_update_version

    def _cleanup(self):
        if self.local_library:
            self.client.local_library_service.delete(
                library_id=self.local_library.id)
            print('Deleted Library Id: {0}'.format(self.local_library.id))
示例#19
0
class IsoMount(SampleBase):
    """
    Demonstrates the content library ISO item mount and
    unmount workflow via the mount and unmount APIs from the
    ISO service.
    """

    ISO_FILENAME = 'test.iso'

    def __init__(self):
        SampleBase.__init__(self, self.__doc__)
        self.servicemanager = None
        self.client = None
        self.datastore_name = None
        self.lib_name = "iso-demo-lib"
        self.local_library = None
        self.iso_item_name = "iso-demo-lib-item"
        self.vm_name = None

    def _options(self):
        self.argparser.add_argument(
            '-datastorename',
            '--datastorename',
            required=True,
            help='The name of a datastore (of type vmfs) that is'
            ' accessible to the vm specified with --vmname.')
        self.argparser.add_argument(
            '-vmname',
            '--vmname',
            required=True,
            help='The name of the vm where iso will be mounted. '
            'The vm needs to be already created on the vCenter')

    def _setup(self):
        self.datastore_name = self.args.datastorename
        assert self.datastore_name is not None

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

        self.servicemanager = self.get_service_manager()

        self.client = ClsApiClient(self.servicemanager)
        self.helper = ClsApiHelper(self.client, self.skip_verification)

        session = get_unverified_session() if self.skip_verification else None
        self.vsphere_client = create_vsphere_client(server=self.server,
                                                    username=self.username,
                                                    password=self.password,
                                                    session=session)

    def _execute(self):
        storage_backings = self.helper.create_storage_backings(
            self.servicemanager, self.datastore_name)

        library_id = self.helper.create_local_library(storage_backings,
                                                      self.lib_name)
        self.local_library = self.client.local_library_service.get(library_id)

        library_item_id = self.helper.create_iso_library_item(
            library_id, self.iso_item_name, self.ISO_FILENAME)

        vm_id = get_vm(self.vsphere_client, self.vm_name)
        assert vm_id is not None

        # Mount the iso item as a CDROM device
        device_id = self.client.iso_service.mount(library_item_id, vm_id)
        assert device_id is not None
        print('Mounted library item {0} on vm {1} at device {2}'.format(
            self.iso_item_name, self.vm_name, device_id))
        # Unmount the CDROM
        self.client.iso_service.unmount(vm_id, device_id)
        print('Unmounted library item {0} from vm {1} mounted at device {2}'.
              format(self.iso_item_name, self.vm_name, device_id))

    def _cleanup(self):
        if self.local_library:
            self.client.local_library_service.delete(
                library_id=self.local_library.id)
            print('Deleted Library Id: {0}'.format(self.local_library.id))
示例#20
0
class CheckOutVmTemplateWorkflow(SampleBase):
    """
    Demonstrates how to check out a VM from a library item containing a virtual
    machine template, check in the VM checked out from the item, and rollback
    the item to a previous version.

    Prerequisites:
        - A library item containing a virtual machine template
        - A resource pool
        - A datacenter
    """
    def __init__(self):
        SampleBase.__init__(self, self.__doc__)
        self.servicemanager = None
        self.client = None
        self.helper = None
        self.item_name = None
        self.vm_name = None
        self.datacenter_name = None
        self.resource_pool_name = None

    def _options(self):
        self.argparser.add_argument('-itemname',
                                    '--itemname',
                                    required=True,
                                    help='The name of the library item '
                                    'containing the VM template '
                                    'to be checked out')
        self.argparser.add_argument('-datacentername',
                                    '--datacentername',
                                    required=True,
                                    help='The name of the datacenter in which '
                                    'to check out the VM')
        self.argparser.add_argument('-resourcepoolname',
                                    '--resourcepoolname',
                                    required=True,
                                    help='The name of the resource pool in '
                                    'the datacenter in which to place '
                                    'the VM')
        self.argparser.add_argument('-vmname',
                                    '--vmname',
                                    help='The name of the VM to check out of '
                                    'the library item')

    def _setup(self):
        # Required arguments
        self.datacenter_name = self.args.datacentername
        self.resource_pool_name = self.args.resourcepoolname
        self.item_name = self.args.itemname

        # Optional arguments
        self.vm_name = (self.args.vmname
                        if self.args.vmname else rand('checked-out-vm-'))

        self.servicemanager = self.get_service_manager()
        self.client = ClsApiClient(self.servicemanager)
        self.helper = ClsApiHelper(self.client, self.skip_verification)

        session = get_unverified_session() if self.skip_verification else None
        self.vsphere_client = create_vsphere_client(server=self.server,
                                                    username=self.username,
                                                    password=self.password,
                                                    session=session)

    def _execute(self):
        # Get the identifiers
        item_id = self.helper.get_item_id_by_name(self.item_name)
        assert item_id

        resource_pool_id = get_resource_pool(self.vsphere_client,
                                             self.datacenter_name,
                                             self.resource_pool_name)
        assert resource_pool_id

        version_before_check_out = self.client.library_item_service.get(
            item_id).content_version

        self.print_live_versions(item_id)

        # Build the check out spec
        check_out_spec = CheckOuts.CheckOutSpec()
        placement_spec = CheckOuts.PlacementSpec()
        placement_spec.resource_pool = resource_pool_id
        check_out_spec.placement = placement_spec
        check_out_spec.name = self.vm_name

        # Check out VM from item
        vm_id = self.client.check_outs_service.check_out(
            item_id, check_out_spec)
        print("VM (ID: {}) checked out from item".format(vm_id))

        # Get library id associated with checked out VM
        info = self.vsphere_client.vcenter.vm.LibraryItem.get(vm_id)
        assert info.check_out
        print("Library item associated with checked out VM is {}".format(
            info.check_out.library_item))

        # Check in VM into the library item
        check_in_spec = CheckOuts.CheckInSpec()
        check_in_spec.message = "Check in message"
        version_after_check_in = self.client.check_outs_service.check_in(
            item_id, vm_id, check_in_spec)
        print("VM (ID: {}) checked into item {}".format(vm_id, item_id))
        self.print_live_versions(item_id)

        # Rollback to previous version
        rollback_message = "Rollback to v{}".format(version_before_check_out)
        rollback_spec = Versions.RollbackSpec(rollback_message)
        version_after_rollback = self.client.versions_service.rollback(
            item_id, version_before_check_out, rollback_spec)
        print("Item rolled back to version {}. New item version is {}".format(
            version_before_check_out, version_after_rollback))
        self.print_live_versions(item_id)

        # Delete previous version
        self.client.versions_service.delete(item_id, version_after_check_in)
        print("Deleted version {} of item".format(version_after_check_in))
        self.print_live_versions(item_id)
        self.print_change_history(item_id)

    def print_live_versions(self, item_id):
        # Get and print live versions of the VM template item
        versions_info = self.client.versions_service.list(item_id)
        print("Live versions of VM template item:")
        for version_info in versions_info:
            vm_template = get_obj_by_moId(self.servicemanager.content,
                                          [vim.VirtualMachine],
                                          version_info.vm_template)
            print("Version: {}, VM template name: {}".format(
                version_info.version, vm_template.name))

    def print_change_history(self, item_id):
        # Get and print change history of the VM template item
        changes_summary = self.client.changes_service.list(item_id)
        print("Change history of VM template item:")
        for change_summary in changes_summary:
            print("Change version: {}, Time: {}, User: {}, Message: {}".format(
                change_summary.version, change_summary.time,
                change_summary.user, change_summary.short_message))
示例#21
0
class OvfImportExport(SampleBase):
    """
    Demonstrates the workflow to import an OVF package into the content library,
    as well as download of an OVF template from the content library.

    Note: the workflow needs an existing VC DS with available storage.
    """

    def __init__(self):
        SampleBase.__init__(self, self.__doc__)
        self.servicemanager = None
        self.client = None
        self.helper = None
        self.datastore_name = None
        self.lib_name = "demo-lib"
        self.local_library = None
        self.lib_item_name = "simpleVmTemplate"
        self.library_item = None

    def _options(self):
        self.argparser.add_argument('-datastorename',
                                    '--datastorename',
                                    help='The name of the datastore.')

    def _setup(self):
        self.datastore_name = self.args.datastorename
        assert self.datastore_name is not None

        if not self.servicemanager:
            self.servicemanager = self.get_service_manager()

        self.client = ClsApiClient(self.servicemanager)
        self.helper = ClsApiHelper(self.client, self.skip_verification)

    def _execute(self):
        # Find the datastore by the given datastore 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
        print('DataStore: {0} ID: {1}'.format(self.datastore_name, self.datastore_id))

        # Build the storage backing for the library to be created
        storage_backings = []
        storage_backing = StorageBacking(type=StorageBacking.Type.DATASTORE, datastore_id=self.datastore_id)
        storage_backings.append(storage_backing)

        # Build the specification for the library to be created
        create_spec = LibraryModel()
        create_spec.name = self.lib_name
        create_spec.description = "Local library backed by VC datastore"
        create_spec.type = create_spec.LibraryType.LOCAL
        create_spec.storage_backings = storage_backings

        # Create a local content library backed the VC datastore using vAPIs
        library_id = self.client.local_library_service.create(create_spec=create_spec,
                                                              client_token=generate_random_uuid())
        print('Local library created: ID: {0}'.format(library_id))
        self.local_library = self.client.local_library_service.get(library_id)

        # Create a new library item in the content library for uploading the files
        self.library_item_id = self.helper.create_library_item(library_id=self.local_library.id,
                                                               item_name=self.lib_item_name,
                                                               item_description='Sample simple VM template',
                                                               item_type='ovf')
        assert self.library_item_id is not None
        assert self.client.library_item_service.get(self.library_item_id) is not None
        print('Library item created id: {0}'.format(self.library_item_id))

        # Upload a VM template to the CL
        ovf_files_map = self.helper.get_ovf_files_map(ClsApiHelper.SIMPLE_OVF_RELATIVE_DIR)
        self.helper.upload_files(library_item_id=self.library_item_id, files_map=ovf_files_map)
        print('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-')
        print('Downloading library item {0} to directory {1}'.format(self.library_item_id, temp_dir))
        downloaded_files_map = self.helper.download_files(library_item_id=self.library_item_id, directory=temp_dir)
        assert len(downloaded_files_map) == len(ovf_files_map)

    def _cleanup(self):
        if self.local_library:
            self.client.local_library_service.delete(library_id=self.local_library.id)
            print('Deleted Library Id: {0}'.format(self.local_library.id))