Search in sources :

Example 56 with VirtualMachineMO

use of com.cloud.hypervisor.vmware.mo.VirtualMachineMO in project cloudstack by apache.

the class VmwareStorageManagerImpl method execute.

@Override
public Answer execute(VmwareHostService hostService, CreatePrivateTemplateFromVolumeCommand cmd) {
    String secondaryStoragePoolURL = cmd.getSecondaryStorageUrl();
    String volumePath = cmd.getVolumePath();
    Long accountId = cmd.getAccountId();
    Long templateId = cmd.getTemplateId();
    String details = null;
    VmwareContext context = hostService.getServiceContext(cmd);
    try {
        VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd);
        VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName());
        if (vmMo == null) {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Unable to find the owner VM for CreatePrivateTemplateFromVolumeCommand on host " + hyperHost.getHyperHostName() + ", try within datacenter");
            }
            vmMo = hyperHost.findVmOnPeerHyperHost(cmd.getVmName());
            if (vmMo == null) {
                String msg = "Unable to find the owner VM for volume operation. vm: " + cmd.getVmName();
                s_logger.error(msg);
                throw new Exception(msg);
            }
        }
        Ternary<String, Long, Long> result = createTemplateFromVolume(vmMo, accountId, templateId, cmd.getUniqueName(), secondaryStoragePoolURL, volumePath, hostService.getWorkerName(context, cmd, 0, null), cmd.getNfsVersion());
        return new CreatePrivateTemplateAnswer(cmd, true, null, result.first(), result.third(), result.second(), cmd.getUniqueName(), ImageFormat.OVA);
    } catch (Throwable e) {
        return new CreatePrivateTemplateAnswer(cmd, false, hostService.createLogMessageException(e, cmd));
    }
}
Also used : VmwareContext(com.cloud.hypervisor.vmware.util.VmwareContext) VirtualMachineMO(com.cloud.hypervisor.vmware.mo.VirtualMachineMO) CreatePrivateTemplateAnswer(com.cloud.agent.api.storage.CreatePrivateTemplateAnswer) VmwareHypervisorHost(com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException)

Example 57 with VirtualMachineMO

use of com.cloud.hypervisor.vmware.mo.VirtualMachineMO in project cloudstack by apache.

the class VmwareCleanupMaid method gcLeftOverVMs.

public static synchronized void gcLeftOverVMs(VmwareContext context) {
    List<VmwareCleanupMaid> l = s_leftoverDummyVMs.get(context.getServerAddress());
    VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
    assert (mgr != null);
    if (l != null && l.size() > 0) {
        for (VmwareCleanupMaid cleanupMaid : l) {
            try {
                VirtualMachineMO vmMo = null;
                if (cleanupMaid.getDatacenterMorValue() != null) {
                    DatacenterMO dcMo = new DatacenterMO(context, "Datacenter", cleanupMaid.getDatacenterMorValue());
                    vmMo = dcMo.findVm(cleanupMaid.getVmName());
                } else {
                    assert (cleanupMaid.getHostMorValue() != null);
                    HostMO hostMo = new HostMO(context, "HostSystem", cleanupMaid.getHostMorValue());
                    ClusterMO clusterMo = new ClusterMO(context, hostMo.getHyperHostCluster());
                    vmMo = clusterMo.findVmOnHyperHost(cleanupMaid.getVmName());
                }
                if (vmMo != null) {
                    s_logger.info("Found left over dummy VM " + cleanupMaid.getVmName() + ", destroy it");
                    vmMo.destroy();
                }
            } catch (Throwable e) {
                s_logger.warn("Unable to destroy left over dummy VM " + cleanupMaid.getVmName());
            } finally {
            // FIXME                    mgr.popCleanupCheckpoint(cleanupMaid.getCheckPoint());
            }
        }
        l.clear();
    }
}
Also used : VmwareManager(com.cloud.hypervisor.vmware.manager.VmwareManager) HostMO(com.cloud.hypervisor.vmware.mo.HostMO) VirtualMachineMO(com.cloud.hypervisor.vmware.mo.VirtualMachineMO) ClusterMO(com.cloud.hypervisor.vmware.mo.ClusterMO) DatacenterMO(com.cloud.hypervisor.vmware.mo.DatacenterMO)

Example 58 with VirtualMachineMO

use of com.cloud.hypervisor.vmware.mo.VirtualMachineMO in project cloudstack by apache.

the class VmwareStorageProcessor method deleteVolume.

@Override
public Answer deleteVolume(DeleteCommand cmd) {
    try {
        VmwareContext context = hostService.getServiceContext(null);
        VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, null);
        VolumeObjectTO vol = (VolumeObjectTO) cmd.getData();
        DataStoreTO store = vol.getDataStore();
        PrimaryDataStoreTO primaryDataStoreTO = (PrimaryDataStoreTO) store;
        Map<String, String> details = primaryDataStoreTO.getDetails();
        boolean isManaged = false;
        String managedDatastoreName = null;
        if (details != null) {
            isManaged = Boolean.parseBoolean(details.get(PrimaryDataStoreTO.MANAGED));
            if (isManaged) {
                managedDatastoreName = getManagedDatastoreNameFromPath(vol.getPath());
            }
        }
        ManagedObjectReference morDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, isManaged ? managedDatastoreName : store.getUuid());
        if (morDs == null) {
            String msg = "Unable to find datastore based on volume mount point " + store.getUuid();
            s_logger.error(msg);
            throw new Exception(msg);
        }
        DatastoreMO dsMo = new DatastoreMO(context, morDs);
        ManagedObjectReference morDc = hyperHost.getHyperHostDatacenter();
        DatacenterMO dcMo = new DatacenterMO(context, morDc);
        ManagedObjectReference morCluster = hyperHost.getHyperHostCluster();
        ClusterMO clusterMo = new ClusterMO(context, morCluster);
        if (vol.getVolumeType() == Volume.Type.ROOT) {
            String vmName = vol.getVmName();
            if (vmName != null) {
                VirtualMachineMO vmMo = clusterMo.findVmOnHyperHost(vmName);
                if (vmMo == null) {
                    // Volume might be on a zone-wide storage pool, look for VM in datacenter
                    vmMo = dcMo.findVm(vmName);
                }
                List<Map<String, String>> dynamicTargetsToRemove = null;
                boolean deployAsIs = vol.isDeployAsIs();
                if (vmMo != null) {
                    if (s_logger.isInfoEnabled()) {
                        if (deployAsIs) {
                            s_logger.info("Destroying root volume " + vol.getPath() + " of deploy-as-is VM " + vmName);
                        } else {
                            s_logger.info("Destroy root volume and VM itself. vmName " + vmName);
                        }
                    }
                    VirtualMachineDiskInfo diskInfo = null;
                    if (vol.getChainInfo() != null)
                        diskInfo = _gson.fromJson(vol.getChainInfo(), VirtualMachineDiskInfo.class);
                    HostMO hostMo = vmMo.getRunningHost();
                    List<NetworkDetails> networks = vmMo.getNetworksWithDetails();
                    // tear down all devices first before we destroy the VM to avoid accidently delete disk backing files
                    if (VmwareResource.getVmState(vmMo) != PowerState.PowerOff) {
                        vmMo.safePowerOff(_shutdownWaitMs);
                    }
                    // call this before calling detachAllDisksExcept
                    // when expunging a VM, we need to see if any of its disks are serviced by managed storage
                    // if there is one or more disk serviced by managed storage, remove the iSCSI connection(s)
                    // don't remove the iSCSI connection(s) until the supported disk(s) is/are removed from the VM
                    // (removeManagedTargetsFromCluster should be called after detachAllDisksExcept and vm.destroy)
                    List<VirtualDisk> virtualDisks = vmMo.getVirtualDisks();
                    List<String> managedDatastoreNames = getManagedDatastoreNamesFromVirtualDisks(virtualDisks);
                    // Preserve other disks of the VM
                    List<String> detachedDisks = vmMo.detachAllDisksExcept(vol.getPath(), diskInfo != null ? diskInfo.getDiskDeviceBusName() : null);
                    VmwareStorageLayoutHelper.moveVolumeToRootFolder(new DatacenterMO(context, morDc), detachedDisks);
                    // vmMo.tearDownDevices(new Class<?>[] { VirtualDisk.class, VirtualEthernetCard.class });
                    if (isManaged) {
                        vmMo.unregisterVm();
                    } else {
                        vmMo.destroy();
                    }
                    // this.hostService.handleDatastoreAndVmdkDetach(iScsiName, storageHost, storagePort);
                    if (managedDatastoreNames != null && !managedDatastoreNames.isEmpty()) {
                        removeManagedTargetsFromCluster(managedDatastoreNames);
                    }
                    for (NetworkDetails netDetails : networks) {
                        if (netDetails.getGCTag() != null && netDetails.getGCTag().equalsIgnoreCase("true")) {
                            if (netDetails.getVMMorsOnNetwork() == null || netDetails.getVMMorsOnNetwork().length == 1) {
                                resource.cleanupNetwork(dcMo, netDetails);
                            }
                        }
                    }
                } else if (deployAsIs) {
                    if (s_logger.isInfoEnabled()) {
                        s_logger.info("Destroying root volume " + vol.getPath() + " of already removed deploy-as-is VM " + vmName);
                    }
                    // The disks of the deploy-as-is VM have been detached from the VM and moved to root folder
                    String deployAsIsRootDiskPath = dsMo.searchFileInSubFolders(vol.getPath() + VmwareResource.VMDK_EXTENSION, true, null);
                    if (StringUtils.isNotBlank(deployAsIsRootDiskPath)) {
                        if (s_logger.isInfoEnabled()) {
                            s_logger.info("Removing disk " + deployAsIsRootDiskPath);
                        }
                        dsMo.deleteFile(deployAsIsRootDiskPath, morDc, true);
                        String deltaFilePath = dsMo.searchFileInSubFolders(vol.getPath() + "-delta" + VmwareResource.VMDK_EXTENSION, true, null);
                        if (StringUtils.isNotBlank(deltaFilePath)) {
                            dsMo.deleteFile(deltaFilePath, morDc, true);
                        }
                    }
                }
                return new Answer(cmd, true, "");
            }
            if (s_logger.isInfoEnabled()) {
                s_logger.info("Destroy root volume directly from datastore");
            }
        }
        if (!isManaged) {
            VmwareStorageLayoutHelper.deleteVolumeVmdkFiles(dsMo, vol.getPath(), new DatacenterMO(context, morDc), VmwareManager.s_vmwareSearchExcludeFolder.value());
        }
        return new Answer(cmd, true, "Success");
    } catch (Throwable e) {
        return new Answer(cmd, false, hostService.createLogMessageException(e, cmd));
    }
}
Also used : HostMO(com.cloud.hypervisor.vmware.mo.HostMO) NetworkDetails(com.cloud.hypervisor.vmware.mo.NetworkDetails) ClusterMO(com.cloud.hypervisor.vmware.mo.ClusterMO) VirtualMachineDiskInfo(org.apache.cloudstack.utils.volume.VirtualMachineDiskInfo) VolumeObjectTO(org.apache.cloudstack.storage.to.VolumeObjectTO) PrimaryDataStoreTO(org.apache.cloudstack.storage.to.PrimaryDataStoreTO) DataStoreTO(com.cloud.agent.api.to.DataStoreTO) VirtualMachineMO(com.cloud.hypervisor.vmware.mo.VirtualMachineMO) VmwareHypervisorHost(com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) RemoteException(java.rmi.RemoteException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DatastoreMO(com.cloud.hypervisor.vmware.mo.DatastoreMO) VirtualDisk(com.vmware.vim25.VirtualDisk) VmwareContext(com.cloud.hypervisor.vmware.util.VmwareContext) ResignatureAnswer(org.apache.cloudstack.storage.command.ResignatureAnswer) SnapshotAndCopyAnswer(org.apache.cloudstack.storage.command.SnapshotAndCopyAnswer) CopyCmdAnswer(org.apache.cloudstack.storage.command.CopyCmdAnswer) AttachAnswer(org.apache.cloudstack.storage.command.AttachAnswer) CreateObjectAnswer(org.apache.cloudstack.storage.command.CreateObjectAnswer) Answer(com.cloud.agent.api.Answer) SyncVolumePathAnswer(org.apache.cloudstack.storage.command.SyncVolumePathAnswer) PrimaryDataStoreTO(org.apache.cloudstack.storage.to.PrimaryDataStoreTO) Map(java.util.Map) HashMap(java.util.HashMap) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference) DatacenterMO(com.cloud.hypervisor.vmware.mo.DatacenterMO)

Example 59 with VirtualMachineMO

use of com.cloud.hypervisor.vmware.mo.VirtualMachineMO in project cloudstack by apache.

the class VmwareStorageProcessor method createVmdk.

private void createVmdk(Command cmd, DatastoreMO dsMo, String vmdkDatastorePath, Long volumeSize) throws Exception {
    VmwareContext context = hostService.getServiceContext(null);
    VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, null);
    String dummyVmName = hostService.getWorkerName(context, cmd, 0, dsMo);
    VirtualMachineMO vmMo = HypervisorHostHelper.createWorkerVM(hyperHost, dsMo, dummyVmName, null);
    if (vmMo == null) {
        throw new Exception("Unable to create a dummy VM for volume creation");
    }
    Long volumeSizeToUse = volumeSize < dsMo.getDatastoreSummary().getFreeSpace() ? volumeSize : dsMo.getDatastoreSummary().getFreeSpace();
    vmMo.createDisk(vmdkDatastorePath, getMBsFromBytes(volumeSizeToUse), dsMo.getMor(), vmMo.getScsiDeviceControllerKey(), null);
    vmMo.detachDisk(vmdkDatastorePath, false);
    vmMo.destroy();
}
Also used : VmwareContext(com.cloud.hypervisor.vmware.util.VmwareContext) VirtualMachineMO(com.cloud.hypervisor.vmware.mo.VirtualMachineMO) VmwareHypervisorHost(com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) RemoteException(java.rmi.RemoteException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 60 with VirtualMachineMO

use of com.cloud.hypervisor.vmware.mo.VirtualMachineMO in project cloudstack by apache.

the class VmwareStorageProcessor method attachIso.

private Answer attachIso(DiskTO disk, boolean isAttach, String vmName, boolean force) {
    try {
        VmwareContext context = hostService.getServiceContext(null);
        VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, null);
        VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName);
        if (vmMo == null) {
            String msg = "Unable to find VM in vSphere to execute AttachIsoCommand, vmName: " + vmName;
            s_logger.error(msg);
            throw new Exception(msg);
        }
        TemplateObjectTO iso = (TemplateObjectTO) disk.getData();
        NfsTO nfsImageStore = (NfsTO) iso.getDataStore();
        String storeUrl = null;
        if (nfsImageStore != null) {
            storeUrl = nfsImageStore.getUrl();
        }
        if (storeUrl == null) {
            if (!iso.getName().equalsIgnoreCase(TemplateManager.VMWARE_TOOLS_ISO)) {
                String msg = "ISO store root url is not found in AttachIsoCommand";
                s_logger.error(msg);
                throw new Exception(msg);
            } else {
                if (isAttach) {
                    vmMo.mountToolsInstaller();
                } else {
                    try {
                        if (!vmMo.unmountToolsInstaller()) {
                            return new AttachAnswer("Failed to unmount vmware-tools installer ISO as the corresponding CDROM device is locked by VM. Please unmount the CDROM device inside the VM and ret-try.");
                        }
                    } catch (Throwable e) {
                        vmMo.detachIso(null, force);
                    }
                }
                return new AttachAnswer(disk);
            }
        }
        ManagedObjectReference morSecondaryDs = prepareSecondaryDatastoreOnHost(storeUrl);
        String isoPath = nfsImageStore.getUrl() + File.separator + iso.getPath();
        if (!isoPath.startsWith(storeUrl)) {
            assert (false);
            String msg = "ISO path does not start with the secondary storage root";
            s_logger.error(msg);
            throw new Exception(msg);
        }
        int isoNameStartPos = isoPath.lastIndexOf('/');
        String isoFileName = isoPath.substring(isoNameStartPos + 1);
        String isoStorePathFromRoot = isoPath.substring(storeUrl.length() + 1, isoNameStartPos);
        // TODO, check if iso is already attached, or if there is a previous
        // attachment
        DatastoreMO secondaryDsMo = new DatastoreMO(context, morSecondaryDs);
        String storeName = secondaryDsMo.getName();
        String isoDatastorePath = String.format("[%s] %s/%s", storeName, isoStorePathFromRoot, isoFileName);
        if (isAttach) {
            vmMo.attachIso(isoDatastorePath, morSecondaryDs, true, false, force);
        } else {
            vmMo.detachIso(isoDatastorePath, force);
        }
        return new AttachAnswer(disk);
    } catch (Throwable e) {
        if (e instanceof RemoteException) {
            s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context");
            hostService.invalidateServiceContext(null);
        }
        String message = String.format("AttachIsoCommand(%s) failed due to: [%s]. Also check if your guest os is a supported version", isAttach ? "attach" : "detach", VmwareHelper.getExceptionMessage(e));
        s_logger.error(message, e);
        return new AttachAnswer(message);
    }
}
Also used : VirtualMachineMO(com.cloud.hypervisor.vmware.mo.VirtualMachineMO) VmwareHypervisorHost(com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost) NfsTO(com.cloud.agent.api.to.NfsTO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) RemoteException(java.rmi.RemoteException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DatastoreMO(com.cloud.hypervisor.vmware.mo.DatastoreMO) VmwareContext(com.cloud.hypervisor.vmware.util.VmwareContext) TemplateObjectTO(org.apache.cloudstack.storage.to.TemplateObjectTO) RemoteException(java.rmi.RemoteException) AttachAnswer(org.apache.cloudstack.storage.command.AttachAnswer) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference)

Aggregations

VirtualMachineMO (com.cloud.hypervisor.vmware.mo.VirtualMachineMO)78 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)68 RemoteException (java.rmi.RemoteException)52 VmwareHypervisorHost (com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost)47 UnsupportedEncodingException (java.io.UnsupportedEncodingException)46 VmwareContext (com.cloud.hypervisor.vmware.util.VmwareContext)40 ManagedObjectReference (com.vmware.vim25.ManagedObjectReference)38 DatacenterMO (com.cloud.hypervisor.vmware.mo.DatacenterMO)28 CloudException (com.cloud.exception.CloudException)26 InternalErrorException (com.cloud.exception.InternalErrorException)26 IOException (java.io.IOException)26 ConnectException (java.net.ConnectException)26 ConfigurationException (javax.naming.ConfigurationException)26 DatastoreMO (com.cloud.hypervisor.vmware.mo.DatastoreMO)24 VirtualDisk (com.vmware.vim25.VirtualDisk)20 DatastoreFile (com.cloud.hypervisor.vmware.mo.DatastoreFile)17 Script (com.cloud.utils.script.Script)17 HostMO (com.cloud.hypervisor.vmware.mo.HostMO)16 File (java.io.File)14 Pair (com.cloud.utils.Pair)13