Search in sources :

Example 11 with VmwareContext

use of com.cloud.hypervisor.vmware.util.VmwareContext in project cloudstack by apache.

the class VmwareResource method fillHostInfo.

protected void fillHostInfo(StartupRoutingCommand cmd) {
    VmwareContext serviceContext = getServiceContext();
    Map<String, String> details = cmd.getHostDetails();
    if (details == null) {
        details = new HashMap<String, String>();
    }
    try {
        fillHostHardwareInfo(serviceContext, cmd);
        fillHostNetworkInfo(serviceContext, cmd);
        fillHostDetailsInfo(serviceContext, details);
    } catch (RuntimeFaultFaultMsg e) {
        s_logger.error("RuntimeFault while retrieving host info: " + e.toString(), e);
        throw new CloudRuntimeException("RuntimeFault while retrieving host info");
    } catch (RemoteException e) {
        s_logger.error("RemoteException while retrieving host info: " + e.toString(), e);
        invalidateServiceContext();
        throw new CloudRuntimeException("RemoteException while retrieving host info");
    } catch (Exception e) {
        s_logger.error("Exception while retrieving host info: " + e.toString(), e);
        invalidateServiceContext();
        throw new CloudRuntimeException("Exception while retrieving host info: " + e.toString());
    }
    cmd.setHostDetails(details);
    cmd.setName(_url);
    cmd.setGuid(_guid);
    cmd.setDataCenter(_dcId);
    cmd.setIqn(getIqn());
    cmd.setPod(_pod);
    cmd.setCluster(_cluster);
    cmd.setVersion(VmwareResource.class.getPackage().getImplementationVersion());
}
Also used : VmwareContext(com.cloud.hypervisor.vmware.util.VmwareContext) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) RuntimeFaultFaultMsg(com.vmware.vim25.RuntimeFaultFaultMsg) 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 12 with VmwareContext

use of com.cloud.hypervisor.vmware.util.VmwareContext in project cloudstack by apache.

the class VmwareResource method configNestedHVSupport.

protected void configNestedHVSupport(VirtualMachineMO vmMo, VirtualMachineTO vmSpec, VirtualMachineConfigSpec vmConfigSpec) throws Exception {
    VmwareContext context = vmMo.getContext();
    if ("true".equals(vmSpec.getDetails().get(VmDetailConstants.NESTED_VIRTUALIZATION_FLAG))) {
        if (s_logger.isDebugEnabled())
            s_logger.debug("Nested Virtualization enabled in configuration, checking hypervisor capability");
        ManagedObjectReference hostMor = vmMo.getRunningHost().getMor();
        ManagedObjectReference computeMor = context.getVimClient().getMoRefProp(hostMor, "parent");
        ManagedObjectReference environmentBrowser = context.getVimClient().getMoRefProp(computeMor, "environmentBrowser");
        HostCapability hostCapability = context.getService().queryTargetCapabilities(environmentBrowser, hostMor);
        Boolean nestedHvSupported = hostCapability.isNestedHVSupported();
        if (nestedHvSupported == null) {
            // nestedHvEnabled property is supported only since VMware 5.1. It's not defined for earlier versions.
            s_logger.warn("Hypervisor doesn't support nested virtualization, unable to set config for VM " + vmSpec.getName());
        } else if (nestedHvSupported.booleanValue()) {
            s_logger.debug("Hypervisor supports nested virtualization, enabling for VM " + vmSpec.getName());
            vmConfigSpec.setNestedHVEnabled(true);
        } else {
            s_logger.warn("Hypervisor doesn't support nested virtualization, unable to set config for VM " + vmSpec.getName());
            vmConfigSpec.setNestedHVEnabled(false);
        }
    }
}
Also used : VmwareContext(com.cloud.hypervisor.vmware.util.VmwareContext) HostCapability(com.vmware.vim25.HostCapability) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference)

Example 13 with VmwareContext

use of com.cloud.hypervisor.vmware.util.VmwareContext in project cloudstack by apache.

the class VmwareStorageManagerImpl method execute.

@Override
public CreateVMSnapshotAnswer execute(VmwareHostService hostService, CreateVMSnapshotCommand cmd) {
    List<VolumeObjectTO> volumeTOs = cmd.getVolumeTOs();
    String vmName = cmd.getVmName();
    String vmSnapshotName = cmd.getTarget().getSnapshotName();
    String vmSnapshotDesc = cmd.getTarget().getDescription();
    boolean snapshotMemory = cmd.getTarget().getType() == VMSnapshot.Type.DiskAndMemory;
    boolean quiescevm = cmd.getTarget().getQuiescevm();
    VirtualMachineMO vmMo = null;
    VmwareContext context = hostService.getServiceContext(cmd);
    try {
        VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd);
        // wait if there are already VM snapshot task running
        ManagedObjectReference taskmgr = context.getServiceContent().getTaskManager();
        List<ManagedObjectReference> tasks = context.getVimClient().getDynamicProperty(taskmgr, "recentTask");
        for (ManagedObjectReference taskMor : tasks) {
            TaskInfo info = (TaskInfo) (context.getVimClient().getDynamicProperty(taskMor, "info"));
            if (info.getEntityName().equals(cmd.getVmName()) && StringUtils.isNotBlank(info.getName()) && info.getName().equalsIgnoreCase("CreateSnapshot_Task")) {
                if (!(info.getState().equals(TaskInfoState.SUCCESS) || info.getState().equals(TaskInfoState.ERROR))) {
                    s_logger.debug("There is already a VM snapshot task running, wait for it");
                    context.getVimClient().waitForTask(taskMor);
                }
            }
        }
        vmMo = hyperHost.findVmOnHyperHost(vmName);
        if (vmMo == null) {
            vmMo = hyperHost.findVmOnPeerHyperHost(vmName);
        }
        if (vmMo == null) {
            String msg = "Unable to find VM for CreateVMSnapshotCommand";
            s_logger.info(msg);
            return new CreateVMSnapshotAnswer(cmd, false, msg);
        } else {
            if (vmMo.getSnapshotMor(vmSnapshotName) != null) {
                s_logger.info("VM snapshot " + vmSnapshotName + " already exists");
            } else if (!vmMo.createSnapshot(vmSnapshotName, vmSnapshotDesc, snapshotMemory, quiescevm)) {
                return new CreateVMSnapshotAnswer(cmd, false, "Unable to create snapshot due to esxi internal failed");
            }
            Map<String, String> mapNewDisk = getNewDiskMap(vmMo);
            setVolumeToPathAndSize(volumeTOs, mapNewDisk, context, hyperHost, cmd.getVmName());
            return new CreateVMSnapshotAnswer(cmd, cmd.getTarget(), volumeTOs);
        }
    } catch (Exception e) {
        String msg = e.getMessage();
        s_logger.error("failed to create snapshot for vm:" + vmName + " due to " + msg);
        try {
            if (vmMo.getSnapshotMor(vmSnapshotName) != null) {
                vmMo.removeSnapshot(vmSnapshotName, false);
            }
        } catch (Exception e1) {
            s_logger.info("[ignored]" + "error during snapshot remove: " + e1.getLocalizedMessage());
        }
        return new CreateVMSnapshotAnswer(cmd, false, e.getMessage());
    }
}
Also used : VirtualMachineMO(com.cloud.hypervisor.vmware.mo.VirtualMachineMO) VmwareHypervisorHost(com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost) RemoteException(java.rmi.RemoteException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) TaskInfo(com.vmware.vim25.TaskInfo) VmwareContext(com.cloud.hypervisor.vmware.util.VmwareContext) CreateVMSnapshotAnswer(com.cloud.agent.api.CreateVMSnapshotAnswer) VolumeObjectTO(org.apache.cloudstack.storage.to.VolumeObjectTO) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference)

Example 14 with VmwareContext

use of com.cloud.hypervisor.vmware.util.VmwareContext in project cloudstack by apache.

the class VmwareStorageManagerImpl method execute.

@Override
public Answer execute(VmwareHostService hostService, PrimaryStorageDownloadCommand cmd) {
    String secondaryStorageUrl = cmd.getSecondaryStorageUrl();
    assert (secondaryStorageUrl != null);
    String templateUrl = cmd.getUrl();
    String templateName = null;
    String mountPoint = null;
    if (templateUrl.endsWith(".ova")) {
        int index = templateUrl.lastIndexOf("/");
        mountPoint = templateUrl.substring(0, index);
        mountPoint = mountPoint.substring(secondaryStorageUrl.length() + 1);
        if (!mountPoint.endsWith("/")) {
            mountPoint = mountPoint + "/";
        }
        templateName = templateUrl.substring(index + 1).replace("." + ImageFormat.OVA.getFileExtension(), "");
        if (templateName == null || templateName.isEmpty()) {
            templateName = cmd.getName();
        }
    } else {
        mountPoint = templateUrl.substring(secondaryStorageUrl.length() + 1);
        if (!mountPoint.endsWith("/")) {
            mountPoint = mountPoint + "/";
        }
        templateName = cmd.getName();
    }
    VmwareContext context = hostService.getServiceContext(cmd);
    try {
        VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd);
        String templateUuidName = UUID.nameUUIDFromBytes((templateName + "@" + cmd.getPoolUuid() + "-" + hyperHost.getMor().getValue()).getBytes("UTF-8")).toString();
        // truncate template name to 32 chars to ensure they work well with vSphere API's.
        templateUuidName = templateUuidName.replace("-", "");
        DatacenterMO dcMo = new DatacenterMO(context, hyperHost.getHyperHostDatacenter());
        VirtualMachineMO templateMo = VmwareHelper.pickOneVmOnRunningHost(dcMo.findVmByNameAndLabel(templateUuidName), true);
        if (templateMo == null) {
            if (s_logger.isInfoEnabled()) {
                s_logger.info("Template " + templateName + " is not setup yet, setup template from secondary storage with uuid name: " + templateUuidName);
            }
            ManagedObjectReference morDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, cmd.getPoolUuid());
            assert (morDs != null);
            DatastoreMO primaryStorageDatastoreMo = new DatastoreMO(context, morDs);
            copyTemplateFromSecondaryToPrimary(hyperHost, primaryStorageDatastoreMo, secondaryStorageUrl, mountPoint, templateName, templateUuidName, cmd.getNfsVersion());
        } else {
            s_logger.info("Template " + templateName + " has already been setup, skip the template setup process in primary storage");
        }
        return new PrimaryStorageDownloadAnswer(templateUuidName, 0);
    } catch (Throwable e) {
        if (e instanceof RemoteException) {
            hostService.invalidateServiceContext(context);
        }
        String msg = "Unable to execute PrimaryStorageDownloadCommand due to exception";
        s_logger.error(msg, e);
        return new PrimaryStorageDownloadAnswer(msg);
    }
}
Also used : VmwareContext(com.cloud.hypervisor.vmware.util.VmwareContext) PrimaryStorageDownloadAnswer(com.cloud.agent.api.storage.PrimaryStorageDownloadAnswer) VirtualMachineMO(com.cloud.hypervisor.vmware.mo.VirtualMachineMO) VmwareHypervisorHost(com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost) RemoteException(java.rmi.RemoteException) DatastoreMO(com.cloud.hypervisor.vmware.mo.DatastoreMO) DatacenterMO(com.cloud.hypervisor.vmware.mo.DatacenterMO) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference)

Example 15 with VmwareContext

use of com.cloud.hypervisor.vmware.util.VmwareContext in project cloudstack by apache.

the class VmwareManagerImpl method addVmwareDatacenter.

@Override
@DB
public VmwareDatacenterVO addVmwareDatacenter(AddVmwareDcCmd cmd) throws ResourceInUseException {
    VmwareDatacenterVO vmwareDc = null;
    Long zoneId = cmd.getZoneId();
    String userName = cmd.getUsername();
    String password = cmd.getPassword();
    String vCenterHost = cmd.getVcenter();
    String vmwareDcName = cmd.getName();
    // Validate username, password, VMware DC name and vCenter
    if (userName == null) {
        throw new InvalidParameterValueException("Missing or invalid parameter username.");
    }
    if (password == null) {
        throw new InvalidParameterValueException("Missing or invalid parameter username.");
    }
    if (vmwareDcName == null) {
        throw new InvalidParameterValueException("Missing or invalid parameter name. Please provide valid VMware datacenter name.");
    }
    if (vCenterHost == null) {
        throw new InvalidParameterValueException("Missing or invalid parameter name. " + "Please provide valid VMware vCenter server's IP address or fully qualified domain name.");
    }
    if (zoneId == null) {
        throw new InvalidParameterValueException("Missing or invalid parameter name. " + "Please provide valid zone id.");
    }
    // Zone validation
    validateZone(zoneId);
    VmwareDatacenterZoneMapVO vmwareDcZoneMap = _vmwareDcZoneMapDao.findByZoneId(zoneId);
    // Check if zone is associated with VMware DC
    if (vmwareDcZoneMap != null) {
        // Check if the associated VMware DC matches the one specified in API params
        // This check would yield success as the association exists between same entities (zone and VMware DC)
        // This scenario would result in if the API addVmwareDc is called more than once with same parameters.
        Long associatedVmwareDcId = vmwareDcZoneMap.getVmwareDcId();
        VmwareDatacenterVO associatedVmwareDc = _vmwareDcDao.findById(associatedVmwareDcId);
        if (associatedVmwareDc.getVcenterHost().equalsIgnoreCase(vCenterHost) && associatedVmwareDc.getVmwareDatacenterName().equalsIgnoreCase(vmwareDcName)) {
            s_logger.info("Ignoring API call addVmwareDc, because VMware DC " + vCenterHost + "/" + vmwareDcName + " is already associated with specified zone with id " + zoneId);
            return associatedVmwareDc;
        } else {
            throw new CloudRuntimeException("Zone " + zoneId + " is already associated with a VMware datacenter. " + "Only 1 VMware DC can be associated with a zone.");
        }
    }
    // Zone validation to check if the zone already has resources.
    // Association of VMware DC to zone is not allowed if zone already has resources added.
    validateZoneWithResources(zoneId, "add VMware datacenter to zone");
    // Check if DC is already part of zone
    // In that case vmware_data_center table should have the DC
    vmwareDc = _vmwareDcDao.getVmwareDatacenterByGuid(vmwareDcName + "@" + vCenterHost);
    if (vmwareDc != null) {
        throw new ResourceInUseException("This DC is already part of other CloudStack zone(s). Cannot add this DC to more zones.");
    }
    VmwareContext context = null;
    DatacenterMO dcMo = null;
    String dcCustomFieldValue;
    boolean addDcCustomFieldDef = false;
    boolean dcInUse = false;
    String guid;
    ManagedObjectReference dcMor;
    try {
        context = VmwareContextFactory.create(vCenterHost, userName, password);
        // Check if DC exists on vCenter
        dcMo = new DatacenterMO(context, vmwareDcName);
        dcMor = dcMo.getMor();
        if (dcMor == null) {
            String msg = "Unable to find VMware DC " + vmwareDcName + " in vCenter " + vCenterHost + ". ";
            s_logger.error(msg);
            throw new InvalidParameterValueException(msg);
        }
        // Check if DC is already associated with another cloudstack deployment
        // Get custom field property cloud.zone over this DC
        guid = vmwareDcName + "@" + vCenterHost;
        dcCustomFieldValue = dcMo.getCustomFieldValue(CustomFieldConstants.CLOUD_ZONE);
        if (dcCustomFieldValue == null) {
            addDcCustomFieldDef = true;
        }
        dcInUse = Boolean.parseBoolean(dcCustomFieldValue);
        if (dcInUse) {
            throw new ResourceInUseException("This DC is being managed by other CloudStack deployment. Cannot add this DC to zone.");
        }
        // Add DC to database into vmware_data_center table
        vmwareDc = new VmwareDatacenterVO(guid, vmwareDcName, vCenterHost, userName, password);
        vmwareDc = _vmwareDcDao.persist(vmwareDc);
        // Map zone with vmware datacenter
        vmwareDcZoneMap = new VmwareDatacenterZoneMapVO(zoneId, vmwareDc.getId());
        vmwareDcZoneMap = _vmwareDcZoneMapDao.persist(vmwareDcZoneMap);
        // Set custom field for this DC
        if (addDcCustomFieldDef) {
            dcMo.ensureCustomFieldDef(CustomFieldConstants.CLOUD_ZONE);
        }
        dcMo.setCustomFieldValue(CustomFieldConstants.CLOUD_ZONE, "true");
    } catch (Throwable e) {
        String msg = "Failed to add VMware DC to zone ";
        if (e instanceof RemoteException) {
            msg = "Encountered remote exception at vCenter. " + VmwareHelper.getExceptionMessage(e);
        } else {
            msg += "due to : " + e.getMessage();
        }
        throw new CloudRuntimeException(msg);
    } finally {
        if (context != null) {
            context.close();
        }
        context = null;
    }
    return vmwareDc;
}
Also used : VmwareDatacenterZoneMapVO(com.cloud.hypervisor.vmware.VmwareDatacenterZoneMapVO) VmwareContext(com.cloud.hypervisor.vmware.util.VmwareContext) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) VmwareDatacenterVO(com.cloud.hypervisor.vmware.VmwareDatacenterVO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ResourceInUseException(com.cloud.exception.ResourceInUseException) RemoteException(java.rmi.RemoteException) DatacenterMO(com.cloud.hypervisor.vmware.mo.DatacenterMO) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference) DB(com.cloud.utils.db.DB)

Aggregations

VmwareContext (com.cloud.hypervisor.vmware.util.VmwareContext)76 RemoteException (java.rmi.RemoteException)58 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)47 VmwareHypervisorHost (com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost)45 UnsupportedEncodingException (java.io.UnsupportedEncodingException)35 ManagedObjectReference (com.vmware.vim25.ManagedObjectReference)32 VirtualMachineMO (com.cloud.hypervisor.vmware.mo.VirtualMachineMO)28 IOException (java.io.IOException)26 CloudException (com.cloud.exception.CloudException)25 ConfigurationException (javax.naming.ConfigurationException)25 InternalErrorException (com.cloud.exception.InternalErrorException)23 ConnectException (java.net.ConnectException)23 DatastoreMO (com.cloud.hypervisor.vmware.mo.DatastoreMO)16 VmwareManager (com.cloud.hypervisor.vmware.manager.VmwareManager)14 HostMO (com.cloud.hypervisor.vmware.mo.HostMO)13 VolumeObjectTO (org.apache.cloudstack.storage.to.VolumeObjectTO)13 DataStoreTO (com.cloud.agent.api.to.DataStoreTO)12 PrimaryDataStoreTO (org.apache.cloudstack.storage.to.PrimaryDataStoreTO)12 DatacenterMO (com.cloud.hypervisor.vmware.mo.DatacenterMO)11 CreatePrivateTemplateAnswer (com.cloud.agent.api.storage.CreatePrivateTemplateAnswer)10