Ejemplo n.º 1
0
 def test_get_vm_create_spec(self):
     instance_uuid = uuidutils.generate_uuid()
     fake_instance = {"id": 7, "name": "fake!", "uuid": instance_uuid, "vcpus": 2, "memory_mb": 2048}
     result = vm_util.get_vm_create_spec(fake.FakeFactory(), fake_instance, instance_uuid, "fake-datastore", [])
     expected = """{
         'files': {'vmPathName': '[fake-datastore]',
         'obj_name': 'ns0:VirtualMachineFileInfo'},
         'instanceUuid': '%(instance_uuid)s',
         'name': '%(instance_uuid)s', 'deviceChange': [],
         'extraConfig': [{'value': '%(instance_uuid)s',
                          'key': 'nvp.vm-uuid',
                          'obj_name': 'ns0:OptionValue'}],
         'memoryMB': 2048,
         'obj_name': 'ns0:VirtualMachineConfigSpec',
         'guestId': 'otherGuest',
         'tools': {'beforeGuestStandby': True,
                   'beforeGuestReboot': True,
                   'beforeGuestShutdown': True,
                   'afterResume': True,
                   'afterPowerOn': True,
         'obj_name': 'ns0:ToolsConfigInfo'},
         'numCPUs': 2}""" % {
         "instance_uuid": instance_uuid
     }
     expected = re.sub(r"\s+", "", expected)
     result = re.sub(r"\s+", "", repr(result))
     self.assertEqual(expected, result)
Ejemplo n.º 2
0
 def test_get_vm_create_spec(self):
     instance_uuid = uuidutils.generate_uuid()
     fake_instance = {
         'id': 7,
         'name': 'fake!',
         'uuid': instance_uuid,
         'vcpus': 2,
         'memory_mb': 2048
     }
     result = vm_util.get_vm_create_spec(fake.FakeFactory(), fake_instance,
                                         instance_uuid, 'fake-datastore',
                                         [])
     expected = """{
         'files': {'vmPathName': '[fake-datastore]',
         'obj_name': 'ns0:VirtualMachineFileInfo'},
         'instanceUuid': '%(instance_uuid)s',
         'name': '%(instance_uuid)s', 'deviceChange': [],
         'extraConfig': [{'value': '%(instance_uuid)s',
                          'key': 'nvp.vm-uuid',
                          'obj_name': 'ns0:OptionValue'}],
         'memoryMB': 2048,
         'obj_name': 'ns0:VirtualMachineConfigSpec',
         'guestId': 'otherGuest',
         'tools': {'beforeGuestStandby': True,
                   'beforeGuestReboot': True,
                   'beforeGuestShutdown': True,
                   'afterResume': True,
                   'afterPowerOn': True,
         'obj_name': 'ns0:ToolsConfigInfo'},
         'numCPUs': 2}""" % {
         'instance_uuid': instance_uuid
     }
     expected = re.sub(r'\s+', '', expected)
     result = re.sub(r'\s+', '', repr(result))
     self.assertEqual(expected, result)
Ejemplo n.º 3
0
 def test_get_vm_create_spec_with_limit(self):
     instance_uuid = uuidutils.generate_uuid()
     fake_instance = {'id': 7, 'name': 'fake!',
                      'uuid': instance_uuid,
                      'vcpus': 2, 'memory_mb': 2048}
     result = vm_util.get_vm_create_spec(fake.FakeFactory(),
                                         fake_instance, instance_uuid,
                                         'fake-datastore', [],
                                         allocations={'cpu_limit': 7})
     expected = """{
         'files': {'vmPathName': '[fake-datastore]',
         'obj_name': 'ns0:VirtualMachineFileInfo'},
         'instanceUuid': '%(instance_uuid)s',
         'name': '%(instance_uuid)s', 'deviceChange': [],
         'extraConfig': [{'value': '%(instance_uuid)s',
                          'key': 'nvp.vm-uuid',
                          'obj_name': 'ns0:OptionValue'}],
         'memoryMB': 2048,
         'managedBy':  {'extensionKey': 'org.openstack.compute',
                        'type': 'instance',
                        'obj_name': 'ns0:ManagedByInfo'},
         'obj_name': 'ns0:VirtualMachineConfigSpec',
         'guestId': 'otherGuest',
         'tools': {'beforeGuestStandby': True,
                   'beforeGuestReboot': True,
                   'beforeGuestShutdown': True,
                   'afterResume': True,
                   'afterPowerOn': True,
         'obj_name': 'ns0:ToolsConfigInfo'},
         'cpuAllocation': {'limit': 7,
                           'obj_name': 'ns0:ResourceAllocationInfo'},
         'numCPUs': 2}""" % {'instance_uuid': instance_uuid}
     expected = re.sub(r'\s+', '', expected)
     result = re.sub(r'\s+', '', repr(result))
     self.assertEqual(expected, result)
Ejemplo n.º 4
0
    def test_create_vm_invalid_guestid(self, mock_log_warn):
        """Ensure we warn when create_vm() fails after we passed an
        unrecognised guestId
        """

        found = [False]

        def fake_log_warn(msg, values):
            if not isinstance(values, dict):
                return
            if values.get('ostype') == 'invalid_os_type':
                found[0] = True
        mock_log_warn.side_effect = fake_log_warn

        instance_values = {'id': 7, 'name': 'fake-name',
                           'uuid': uuidutils.generate_uuid(),
                           'vcpus': 2, 'memory_mb': 2048}
        instance = fake_instance.fake_instance_obj(
            context.RequestContext('fake', 'fake', is_admin=False),
            **instance_values)

        session = driver.VMwareAPISession()

        config_spec = vm_util.get_vm_create_spec(
            session.vim.client.factory,
            instance, instance.name, 'fake-datastore', [],
            vm_util.ExtraSpecs(),
            os_type='invalid_os_type')

        self.assertRaises(vexc.VMwareDriverException,
                          vm_util.create_vm, session, instance, 'folder',
                          config_spec, 'res-pool')
        self.assertTrue(found[0])
Ejemplo n.º 5
0
    def build_virtual_machine(self, instance, instance_name, image_info,
                              dc_info, datastore, network_info,
                              pg_vlan_instance_map):
        node_mo_id = vm_util.get_mo_id_from_instance(instance)
        res_pool_ref = vm_util.get_res_pool_ref(self._session,
                                                self._cluster, node_mo_id)
        vif_infos = vmwarevif.get_vif_info(self._session,
                                           self._cluster,
                                           utils.is_neutron(),
                                           image_info.vif_model,
                                           network_info,
                                           pg_vlan_instance_map)

        allocations = self._get_cpu_allocations(instance.instance_type_id)

        # Get the create vm config spec
        client_factory = self._session._get_vim().client.factory
        config_spec = vm_util.get_vm_create_spec(client_factory,
                                                 instance,
                                                 instance_name,
                                                 datastore.name,
                                                 vif_infos,
                                                 image_info.os_type,
                                                 allocations=allocations)
        # Create the VM
        vm_ref = vm_util.create_vm(self._session, instance, dc_info.vmFolder,
                                   config_spec, res_pool_ref)
        return vm_ref
Ejemplo n.º 6
0
 def test_get_vm_create_spec_with_share_custom(self):
     instance_uuid = uuidutils.generate_uuid()
     fake_instance = {'id': 7, 'name': 'fake!',
                      'uuid': instance_uuid,
                      'vcpus': 2, 'memory_mb': 2048}
     cpu_limits = vm_util.CpuLimits(cpu_shares_level='custom',
                                    cpu_shares_share=1948)
     extra_specs = vm_util.ExtraSpecs(cpu_limits=cpu_limits)
     result = vm_util.get_vm_create_spec(fake.FakeFactory(),
                                         fake_instance, instance_uuid,
                                         'fake-datastore', [],
                                         extra_specs)
     expected = """{
         'files': {'vmPathName': '[fake-datastore]',
         'obj_name': 'ns0:VirtualMachineFileInfo'},
         'instanceUuid': '%(instance_uuid)s',
         'name': '%(instance_uuid)s', 'deviceChange': [],
         'extraConfig': [{'value': '%(instance_uuid)s',
                          'key': 'nvp.vm-uuid',
                          'obj_name': 'ns0:OptionValue'}],
         'memoryMB': 2048,
         'managedBy':  {'extensionKey': 'org.openstack.compute',
                        'type': 'instance',
                        'obj_name': 'ns0:ManagedByInfo'},
         'obj_name': 'ns0:VirtualMachineConfigSpec',
         'guestId': 'otherGuest',
         'tools': {'beforeGuestStandby': True,
                   'beforeGuestReboot': True,
                   'beforeGuestShutdown': True,
                   'afterResume': True,
                   'afterPowerOn': True,
         'obj_name': 'ns0:ToolsConfigInfo'},
         'cpuAllocation': {'shares': {'level': 'custom',
                                      'shares': 1948,
                                      'obj_name':'ns0:SharesInfo'},
                           'obj_name':'ns0:ResourceAllocationInfo'},
         'numCPUs': 2}""" % {'instance_uuid': instance_uuid}
     expected = re.sub(r'\s+', '', expected)
     result = re.sub(r'\s+', '', repr(result))
     self.assertEqual(expected, result)
Ejemplo n.º 7
0
    def spawn(self, context, instance, network_info):
        """
        Creates a VM instance.

        Steps followed are:
        1. Create a VM with no disk and the specifics in the instance object
            like RAM size.
        2. Create a dummy vmdk of the size of the disk file that is to be
            uploaded. This is required just to create the metadata file.
        3. Delete the -flat.vmdk file created in the above step and retain
            the metadata .vmdk file.
        4. Upload the disk file.
        5. Attach the disk to the VM by reconfiguring the same.
        6. Power on the VM.
        """
        vm_ref = self._get_vm_ref_from_the_name(instance.name)
        if vm_ref:
            raise exception.InstanceExists(name=instance.name)

        client_factory = self._session._get_vim().client.factory
        service_content = self._session._get_vim().get_service_content()

        def _get_datastore_ref():
            """Get the datastore list and choose the first local storage."""
            data_stores = self._session._call_method(vim_util, "get_objects",
                        "Datastore", ["summary.type", "summary.name"])
            for elem in data_stores:
                ds_name = None
                ds_type = None
                for prop in elem.propSet:
                    if prop.name == "summary.type":
                        ds_type = prop.val
                    elif prop.name == "summary.name":
                        ds_name = prop.val
                # Local storage identifier
                if ds_type == "VMFS":
                    data_store_name = ds_name
                    return data_store_name

            if data_store_name is None:
                msg = _("Couldn't get a local Datastore reference")
                LOG.exception(msg)
                raise exception.Error(msg)

        data_store_name = _get_datastore_ref()

        def _get_image_properties():
            """
            Get the Size of the flat vmdk file that is there on the storage
            repository.
            """
            image_size, image_properties = \
                    vmware_images.get_vmdk_size_and_properties(context,
                                       instance.image_ref, instance)
            vmdk_file_size_in_kb = int(image_size) / 1024
            os_type = image_properties.get("vmware_ostype", "otherGuest")
            adapter_type = image_properties.get("vmware_adaptertype",
                                                "lsiLogic")
            return vmdk_file_size_in_kb, os_type, adapter_type

        vmdk_file_size_in_kb, os_type, adapter_type = _get_image_properties()

        def _get_vmfolder_and_res_pool_mors():
            """Get the Vm folder ref from the datacenter."""
            dc_objs = self._session._call_method(vim_util, "get_objects",
                                    "Datacenter", ["vmFolder"])
            # There is only one default datacenter in a standalone ESX host
            vm_folder_mor = dc_objs[0].propSet[0].val

            # Get the resource pool. Taking the first resource pool coming our
            # way. Assuming that is the default resource pool.
            res_pool_mor = self._session._call_method(vim_util, "get_objects",
                                    "ResourcePool")[0].obj
            return vm_folder_mor, res_pool_mor

        vm_folder_mor, res_pool_mor = _get_vmfolder_and_res_pool_mors()

        def _check_if_network_bridge_exists(network_name):
            network_ref = \
                network_utils.get_network_with_the_name(self._session,
                                                        network_name)
            if network_ref is None:
                raise exception.NetworkNotFoundForBridge(bridge=network_name)
            return network_ref

        def _get_vif_infos():
            vif_infos = []
            for (network, mapping) in network_info:
                mac_address = mapping['mac']
                network_name = network['bridge']
                if mapping.get('should_create_vlan'):
                    network_ref = self._vif_driver.ensure_vlan_bridge(
                                                        self._session, network)
                else:
                    network_ref = _check_if_network_bridge_exists(network_name)
                vif_infos.append({'network_name': network_name,
                                  'mac_address': mac_address,
                                  'network_ref': network_ref,
                                 })
            return vif_infos

        vif_infos = _get_vif_infos()

        # Get the create vm config spec
        config_spec = vm_util.get_vm_create_spec(
                            client_factory, instance,
                            data_store_name, vif_infos, os_type)

        def _execute_create_vm():
            """Create VM on ESX host."""
            LOG.debug(_("Creating VM with the name %s on the ESX  host") %
                      instance.name)
            # Create the VM on the ESX host
            vm_create_task = self._session._call_method(
                                    self._session._get_vim(),
                                    "CreateVM_Task", vm_folder_mor,
                                    config=config_spec, pool=res_pool_mor)
            self._session._wait_for_task(instance.id, vm_create_task)

            LOG.debug(_("Created VM with the name %s on the ESX  host") %
                      instance.name)

        _execute_create_vm()

        # Set the machine.id parameter of the instance to inject
        # the NIC configuration inside the VM
        if FLAGS.flat_injected:
            self._set_machine_id(client_factory, instance, network_info)

        # Naming the VM files in correspondence with the VM instance name
        # The flat vmdk file name
        flat_uploaded_vmdk_name = "%s/%s-flat.vmdk" % (instance.name,
                                                       instance.name)
        # The vmdk meta-data file
        uploaded_vmdk_name = "%s/%s.vmdk" % (instance.name, instance.name)
        flat_uploaded_vmdk_path = vm_util.build_datastore_path(data_store_name,
                                            flat_uploaded_vmdk_name)
        uploaded_vmdk_path = vm_util.build_datastore_path(data_store_name,
                                            uploaded_vmdk_name)

        def _create_virtual_disk():
            """Create a virtual disk of the size of flat vmdk file."""
            # Create a Virtual Disk of the size of the flat vmdk file. This is
            # done just to generate the meta-data file whose specifics
            # depend on the size of the disk, thin/thick provisioning and the
            # storage adapter type.
            # Here we assume thick provisioning and lsiLogic for the adapter
            # type
            LOG.debug(_("Creating Virtual Disk of size  "
                      "%(vmdk_file_size_in_kb)s KB and adapter type  "
                      "%(adapter_type)s on the ESX host local store"
                      " %(data_store_name)s") %
                       {"vmdk_file_size_in_kb": vmdk_file_size_in_kb,
                        "adapter_type": adapter_type,
                        "data_store_name": data_store_name})
            vmdk_create_spec = vm_util.get_vmdk_create_spec(client_factory,
                                    vmdk_file_size_in_kb, adapter_type)
            vmdk_create_task = self._session._call_method(
                self._session._get_vim(),
                "CreateVirtualDisk_Task",
                service_content.virtualDiskManager,
                name=uploaded_vmdk_path,
                datacenter=self._get_datacenter_name_and_ref()[0],
                spec=vmdk_create_spec)
            self._session._wait_for_task(instance.id, vmdk_create_task)
            LOG.debug(_("Created Virtual Disk of size %(vmdk_file_size_in_kb)s"
                        " KB on the ESX host local store "
                        "%(data_store_name)s") %
                        {"vmdk_file_size_in_kb": vmdk_file_size_in_kb,
                         "data_store_name": data_store_name})

        _create_virtual_disk()

        def _delete_disk_file():
            LOG.debug(_("Deleting the file %(flat_uploaded_vmdk_path)s "
                        "on the ESX host local"
                        "store %(data_store_name)s") %
                        {"flat_uploaded_vmdk_path": flat_uploaded_vmdk_path,
                         "data_store_name": data_store_name})
            # Delete the -flat.vmdk file created. .vmdk file is retained.
            vmdk_delete_task = self._session._call_method(
                        self._session._get_vim(),
                        "DeleteDatastoreFile_Task",
                        service_content.fileManager,
                        name=flat_uploaded_vmdk_path)
            self._session._wait_for_task(instance.id, vmdk_delete_task)
            LOG.debug(_("Deleted the file %(flat_uploaded_vmdk_path)s on the "
                        "ESX host local store %(data_store_name)s") %
                        {"flat_uploaded_vmdk_path": flat_uploaded_vmdk_path,
                         "data_store_name": data_store_name})

        _delete_disk_file()

        cookies = self._session._get_vim().client.options.transport.cookiejar

        def _fetch_image_on_esx_datastore():
            """Fetch image from Glance to ESX datastore."""
            LOG.debug(_("Downloading image file data %(image_ref)s to the ESX "
                        "data store %(data_store_name)s") %
                        ({'image_ref': instance.image_ref,
                          'data_store_name': data_store_name}))
            # Upload the -flat.vmdk file whose meta-data file we just created
            # above
            vmware_images.fetch_image(
                context,
                instance.image_ref,
                instance,
                host=self._session._host_ip,
                data_center_name=self._get_datacenter_name_and_ref()[1],
                datastore_name=data_store_name,
                cookies=cookies,
                file_path=flat_uploaded_vmdk_name)
            LOG.debug(_("Downloaded image file data %(image_ref)s to the ESX "
                        "data store %(data_store_name)s") %
                        ({'image_ref': instance.image_ref,
                         'data_store_name': data_store_name}))
        _fetch_image_on_esx_datastore()

        vm_ref = self._get_vm_ref_from_the_name(instance.name)

        def _attach_vmdk_to_the_vm():
            """
            Attach the vmdk uploaded to the VM. VM reconfigure is done
            to do so.
            """
            vmdk_attach_config_spec = vm_util.get_vmdk_attach_config_spec(
                                client_factory,
                                vmdk_file_size_in_kb, uploaded_vmdk_path,
                                adapter_type)
            LOG.debug(_("Reconfiguring VM instance %s to attach the image "
                      "disk") % instance.name)
            reconfig_task = self._session._call_method(
                               self._session._get_vim(),
                               "ReconfigVM_Task", vm_ref,
                               spec=vmdk_attach_config_spec)
            self._session._wait_for_task(instance.id, reconfig_task)
            LOG.debug(_("Reconfigured VM instance %s to attach the image "
                      "disk") % instance.name)

        _attach_vmdk_to_the_vm()

        def _power_on_vm():
            """Power on the VM."""
            LOG.debug(_("Powering on the VM instance %s") % instance.name)
            # Power On the VM
            power_on_task = self._session._call_method(
                               self._session._get_vim(),
                               "PowerOnVM_Task", vm_ref)
            self._session._wait_for_task(instance.id, power_on_task)
            LOG.debug(_("Powered on the VM instance %s") % instance.name)
        _power_on_vm()
Ejemplo n.º 8
0
    def spawn(self, context, instance, image_meta, network_info):
        """
        Creates a VM instance.

        Steps followed are:
        1. Create a VM with no disk and the specifics in the instance object
            like RAM size.
        2. Create a dummy vmdk of the size of the disk file that is to be
            uploaded. This is required just to create the metadata file.
        3. Delete the -flat.vmdk file created in the above step and retain
            the metadata .vmdk file.
        4. Upload the disk file.
        5. Attach the disk to the VM by reconfiguring the same.
        6. Power on the VM.
        """
        vm_ref = self._get_vm_ref_from_the_name(instance.name)
        if vm_ref:
            raise exception.InstanceExists(name=instance.name)

        client_factory = self._session._get_vim().client.factory
        service_content = self._session._get_vim().get_service_content()

        def _get_datastore_ref():
            """Get the datastore list and choose the first local storage."""
            data_stores = self._session._call_method(
                vim_util, "get_objects", "Datastore",
                ["summary.type", "summary.name"])
            for elem in data_stores:
                ds_name = None
                ds_type = None
                for prop in elem.propSet:
                    if prop.name == "summary.type":
                        ds_type = prop.val
                    elif prop.name == "summary.name":
                        ds_name = prop.val
                # Local storage identifier
                if ds_type == "VMFS":
                    data_store_name = ds_name
                    return data_store_name

            if data_store_name is None:
                msg = _("Couldn't get a local Datastore reference")
                LOG.exception(msg)
                raise exception.Error(msg)

        data_store_name = _get_datastore_ref()

        def _get_image_properties():
            """
            Get the Size of the flat vmdk file that is there on the storage
            repository.
            """
            image_size, image_properties = \
                    vmware_images.get_vmdk_size_and_properties(context,
                                       instance.image_ref, instance)
            vmdk_file_size_in_kb = int(image_size) / 1024
            os_type = image_properties.get("vmware_ostype", "otherGuest")
            adapter_type = image_properties.get("vmware_adaptertype",
                                                "lsiLogic")
            return vmdk_file_size_in_kb, os_type, adapter_type

        vmdk_file_size_in_kb, os_type, adapter_type = _get_image_properties()

        def _get_vmfolder_and_res_pool_mors():
            """Get the Vm folder ref from the datacenter."""
            dc_objs = self._session._call_method(vim_util, "get_objects",
                                                 "Datacenter", ["vmFolder"])
            # There is only one default datacenter in a standalone ESX host
            vm_folder_mor = dc_objs[0].propSet[0].val

            # Get the resource pool. Taking the first resource pool coming our
            # way. Assuming that is the default resource pool.
            res_pool_mor = self._session._call_method(vim_util, "get_objects",
                                                      "ResourcePool")[0].obj
            return vm_folder_mor, res_pool_mor

        vm_folder_mor, res_pool_mor = _get_vmfolder_and_res_pool_mors()

        def _check_if_network_bridge_exists(network_name):
            network_ref = \
                network_utils.get_network_with_the_name(self._session,
                                                        network_name)
            if network_ref is None:
                raise exception.NetworkNotFoundForBridge(bridge=network_name)
            return network_ref

        def _get_vif_infos():
            vif_infos = []
            for (network, mapping) in network_info:
                mac_address = mapping['mac']
                network_name = network['bridge']
                if mapping.get('should_create_vlan'):
                    network_ref = self._vif_driver.ensure_vlan_bridge(
                        self._session, network)
                else:
                    network_ref = _check_if_network_bridge_exists(network_name)
                vif_infos.append({
                    'network_name': network_name,
                    'mac_address': mac_address,
                    'network_ref': network_ref,
                })
            return vif_infos

        vif_infos = _get_vif_infos()

        # Get the create vm config spec
        config_spec = vm_util.get_vm_create_spec(client_factory, instance,
                                                 data_store_name, vif_infos,
                                                 os_type)

        def _execute_create_vm():
            """Create VM on ESX host."""
            LOG.debug(
                _("Creating VM with the name %s on the ESX  host") %
                instance.name)
            # Create the VM on the ESX host
            vm_create_task = self._session._call_method(
                self._session._get_vim(),
                "CreateVM_Task",
                vm_folder_mor,
                config=config_spec,
                pool=res_pool_mor)
            self._session._wait_for_task(instance.id, vm_create_task)

            LOG.debug(
                _("Created VM with the name %s on the ESX  host") %
                instance.name)

        _execute_create_vm()

        # Set the machine.id parameter of the instance to inject
        # the NIC configuration inside the VM
        if FLAGS.flat_injected:
            self._set_machine_id(client_factory, instance, network_info)

        # Naming the VM files in correspondence with the VM instance name
        # The flat vmdk file name
        flat_uploaded_vmdk_name = "%s/%s-flat.vmdk" % (instance.name,
                                                       instance.name)
        # The vmdk meta-data file
        uploaded_vmdk_name = "%s/%s.vmdk" % (instance.name, instance.name)
        flat_uploaded_vmdk_path = vm_util.build_datastore_path(
            data_store_name, flat_uploaded_vmdk_name)
        uploaded_vmdk_path = vm_util.build_datastore_path(
            data_store_name, uploaded_vmdk_name)

        def _create_virtual_disk():
            """Create a virtual disk of the size of flat vmdk file."""
            # Create a Virtual Disk of the size of the flat vmdk file. This is
            # done just to generate the meta-data file whose specifics
            # depend on the size of the disk, thin/thick provisioning and the
            # storage adapter type.
            # Here we assume thick provisioning and lsiLogic for the adapter
            # type
            LOG.debug(
                _("Creating Virtual Disk of size  "
                  "%(vmdk_file_size_in_kb)s KB and adapter type  "
                  "%(adapter_type)s on the ESX host local store"
                  " %(data_store_name)s") % {
                      "vmdk_file_size_in_kb": vmdk_file_size_in_kb,
                      "adapter_type": adapter_type,
                      "data_store_name": data_store_name
                  })
            vmdk_create_spec = vm_util.get_vmdk_create_spec(
                client_factory, vmdk_file_size_in_kb, adapter_type)
            vmdk_create_task = self._session._call_method(
                self._session._get_vim(),
                "CreateVirtualDisk_Task",
                service_content.virtualDiskManager,
                name=uploaded_vmdk_path,
                datacenter=self._get_datacenter_name_and_ref()[0],
                spec=vmdk_create_spec)
            self._session._wait_for_task(instance.id, vmdk_create_task)
            LOG.debug(
                _("Created Virtual Disk of size %(vmdk_file_size_in_kb)s"
                  " KB on the ESX host local store "
                  "%(data_store_name)s") % {
                      "vmdk_file_size_in_kb": vmdk_file_size_in_kb,
                      "data_store_name": data_store_name
                  })

        _create_virtual_disk()

        def _delete_disk_file():
            LOG.debug(
                _("Deleting the file %(flat_uploaded_vmdk_path)s "
                  "on the ESX host local"
                  "store %(data_store_name)s") % {
                      "flat_uploaded_vmdk_path": flat_uploaded_vmdk_path,
                      "data_store_name": data_store_name
                  })
            # Delete the -flat.vmdk file created. .vmdk file is retained.
            vmdk_delete_task = self._session._call_method(
                self._session._get_vim(),
                "DeleteDatastoreFile_Task",
                service_content.fileManager,
                name=flat_uploaded_vmdk_path)
            self._session._wait_for_task(instance.id, vmdk_delete_task)
            LOG.debug(
                _("Deleted the file %(flat_uploaded_vmdk_path)s on the "
                  "ESX host local store %(data_store_name)s") % {
                      "flat_uploaded_vmdk_path": flat_uploaded_vmdk_path,
                      "data_store_name": data_store_name
                  })

        _delete_disk_file()

        cookies = self._session._get_vim().client.options.transport.cookiejar

        def _fetch_image_on_esx_datastore():
            """Fetch image from Glance to ESX datastore."""
            LOG.debug(
                _("Downloading image file data %(image_ref)s to the ESX "
                  "data store %(data_store_name)s") %
                ({
                    'image_ref': instance.image_ref,
                    'data_store_name': data_store_name
                }))
            # Upload the -flat.vmdk file whose meta-data file we just created
            # above
            vmware_images.fetch_image(
                context,
                instance.image_ref,
                instance,
                host=self._session._host_ip,
                data_center_name=self._get_datacenter_name_and_ref()[1],
                datastore_name=data_store_name,
                cookies=cookies,
                file_path=flat_uploaded_vmdk_name)
            LOG.debug(
                _("Downloaded image file data %(image_ref)s to the ESX "
                  "data store %(data_store_name)s") %
                ({
                    'image_ref': instance.image_ref,
                    'data_store_name': data_store_name
                }))

        _fetch_image_on_esx_datastore()

        vm_ref = self._get_vm_ref_from_the_name(instance.name)

        def _attach_vmdk_to_the_vm():
            """
            Attach the vmdk uploaded to the VM. VM reconfigure is done
            to do so.
            """
            vmdk_attach_config_spec = vm_util.get_vmdk_attach_config_spec(
                client_factory, vmdk_file_size_in_kb, uploaded_vmdk_path,
                adapter_type)
            LOG.debug(
                _("Reconfiguring VM instance %s to attach the image "
                  "disk") % instance.name)
            reconfig_task = self._session._call_method(
                self._session._get_vim(),
                "ReconfigVM_Task",
                vm_ref,
                spec=vmdk_attach_config_spec)
            self._session._wait_for_task(instance.id, reconfig_task)
            LOG.debug(
                _("Reconfigured VM instance %s to attach the image "
                  "disk") % instance.name)

        _attach_vmdk_to_the_vm()

        def _power_on_vm():
            """Power on the VM."""
            LOG.debug(_("Powering on the VM instance %s") % instance.name)
            # Power On the VM
            power_on_task = self._session._call_method(
                self._session._get_vim(), "PowerOnVM_Task", vm_ref)
            self._session._wait_for_task(instance.id, power_on_task)
            LOG.debug(_("Powered on the VM instance %s") % instance.name)

        _power_on_vm()