Search in sources :

Example 16 with VirtualMachineMO

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

the class VmwareResource method execute.

protected Answer execute(GetVncPortCommand cmd) {
    if (s_logger.isTraceEnabled()) {
        s_logger.trace("Executing resource GetVncPortCommand: " + _gson.toJson(cmd));
    }
    try {
        VmwareContext context = getServiceContext();
        VmwareHypervisorHost hyperHost = getHyperHost(context);
        assert (hyperHost instanceof HostMO);
        VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
        VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getName());
        if (vmMo == null) {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Unable to find the owner VM for GetVncPortCommand on host " + hyperHost.getHyperHostName() + ", try within datacenter");
            }
            vmMo = hyperHost.findVmOnPeerHyperHost(cmd.getName());
            if (vmMo == null) {
                throw new Exception("Unable to find VM in vSphere, vm: " + cmd.getName());
            }
        }
        Pair<String, Integer> portInfo = vmMo.getVncPort(mgr.getManagementPortGroupByHost((HostMO) hyperHost));
        if (s_logger.isTraceEnabled()) {
            s_logger.trace("Found vnc port info. vm: " + cmd.getName() + " host: " + portInfo.first() + ", vnc port: " + portInfo.second());
        }
        return new GetVncPortAnswer(cmd, portInfo.first(), portInfo.second());
    } catch (Throwable e) {
        if (e instanceof RemoteException) {
            s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context");
            invalidateServiceContext();
        }
        String msg = "GetVncPortCommand failed due to " + VmwareHelper.getExceptionMessage(e);
        s_logger.error(msg, e);
        return new GetVncPortAnswer(cmd, msg);
    }
}
Also used : VmwareContext(com.cloud.hypervisor.vmware.util.VmwareContext) GetVncPortAnswer(com.cloud.agent.api.GetVncPortAnswer) HostMO(com.cloud.hypervisor.vmware.mo.HostMO) VmwareManager(com.cloud.hypervisor.vmware.manager.VmwareManager) 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)

Example 17 with VirtualMachineMO

use of com.cloud.hypervisor.vmware.mo.VirtualMachineMO 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 18 with VirtualMachineMO

use of com.cloud.hypervisor.vmware.mo.VirtualMachineMO in project CloudStack-archive by CloudStack-extras.

the class VmwareHelper method pickOneVmOnRunningHost.

public static VirtualMachineMO pickOneVmOnRunningHost(List<VirtualMachineMO> vmList, boolean bFirstFit) throws Exception {
    List<VirtualMachineMO> candidates = new ArrayList<VirtualMachineMO>();
    for (VirtualMachineMO vmMo : vmList) {
        HostMO hostMo = vmMo.getRunningHost();
        if (hostMo.isHyperHostConnected())
            candidates.add(vmMo);
    }
    if (candidates.size() == 0)
        return null;
    if (bFirstFit)
        return candidates.get(0);
    Random random = new Random();
    return candidates.get(random.nextInt(candidates.size()));
}
Also used : Random(java.util.Random) HostMO(com.cloud.hypervisor.vmware.mo.HostMO) VirtualMachineMO(com.cloud.hypervisor.vmware.mo.VirtualMachineMO) ArrayList(java.util.ArrayList)

Example 19 with VirtualMachineMO

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

the class VmwareResource method execute.

protected Answer execute(AttachIsoCommand cmd) {
    if (s_logger.isInfoEnabled()) {
        s_logger.info("Executing resource AttachIsoCommand: " + _gson.toJson(cmd));
    }
    try {
        VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext());
        VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName());
        if (vmMo == null) {
            String msg = "Unable to find VM in vSphere to execute AttachIsoCommand, vmName: " + cmd.getVmName();
            s_logger.error(msg);
            throw new Exception(msg);
        }
        String storeUrl = cmd.getStoreUrl();
        if (storeUrl == null) {
            if (!cmd.getIsoPath().equalsIgnoreCase("vmware-tools.iso")) {
                String msg = "ISO store root url is not found in AttachIsoCommand";
                s_logger.error(msg);
                throw new Exception(msg);
            } else {
                if (cmd.isAttach()) {
                    vmMo.mountToolsInstaller();
                } else {
                    try {
                        if (!vmMo.unmountToolsInstaller()) {
                            return new Answer(cmd, false, "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);
                    }
                }
                return new Answer(cmd);
            }
        }
        ManagedObjectReference morSecondaryDs = prepareSecondaryDatastoreOnHost(storeUrl);
        String isoPath = cmd.getIsoPath();
        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(), isoNameStartPos);
        // TODO, check if iso is already attached, or if there is a previous
        // attachment
        DatastoreMO secondaryDsMo = new DatastoreMO(getServiceContext(), morSecondaryDs);
        String storeName = secondaryDsMo.getName();
        String isoDatastorePath = String.format("[%s] %s%s", storeName, isoStorePathFromRoot, isoFileName);
        if (cmd.isAttach()) {
            vmMo.attachIso(isoDatastorePath, morSecondaryDs, true, false);
        } else {
            vmMo.detachIso(isoDatastorePath);
        }
        return new Answer(cmd);
    } catch (Throwable e) {
        if (e instanceof RemoteException) {
            s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context");
            invalidateServiceContext();
        }
        if (cmd.isAttach()) {
            String msg = "AttachIsoCommand(attach) failed due to " + VmwareHelper.getExceptionMessage(e);
            s_logger.error(msg, e);
            return new Answer(cmd, false, msg);
        } else {
            String msg = "AttachIsoCommand(detach) failed due to " + VmwareHelper.getExceptionMessage(e);
            s_logger.warn(msg, e);
            return new Answer(cmd, false, msg);
        }
    }
}
Also used : ModifyTargetsAnswer(com.cloud.agent.api.ModifyTargetsAnswer) GetVncPortAnswer(com.cloud.agent.api.GetVncPortAnswer) ManageSnapshotAnswer(com.cloud.agent.api.ManageSnapshotAnswer) CreatePrivateTemplateAnswer(com.cloud.agent.api.storage.CreatePrivateTemplateAnswer) ModifyStoragePoolAnswer(com.cloud.agent.api.ModifyStoragePoolAnswer) MigrateVolumeAnswer(com.cloud.agent.api.storage.MigrateVolumeAnswer) SetupAnswer(com.cloud.agent.api.SetupAnswer) GetVmStatsAnswer(com.cloud.agent.api.GetVmStatsAnswer) StopAnswer(com.cloud.agent.api.StopAnswer) NetworkUsageAnswer(com.cloud.agent.api.NetworkUsageAnswer) Answer(com.cloud.agent.api.Answer) UnPlugNicAnswer(com.cloud.agent.api.UnPlugNicAnswer) CheckOnHostAnswer(com.cloud.agent.api.CheckOnHostAnswer) CheckHealthAnswer(com.cloud.agent.api.CheckHealthAnswer) RevertToVMSnapshotAnswer(com.cloud.agent.api.RevertToVMSnapshotAnswer) CopyVolumeAnswer(com.cloud.agent.api.storage.CopyVolumeAnswer) CreateVMSnapshotAnswer(com.cloud.agent.api.CreateVMSnapshotAnswer) DeleteVMSnapshotAnswer(com.cloud.agent.api.DeleteVMSnapshotAnswer) MaintainAnswer(com.cloud.agent.api.MaintainAnswer) GetHostStatsAnswer(com.cloud.agent.api.GetHostStatsAnswer) CheckSshAnswer(com.cloud.agent.api.check.CheckSshAnswer) RebootAnswer(com.cloud.agent.api.RebootAnswer) PrimaryStorageDownloadAnswer(com.cloud.agent.api.storage.PrimaryStorageDownloadAnswer) StartAnswer(com.cloud.agent.api.StartAnswer) GetStorageStatsAnswer(com.cloud.agent.api.GetStorageStatsAnswer) MigrateAnswer(com.cloud.agent.api.MigrateAnswer) CreateVolumeFromSnapshotAnswer(com.cloud.agent.api.CreateVolumeFromSnapshotAnswer) CheckNetworkAnswer(com.cloud.agent.api.CheckNetworkAnswer) PlugNicAnswer(com.cloud.agent.api.PlugNicAnswer) ScaleVmAnswer(com.cloud.agent.api.ScaleVmAnswer) MigrateWithStorageAnswer(com.cloud.agent.api.MigrateWithStorageAnswer) ResizeVolumeAnswer(com.cloud.agent.api.storage.ResizeVolumeAnswer) BackupSnapshotAnswer(com.cloud.agent.api.BackupSnapshotAnswer) CheckVirtualMachineAnswer(com.cloud.agent.api.CheckVirtualMachineAnswer) ValidateSnapshotAnswer(com.cloud.agent.api.ValidateSnapshotAnswer) ReadyAnswer(com.cloud.agent.api.ReadyAnswer) PrepareForMigrationAnswer(com.cloud.agent.api.PrepareForMigrationAnswer) GetVmDiskStatsAnswer(com.cloud.agent.api.GetVmDiskStatsAnswer) 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) DatastoreMO(com.cloud.hypervisor.vmware.mo.DatastoreMO) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference)

Example 20 with VirtualMachineMO

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

the class VmwareResource method configureVnc.

protected OptionValue[] configureVnc(OptionValue[] optionsToMerge, VmwareHypervisorHost hyperHost, String vmName, String vncPassword, String keyboardLayout) throws Exception {
    VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName);
    VmwareManager mgr = hyperHost.getContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
    if (!mgr.beginExclusiveOperation(600))
        throw new Exception("Unable to begin exclusive operation, lock time out");
    try {
        int maxVncPorts = 64;
        int vncPort = 0;
        Random random = new Random();
        HostMO vmOwnerHost = vmMo.getRunningHost();
        ManagedObjectReference morParent = vmOwnerHost.getParentMor();
        HashMap<String, Integer> portInfo;
        if (morParent.getType().equalsIgnoreCase("ClusterComputeResource")) {
            ClusterMO clusterMo = new ClusterMO(vmOwnerHost.getContext(), morParent);
            portInfo = clusterMo.getVmVncPortsOnCluster();
        } else {
            portInfo = vmOwnerHost.getVmVncPortsOnHost();
        }
        // allocate first at 5900 - 5964 range
        Collection<Integer> existingPorts = portInfo.values();
        int val = random.nextInt(maxVncPorts);
        int startVal = val;
        do {
            if (!existingPorts.contains(5900 + val)) {
                vncPort = 5900 + val;
                break;
            }
            val = (++val) % maxVncPorts;
        } while (val != startVal);
        if (vncPort == 0) {
            s_logger.info("we've run out of range for ports between 5900-5964 for the cluster, we will try port range at 59000-60000");
            Pair<Integer, Integer> additionalRange = mgr.getAddiionalVncPortRange();
            maxVncPorts = additionalRange.second();
            val = random.nextInt(maxVncPorts);
            startVal = val;
            do {
                if (!existingPorts.contains(additionalRange.first() + val)) {
                    vncPort = additionalRange.first() + val;
                    break;
                }
                val = (++val) % maxVncPorts;
            } while (val != startVal);
        }
        if (vncPort == 0) {
            throw new Exception("Unable to find an available VNC port on host");
        }
        if (s_logger.isInfoEnabled()) {
            s_logger.info("Configure VNC port for VM " + vmName + ", port: " + vncPort + ", host: " + vmOwnerHost.getHyperHostName());
        }
        return VmwareHelper.composeVncOptions(optionsToMerge, true, vncPassword, vncPort, keyboardLayout);
    } finally {
        try {
            mgr.endExclusiveOperation();
        } catch (Throwable e) {
            assert (false);
            s_logger.error("Unexpected exception ", e);
        }
    }
}
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) 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) Random(java.util.Random) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference)

Aggregations

VirtualMachineMO (com.cloud.hypervisor.vmware.mo.VirtualMachineMO)51 RemoteException (java.rmi.RemoteException)46 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)41 VmwareHypervisorHost (com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost)35 UnsupportedEncodingException (java.io.UnsupportedEncodingException)31 VmwareContext (com.cloud.hypervisor.vmware.util.VmwareContext)28 ManagedObjectReference (com.vmware.vim25.ManagedObjectReference)25 CloudException (com.cloud.exception.CloudException)17 InternalErrorException (com.cloud.exception.InternalErrorException)17 IOException (java.io.IOException)17 ConnectException (java.net.ConnectException)17 ConfigurationException (javax.naming.ConfigurationException)17 DatastoreMO (com.cloud.hypervisor.vmware.mo.DatastoreMO)16 HostMO (com.cloud.hypervisor.vmware.mo.HostMO)14 DatacenterMO (com.cloud.hypervisor.vmware.mo.DatacenterMO)13 VolumeObjectTO (org.apache.cloudstack.storage.to.VolumeObjectTO)11 VirtualDisk (com.vmware.vim25.VirtualDisk)9 DataStoreTO (com.cloud.agent.api.to.DataStoreTO)8 Script (com.cloud.utils.script.Script)8 VmwareManager (com.cloud.hypervisor.vmware.manager.VmwareManager)7