Search in sources :

Example 16 with Datacenter

use of com.vmware.vim25.mo.Datacenter in project cloudstack by apache.

the class VmwareResource method execute.

protected Answer execute(MigrateWithStorageCommand cmd) {
    if (s_logger.isInfoEnabled()) {
        s_logger.info("Executing resource MigrateWithStorageCommand: " + _gson.toJson(cmd));
    }
    VirtualMachineTO vmTo = cmd.getVirtualMachine();
    String vmName = vmTo.getName();
    VmwareHypervisorHost srcHyperHost = null;
    VmwareHypervisorHost tgtHyperHost = null;
    VirtualMachineMO vmMo = null;
    ManagedObjectReference morDsAtTarget = null;
    ManagedObjectReference morDsAtSource = null;
    ManagedObjectReference morDc = null;
    ManagedObjectReference morDcOfTargetHost = null;
    ManagedObjectReference morTgtHost = new ManagedObjectReference();
    ManagedObjectReference morTgtDatastore = new ManagedObjectReference();
    VirtualMachineRelocateSpec relocateSpec = new VirtualMachineRelocateSpec();
    List<VirtualMachineRelocateSpecDiskLocator> diskLocators = new ArrayList<VirtualMachineRelocateSpecDiskLocator>();
    VirtualMachineRelocateSpecDiskLocator diskLocator = null;
    String tgtDsName = "";
    String tgtDsHost;
    String tgtDsPath;
    int tgtDsPort;
    VolumeTO volume;
    StorageFilerTO filerTo;
    Set<String> mountedDatastoresAtSource = new HashSet<String>();
    List<VolumeObjectTO> volumeToList = new ArrayList<VolumeObjectTO>();
    Map<Long, Integer> volumeDeviceKey = new HashMap<Long, Integer>();
    List<Pair<VolumeTO, StorageFilerTO>> volToFiler = cmd.getVolumeToFilerAsList();
    String tgtHost = cmd.getTargetHost();
    String tgtHostMorInfo = tgtHost.split("@")[0];
    morTgtHost.setType(tgtHostMorInfo.split(":")[0]);
    morTgtHost.setValue(tgtHostMorInfo.split(":")[1]);
    try {
        srcHyperHost = getHyperHost(getServiceContext());
        tgtHyperHost = new HostMO(getServiceContext(), morTgtHost);
        morDc = srcHyperHost.getHyperHostDatacenter();
        morDcOfTargetHost = tgtHyperHost.getHyperHostDatacenter();
        if (!morDc.getValue().equalsIgnoreCase(morDcOfTargetHost.getValue())) {
            String msg = "Source host & target host are in different datacentesr";
            throw new CloudRuntimeException(msg);
        }
        VmwareManager mgr = tgtHyperHost.getContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
        String srcHostApiVersion = ((HostMO) srcHyperHost).getHostAboutInfo().getApiVersion();
        // find VM through datacenter (VM is not at the target host yet)
        vmMo = srcHyperHost.findVmOnPeerHyperHost(vmName);
        if (vmMo == null) {
            String msg = "VM " + vmName + " does not exist in VMware datacenter " + morDc.getValue();
            s_logger.error(msg);
            throw new Exception(msg);
        }
        vmName = vmMo.getName();
        // Specify destination datastore location for each volume
        for (Pair<VolumeTO, StorageFilerTO> entry : volToFiler) {
            volume = entry.first();
            filerTo = entry.second();
            s_logger.debug("Preparing spec for volume : " + volume.getName());
            morDsAtTarget = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(tgtHyperHost, filerTo.getUuid());
            morDsAtSource = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(srcHyperHost, filerTo.getUuid());
            if (morDsAtTarget == null) {
                String msg = "Unable to find the target datastore: " + filerTo.getUuid() + " on target host: " + tgtHyperHost.getHyperHostName() + " to execute MigrateWithStorageCommand";
                s_logger.error(msg);
                throw new Exception(msg);
            }
            morTgtDatastore = morDsAtTarget;
            // So since only the datastore will be changed first, ensure the target datastore is mounted on source host.
            if (srcHostApiVersion.compareTo("5.1") < 0) {
                tgtDsName = filerTo.getUuid().replace("-", "");
                tgtDsHost = filerTo.getHost();
                tgtDsPath = filerTo.getPath();
                tgtDsPort = filerTo.getPort();
                // If datastore is NFS and target datastore is not already mounted on source host then mount the datastore.
                if (filerTo.getType().equals(StoragePoolType.NetworkFilesystem)) {
                    if (morDsAtSource == null) {
                        morDsAtSource = srcHyperHost.mountDatastore(false, tgtDsHost, tgtDsPort, tgtDsPath, tgtDsName);
                        if (morDsAtSource == null) {
                            throw new Exception("Unable to mount NFS datastore " + tgtDsHost + ":/" + tgtDsPath + " on " + _hostName);
                        }
                        mountedDatastoresAtSource.add(tgtDsName);
                        s_logger.debug("Mounted datastore " + tgtDsHost + ":/" + tgtDsPath + " on " + _hostName);
                    }
                }
                // If datastore is VMFS and target datastore is not mounted or accessible to source host then fail migration.
                if (filerTo.getType().equals(StoragePoolType.VMFS)) {
                    if (morDsAtSource == null) {
                        s_logger.warn("If host version is below 5.1, then target VMFS datastore(s) need to manually mounted on source host for a successful live storage migration.");
                        throw new Exception("Target VMFS datastore: " + tgtDsPath + " is not mounted on source host: " + _hostName);
                    }
                    DatastoreMO dsAtSourceMo = new DatastoreMO(getServiceContext(), morDsAtSource);
                    String srcHostValue = srcHyperHost.getMor().getValue();
                    if (!dsAtSourceMo.isAccessibleToHost(srcHostValue)) {
                        s_logger.warn("If host version is below 5.1, then target VMFS datastore(s) need to accessible to source host for a successful live storage migration.");
                        throw new Exception("Target VMFS datastore: " + tgtDsPath + " is not accessible on source host: " + _hostName);
                    }
                }
                morTgtDatastore = morDsAtSource;
            }
            if (volume.getType() == Volume.Type.ROOT) {
                relocateSpec.setDatastore(morTgtDatastore);
            }
            diskLocator = new VirtualMachineRelocateSpecDiskLocator();
            diskLocator.setDatastore(morDsAtSource);
            Pair<VirtualDisk, String> diskInfo = getVirtualDiskInfo(vmMo, volume.getPath() + ".vmdk");
            String vmdkAbsFile = getAbsoluteVmdkFile(diskInfo.first());
            if (vmdkAbsFile != null && !vmdkAbsFile.isEmpty()) {
                vmMo.updateAdapterTypeIfRequired(vmdkAbsFile);
            }
            int diskId = diskInfo.first().getKey();
            diskLocator.setDiskId(diskId);
            diskLocators.add(diskLocator);
            volumeDeviceKey.put(volume.getId(), diskId);
        }
        // If a target datastore is provided for the VM, then by default all volumes associated with the VM will be migrated to that target datastore.
        // Hence set the existing datastore as target datastore for volumes that are not to be migrated.
        List<Pair<Integer, ManagedObjectReference>> diskDatastores = vmMo.getAllDiskDatastores();
        for (Pair<Integer, ManagedObjectReference> diskDatastore : diskDatastores) {
            if (!volumeDeviceKey.containsValue(diskDatastore.first().intValue())) {
                diskLocator = new VirtualMachineRelocateSpecDiskLocator();
                diskLocator.setDiskId(diskDatastore.first().intValue());
                diskLocator.setDatastore(diskDatastore.second());
                diskLocators.add(diskLocator);
            }
        }
        relocateSpec.getDisk().addAll(diskLocators);
        // Prepare network at target before migration
        NicTO[] nics = vmTo.getNics();
        for (NicTO nic : nics) {
            // prepare network on the host
            prepareNetworkFromNicInfo(new HostMO(getServiceContext(), morTgtHost), nic, false, vmTo.getType());
        }
        // Ensure secondary storage mounted on target host
        Pair<String, Long> secStoreUrlAndId = mgr.getSecondaryStorageStoreUrlAndId(Long.parseLong(_dcId));
        String secStoreUrl = secStoreUrlAndId.first();
        Long secStoreId = secStoreUrlAndId.second();
        if (secStoreUrl == null) {
            String msg = "secondary storage for dc " + _dcId + " is not ready yet?";
            throw new Exception(msg);
        }
        mgr.prepareSecondaryStorageStore(secStoreUrl, secStoreId);
        ManagedObjectReference morSecDs = prepareSecondaryDatastoreOnSpecificHost(secStoreUrl, tgtHyperHost);
        if (morSecDs == null) {
            String msg = "Failed to prepare secondary storage on host, secondary store url: " + secStoreUrl;
            throw new Exception(msg);
        }
        if (srcHostApiVersion.compareTo("5.1") < 0) {
            // Migrate VM's volumes to target datastore(s).
            if (!vmMo.changeDatastore(relocateSpec)) {
                throw new Exception("Change datastore operation failed during storage migration");
            } else {
                s_logger.debug("Successfully migrated storage of VM " + vmName + " to target datastore(s)");
            }
            // Migrate VM to target host.
            ManagedObjectReference morPool = tgtHyperHost.getHyperHostOwnerResourcePool();
            if (!vmMo.migrate(morPool, tgtHyperHost.getMor())) {
                throw new Exception("VM migration to target host failed during storage migration");
            } else {
                s_logger.debug("Successfully migrated VM " + vmName + " from " + _hostName + " to " + tgtHyperHost.getHyperHostName());
            }
        } else {
            // Simultaneously migrate VM's volumes to target datastore and VM to target host.
            relocateSpec.setHost(tgtHyperHost.getMor());
            relocateSpec.setPool(tgtHyperHost.getHyperHostOwnerResourcePool());
            if (!vmMo.changeDatastore(relocateSpec)) {
                throw new Exception("Change datastore operation failed during storage migration");
            } else {
                s_logger.debug("Successfully migrated VM " + vmName + " from " + _hostName + " to " + tgtHyperHost.getHyperHostName() + " and its storage to target datastore(s)");
            }
        }
        // In case of a linked clone VM, if VM's disks are not consolidated, further VM operations such as volume snapshot, VM snapshot etc. will result in DB inconsistencies.
        if (!vmMo.consolidateVmDisks()) {
            s_logger.warn("VM disk consolidation failed after storage migration. Yet proceeding with VM migration.");
        } else {
            s_logger.debug("Successfully consolidated disks of VM " + vmName + ".");
        }
        // Update and return volume path and chain info for every disk because that could have changed after migration
        VirtualMachineDiskInfoBuilder diskInfoBuilder = vmMo.getDiskInfoBuilder();
        for (Pair<VolumeTO, StorageFilerTO> entry : volToFiler) {
            volume = entry.first();
            long volumeId = volume.getId();
            VirtualDisk[] disks = vmMo.getAllDiskDevice();
            for (VirtualDisk disk : disks) {
                if (volumeDeviceKey.get(volumeId) == disk.getKey()) {
                    VolumeObjectTO newVol = new VolumeObjectTO();
                    String newPath = vmMo.getVmdkFileBaseName(disk);
                    String poolName = entry.second().getUuid().replace("-", "");
                    VirtualMachineDiskInfo diskInfo = diskInfoBuilder.getDiskInfoByBackingFileBaseName(newPath, poolName);
                    newVol.setId(volumeId);
                    newVol.setPath(newPath);
                    newVol.setChainInfo(_gson.toJson(diskInfo));
                    volumeToList.add(newVol);
                    break;
                }
            }
        }
        return new MigrateWithStorageAnswer(cmd, volumeToList);
    } catch (Throwable e) {
        if (e instanceof RemoteException) {
            s_logger.warn("Encountered remote exception at vCenter, invalidating VMware session context");
            invalidateServiceContext();
        }
        String msg = "MigrationCommand failed due to " + VmwareHelper.getExceptionMessage(e);
        s_logger.warn(msg, e);
        return new MigrateWithStorageAnswer(cmd, (Exception) e);
    } finally {
        // Cleanup datastores mounted on source host
        for (String mountedDatastore : mountedDatastoresAtSource) {
            s_logger.debug("Attempting to unmount datastore " + mountedDatastore + " at " + _hostName);
            try {
                srcHyperHost.unmountDatastore(mountedDatastore);
            } catch (Exception unmountEx) {
                s_logger.debug("Failed to unmount datastore " + mountedDatastore + " at " + _hostName + ". Seems the datastore is still being used by " + _hostName + ". Please unmount manually to cleanup.");
            }
            s_logger.debug("Successfully unmounted datastore " + mountedDatastore + " at " + _hostName);
        }
    }
}
Also used : HashMap(java.util.HashMap) HostMO(com.cloud.hypervisor.vmware.mo.HostMO) ArrayList(java.util.ArrayList) StorageFilerTO(com.cloud.agent.api.to.StorageFilerTO) VirtualMachineTO(com.cloud.agent.api.to.VirtualMachineTO) VolumeTO(com.cloud.agent.api.to.VolumeTO) VirtualMachineRelocateSpec(com.vmware.vim25.VirtualMachineRelocateSpec) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VirtualMachineDiskInfo(org.apache.cloudstack.utils.volume.VirtualMachineDiskInfo) VolumeObjectTO(org.apache.cloudstack.storage.to.VolumeObjectTO) HashSet(java.util.HashSet) Pair(com.cloud.utils.Pair) NicTO(com.cloud.agent.api.to.NicTO) MigrateWithStorageAnswer(com.cloud.agent.api.MigrateWithStorageAnswer) VmwareManager(com.cloud.hypervisor.vmware.manager.VmwareManager) VirtualMachineMO(com.cloud.hypervisor.vmware.mo.VirtualMachineMO) VirtualMachineDiskInfoBuilder(com.cloud.hypervisor.vmware.mo.VirtualMachineDiskInfoBuilder) VmwareHypervisorHost(com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost) ConnectException(java.net.ConnectException) IOException(java.io.IOException) RemoteException(java.rmi.RemoteException) InternalErrorException(com.cloud.exception.InternalErrorException) CloudException(com.cloud.exception.CloudException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ConfigurationException(javax.naming.ConfigurationException) DatastoreMO(com.cloud.hypervisor.vmware.mo.DatastoreMO) VirtualDisk(com.vmware.vim25.VirtualDisk) RemoteException(java.rmi.RemoteException) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference) VirtualMachineRelocateSpecDiskLocator(com.vmware.vim25.VirtualMachineRelocateSpecDiskLocator)

Example 17 with Datacenter

use of com.vmware.vim25.mo.Datacenter in project cloudstack by apache.

the class VmwareResource method execute.

protected Answer execute(MigrateCommand cmd) {
    if (s_logger.isInfoEnabled()) {
        s_logger.info("Executing resource MigrateCommand: " + _gson.toJson(cmd));
    }
    final String vmName = cmd.getVmName();
    try {
        VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext());
        ManagedObjectReference morDc = hyperHost.getHyperHostDatacenter();
        // find VM through datacenter (VM is not at the target host yet)
        VirtualMachineMO vmMo = hyperHost.findVmOnPeerHyperHost(vmName);
        if (vmMo == null) {
            String msg = "VM " + vmName + " does not exist in VMware datacenter";
            s_logger.error(msg);
            throw new Exception(msg);
        }
        VmwareHypervisorHost destHyperHost = getTargetHyperHost(new DatacenterMO(hyperHost.getContext(), morDc), cmd.getDestinationIp());
        ManagedObjectReference morTargetPhysicalHost = destHyperHost.findMigrationTarget(vmMo);
        if (morTargetPhysicalHost == null) {
            throw new Exception("Unable to find a target capable physical host");
        }
        if (!vmMo.migrate(destHyperHost.getHyperHostOwnerResourcePool(), morTargetPhysicalHost)) {
            throw new Exception("Migration failed");
        }
        return new MigrateAnswer(cmd, true, "migration succeeded", null);
    } catch (Throwable e) {
        if (e instanceof RemoteException) {
            s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context");
            invalidateServiceContext();
        }
        String msg = "MigrationCommand failed due to " + VmwareHelper.getExceptionMessage(e);
        s_logger.warn(msg, e);
        return new MigrateAnswer(cmd, false, msg, null);
    }
}
Also used : MigrateAnswer(com.cloud.agent.api.MigrateAnswer) VirtualMachineMO(com.cloud.hypervisor.vmware.mo.VirtualMachineMO) VmwareHypervisorHost(com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost) RemoteException(java.rmi.RemoteException) ConnectException(java.net.ConnectException) IOException(java.io.IOException) RemoteException(java.rmi.RemoteException) InternalErrorException(com.cloud.exception.InternalErrorException) CloudException(com.cloud.exception.CloudException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ConfigurationException(javax.naming.ConfigurationException) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference) DatacenterMO(com.cloud.hypervisor.vmware.mo.DatacenterMO)

Example 18 with Datacenter

use of com.vmware.vim25.mo.Datacenter in project cloudstack by apache.

the class VmwareResource method execute.

protected Answer execute(PrepareForMigrationCommand cmd) {
    if (s_logger.isInfoEnabled()) {
        s_logger.info("Executing resource PrepareForMigrationCommand: " + _gson.toJson(cmd));
    }
    VirtualMachineTO vm = cmd.getVirtualMachine();
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Preparing host for migrating " + vm);
    }
    final String vmName = vm.getName();
    try {
        VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext());
        VmwareManager mgr = hyperHost.getContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
        // find VM through datacenter (VM is not at the target host yet)
        VirtualMachineMO vmMo = hyperHost.findVmOnPeerHyperHost(vmName);
        if (vmMo == null) {
            s_logger.info("VM " + vmName + " was not found in the cluster of host " + hyperHost.getHyperHostName() + ". Looking for the VM in datacenter.");
            ManagedObjectReference dcMor = hyperHost.getHyperHostDatacenter();
            DatacenterMO dcMo = new DatacenterMO(hyperHost.getContext(), dcMor);
            vmMo = dcMo.findVm(vmName);
            if (vmMo == null) {
                String msg = "VM " + vmName + " does not exist in VMware datacenter";
                s_logger.error(msg);
                throw new Exception(msg);
            }
        }
        NicTO[] nics = vm.getNics();
        for (NicTO nic : nics) {
            // prepare network on the host
            prepareNetworkFromNicInfo(new HostMO(getServiceContext(), _morHyperHost), nic, false, cmd.getVirtualMachine().getType());
        }
        Pair<String, Long> secStoreUrlAndId = mgr.getSecondaryStorageStoreUrlAndId(Long.parseLong(_dcId));
        String secStoreUrl = secStoreUrlAndId.first();
        Long secStoreId = secStoreUrlAndId.second();
        if (secStoreUrl == null) {
            String msg = "secondary storage for dc " + _dcId + " is not ready yet?";
            throw new Exception(msg);
        }
        mgr.prepareSecondaryStorageStore(secStoreUrl, secStoreId);
        ManagedObjectReference morSecDs = prepareSecondaryDatastoreOnHost(secStoreUrl);
        if (morSecDs == null) {
            String msg = "Failed to prepare secondary storage on host, secondary store url: " + secStoreUrl;
            throw new Exception(msg);
        }
        return new PrepareForMigrationAnswer(cmd);
    } catch (Throwable e) {
        if (e instanceof RemoteException) {
            s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context");
            invalidateServiceContext();
        }
        String msg = "Unexcpeted exception " + VmwareHelper.getExceptionMessage(e);
        s_logger.error(msg, e);
        return new PrepareForMigrationAnswer(cmd, msg);
    }
}
Also used : VmwareManager(com.cloud.hypervisor.vmware.manager.VmwareManager) HostMO(com.cloud.hypervisor.vmware.mo.HostMO) VirtualMachineMO(com.cloud.hypervisor.vmware.mo.VirtualMachineMO) VmwareHypervisorHost(com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost) VirtualMachineTO(com.cloud.agent.api.to.VirtualMachineTO) ConnectException(java.net.ConnectException) IOException(java.io.IOException) RemoteException(java.rmi.RemoteException) InternalErrorException(com.cloud.exception.InternalErrorException) CloudException(com.cloud.exception.CloudException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ConfigurationException(javax.naming.ConfigurationException) PrepareForMigrationAnswer(com.cloud.agent.api.PrepareForMigrationAnswer) RemoteException(java.rmi.RemoteException) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference) DatacenterMO(com.cloud.hypervisor.vmware.mo.DatacenterMO) NicTO(com.cloud.agent.api.to.NicTO)

Example 19 with Datacenter

use of com.vmware.vim25.mo.Datacenter in project cloudstack by apache.

the class VmwareResource method execute.

private Answer execute(ResizeVolumeCommand cmd) {
    String path = cmd.getPath();
    String vmName = cmd.getInstanceName();
    long newSize = cmd.getNewSize() / 1024;
    long oldSize = cmd.getCurrentSize() / 1024;
    boolean useWorkerVm = false;
    VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext());
    String poolId = cmd.getPoolUuid();
    VirtualMachineMO vmMo = null;
    DatastoreMO dsMo = null;
    ManagedObjectReference morDS = null;
    String vmdkDataStorePath = null;
    try {
        if (newSize < oldSize) {
            throw new Exception("VMware doesn't support shrinking volume from larger size: " + oldSize / (1024 * 1024) + " GB to a smaller size: " + newSize / (1024 * 1024) + " GB");
        } else if (newSize == oldSize) {
            return new ResizeVolumeAnswer(cmd, true, "success", newSize * 1024);
        }
        if (vmName.equalsIgnoreCase("none")) {
            // we need to spawn a worker VM to attach the volume to and
            // resize the volume.
            useWorkerVm = true;
            vmName = getWorkerName(getServiceContext(), cmd, 0);
            morDS = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, poolId);
            dsMo = new DatastoreMO(hyperHost.getContext(), morDS);
            s_logger.info("Create worker VM " + vmName);
            vmMo = HypervisorHostHelper.createWorkerVM(hyperHost, dsMo, vmName);
            if (vmMo == null) {
                throw new Exception("Unable to create a worker VM for volume resize");
            }
            synchronized (this) {
                vmdkDataStorePath = VmwareStorageLayoutHelper.getLegacyDatastorePathFromVmdkFileName(dsMo, path + ".vmdk");
                vmMo.attachDisk(new String[] { vmdkDataStorePath }, morDS);
            }
        }
        // find VM through datacenter (VM is not at the target host yet)
        vmMo = hyperHost.findVmOnPeerHyperHost(vmName);
        if (vmMo == null) {
            String msg = "VM " + vmName + " does not exist in VMware datacenter";
            s_logger.error(msg);
            throw new Exception(msg);
        }
        Pair<VirtualDisk, String> vdisk = vmMo.getDiskDevice(path);
        if (vdisk == null) {
            if (s_logger.isTraceEnabled())
                s_logger.trace("resize volume done (failed)");
            throw new Exception("No such disk device: " + path);
        }
        // IDE virtual disk cannot be re-sized if VM is running
        if (vdisk.second() != null && vdisk.second().contains("ide")) {
            throw new Exception("Re-sizing a virtual disk over IDE controller is not supported in VMware hypervisor. " + "Please re-try when virtual disk is attached to a VM using SCSI controller.");
        }
        if (vdisk.second() != null && !vdisk.second().toLowerCase().startsWith("scsi")) {
            s_logger.error("Unsupported disk device bus " + vdisk.second());
            throw new Exception("Unsupported disk device bus " + vdisk.second());
        }
        VirtualDisk disk = vdisk.first();
        if ((VirtualDiskFlatVer2BackingInfo) disk.getBacking() != null && ((VirtualDiskFlatVer2BackingInfo) disk.getBacking()).getParent() != null) {
            s_logger.error("Resize is not supported because Disk device has Parent " + ((VirtualDiskFlatVer2BackingInfo) disk.getBacking()).getParent().getUuid());
            throw new Exception("Resize is not supported because Disk device has Parent " + ((VirtualDiskFlatVer2BackingInfo) disk.getBacking()).getParent().getUuid());
        }
        String vmdkAbsFile = getAbsoluteVmdkFile(disk);
        if (vmdkAbsFile != null && !vmdkAbsFile.isEmpty()) {
            vmMo.updateAdapterTypeIfRequired(vmdkAbsFile);
        }
        disk.setCapacityInKB(newSize);
        VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();
        VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec();
        deviceConfigSpec.setDevice(disk);
        deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.EDIT);
        vmConfigSpec.getDeviceChange().add(deviceConfigSpec);
        if (!vmMo.configureVm(vmConfigSpec)) {
            throw new Exception("Failed to configure VM to resize disk. vmName: " + vmName);
        }
        return new ResizeVolumeAnswer(cmd, true, "success", newSize * 1024);
    } catch (Exception e) {
        s_logger.error("Unable to resize volume", e);
        String error = "Failed to resize volume: " + e.getMessage();
        return new ResizeVolumeAnswer(cmd, false, error);
    } finally {
        try {
            if (useWorkerVm == true) {
                s_logger.info("Destroy worker VM after volume resize");
                vmMo.detachDisk(vmdkDataStorePath, false);
                vmMo.destroy();
            }
        } catch (Throwable e) {
            s_logger.info("Failed to destroy worker VM: " + vmName);
        }
    }
}
Also used : VirtualDeviceConfigSpec(com.vmware.vim25.VirtualDeviceConfigSpec) VirtualMachineMO(com.cloud.hypervisor.vmware.mo.VirtualMachineMO) ResizeVolumeAnswer(com.cloud.agent.api.storage.ResizeVolumeAnswer) VmwareHypervisorHost(com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost) DatastoreMO(com.cloud.hypervisor.vmware.mo.DatastoreMO) ConnectException(java.net.ConnectException) IOException(java.io.IOException) RemoteException(java.rmi.RemoteException) InternalErrorException(com.cloud.exception.InternalErrorException) CloudException(com.cloud.exception.CloudException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ConfigurationException(javax.naming.ConfigurationException) VirtualDisk(com.vmware.vim25.VirtualDisk) VirtualMachineConfigSpec(com.vmware.vim25.VirtualMachineConfigSpec) VirtualDiskFlatVer2BackingInfo(com.vmware.vim25.VirtualDiskFlatVer2BackingInfo) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference)

Example 20 with Datacenter

use of com.vmware.vim25.mo.Datacenter in project coprhd-controller by CoprHD.

the class VcenterApiClient method createManagedEntityMap.

/*
     * Provide names of the vCenter elements and method will locate the MangedEntity representation
     * Each search is done within context of previous entity thus there is a dependency
     * Cluster
     * Datacenter
     * Host
     * Parameters are optional (ie, leave host null to only search datacenter and cluster)
     * Must provide parent element name or child will not be searched
     * hostConnectedPoweredOn ensures host is operational and ready for calls
     */
private Map<String, ManagedEntity> createManagedEntityMap(String datacenterName, String clusterNameOrMoRef, String hostname, boolean hostConnectedPoweredOn) throws VcenterSystemException, VcenterObjectNotFoundException, VcenterObjectConnectionException {
    if (serviceInstance == null) {
        _log.error("Invoke setup to open connection before using client");
        throw new VcenterSystemException("Invoke setup to open connection before using client");
    }
    try {
        Map<String, ManagedEntity> vcenterManagedEntityMap = new HashMap<String, ManagedEntity>();
        if (datacenterName != null && !datacenterName.trim().equals("")) {
            Datacenter datacenter = (Datacenter) new InventoryNavigator(serviceInstance.getRootFolder()).searchManagedEntity("Datacenter", datacenterName);
            if (datacenter == null) {
                _log.error("Datacenter " + datacenterName + " does not exist");
                throw new VcenterObjectNotFoundException("Datacenter " + datacenterName + " does not exist");
            }
            vcenterManagedEntityMap.put("Datacenter", datacenter);
            if (clusterNameOrMoRef != null && !clusterNameOrMoRef.trim().equals("")) {
                ClusterComputeResource clusterComputeResource = searchClusterComputeResource(datacenterName, clusterNameOrMoRef);
                vcenterManagedEntityMap.put("ClusterComputeResource", clusterComputeResource);
                if (hostname != null && !hostname.trim().equals("")) {
                    HostSystem hostSystem = findByHostname(clusterComputeResource, hostname);
                    if (hostSystem == null) {
                        _log.error("Host " + hostname + " does not exist");
                        throw new VcenterObjectNotFoundException("Host " + hostname + " does not exist");
                    }
                    if (hostConnectedPoweredOn) {
                        checkHostConnectedPoweredOn(hostSystem);
                    }
                    vcenterManagedEntityMap.put("HostSystem", hostSystem);
                }
            }
        }
        return vcenterManagedEntityMap;
    } catch (VcenterSystemException | VcenterObjectNotFoundException | VcenterObjectConnectionException e) {
        throw e;
    } catch (Exception e) {
        _log.error("getVcenterObjects exception " + e);
        throw new VcenterSystemException(e.getLocalizedMessage());
    }
}
Also used : ManagedEntity(com.vmware.vim25.mo.ManagedEntity) ClusterComputeResource(com.vmware.vim25.mo.ClusterComputeResource) HashMap(java.util.HashMap) VcenterObjectConnectionException(com.emc.storageos.vcentercontroller.exceptions.VcenterObjectConnectionException) InventoryNavigator(com.vmware.vim25.mo.InventoryNavigator) VcenterSystemException(com.emc.storageos.vcentercontroller.exceptions.VcenterSystemException) VcenterServerConnectionException(com.emc.storageos.vcentercontroller.exceptions.VcenterServerConnectionException) VcenterObjectConnectionException(com.emc.storageos.vcentercontroller.exceptions.VcenterObjectConnectionException) VcenterObjectNotFoundException(com.emc.storageos.vcentercontroller.exceptions.VcenterObjectNotFoundException) VcenterObjectNotFoundException(com.emc.storageos.vcentercontroller.exceptions.VcenterObjectNotFoundException) Datacenter(com.vmware.vim25.mo.Datacenter) HostSystem(com.vmware.vim25.mo.HostSystem) VcenterSystemException(com.emc.storageos.vcentercontroller.exceptions.VcenterSystemException)

Aggregations

ManagedObjectReference (com.vmware.vim25.ManagedObjectReference)28 PropertyFilterSpec (com.vmware.vim25.PropertyFilterSpec)23 TraversalSpec (com.vmware.vim25.TraversalSpec)21 ObjectSpec (com.vmware.vim25.ObjectSpec)20 PropertySpec (com.vmware.vim25.PropertySpec)20 HostSystem (com.vmware.vim25.mo.HostSystem)20 ArrayList (java.util.ArrayList)17 RemoteException (java.rmi.RemoteException)15 ObjectContent (com.vmware.vim25.ObjectContent)14 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)12 VcenterObjectConnectionException (com.emc.storageos.vcentercontroller.exceptions.VcenterObjectConnectionException)11 VcenterObjectNotFoundException (com.emc.storageos.vcentercontroller.exceptions.VcenterObjectNotFoundException)11 VcenterServerConnectionException (com.emc.storageos.vcentercontroller.exceptions.VcenterServerConnectionException)11 VcenterSystemException (com.emc.storageos.vcentercontroller.exceptions.VcenterSystemException)11 SelectionSpec (com.vmware.vim25.SelectionSpec)11 ClusterComputeResource (com.vmware.vim25.mo.ClusterComputeResource)11 VirtualMachineMO (com.cloud.hypervisor.vmware.mo.VirtualMachineMO)10 VmwareHypervisorHost (com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost)10 VcenterDataCenter (com.emc.storageos.db.client.model.VcenterDataCenter)10 Vcenter (com.emc.storageos.db.client.model.Vcenter)9