Search in sources :

Example 6 with DatacenterMO

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

the class VmwareManagerImpl method removeVmwareDatacenter.

@Override
public boolean removeVmwareDatacenter(RemoveVmwareDcCmd cmd) throws ResourceInUseException {
    Long zoneId = cmd.getZoneId();
    // Validate zone
    validateZone(zoneId);
    // 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, "remove VMware datacenter to zone");
    // Get DC associated with this zone
    VmwareDatacenterVO vmwareDatacenter;
    String vmwareDcName;
    String vCenterHost;
    String userName;
    String password;
    DatacenterMO dcMo = null;
    final VmwareDatacenterZoneMapVO vmwareDcZoneMap = _vmwareDcZoneMapDao.findByZoneId(zoneId);
    // Check if zone is associated with VMware DC
    if (vmwareDcZoneMap == null) {
        throw new CloudRuntimeException("Zone " + zoneId + " is not associated with any VMware datacenter.");
    }
    final long vmwareDcId = vmwareDcZoneMap.getVmwareDcId();
    vmwareDatacenter = _vmwareDcDao.findById(vmwareDcId);
    vmwareDcName = vmwareDatacenter.getVmwareDatacenterName();
    vCenterHost = vmwareDatacenter.getVcenterHost();
    userName = vmwareDatacenter.getUser();
    password = vmwareDatacenter.getPassword();
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(TransactionStatus status) {
            // Remove the VMware datacenter entry in table vmware_data_center
            _vmwareDcDao.remove(vmwareDcId);
            // Remove the map entry in table vmware_data_center_zone_map
            _vmwareDcZoneMapDao.remove(vmwareDcZoneMap.getId());
        }
    });
    // Construct context
    VmwareContext context = null;
    try {
        context = VmwareContextFactory.create(vCenterHost, userName, password);
        // Check if DC exists on vCenter
        try {
            dcMo = new DatacenterMO(context, vmwareDcName);
        } catch (Throwable t) {
            String msg = "Unable to find DC " + vmwareDcName + " in vCenter " + vCenterHost;
            s_logger.error(msg);
            throw new DiscoveryException(msg);
        }
        assert (dcMo != null);
        // Reset custom field property cloud.zone over this DC
        dcMo.setCustomFieldValue(CustomFieldConstants.CLOUD_ZONE, "false");
        s_logger.info("Sucessfully reset custom field property cloud.zone over DC " + vmwareDcName);
    } catch (Exception e) {
        String msg = "Unable to reset custom field property cloud.zone over DC " + vmwareDcName + " due to : " + VmwareHelper.getExceptionMessage(e);
        s_logger.error(msg);
        throw new CloudRuntimeException(msg);
    } finally {
        if (context != null) {
            context.close();
        }
        context = null;
    }
    return true;
}
Also used : VmwareDatacenterZoneMapVO(com.cloud.hypervisor.vmware.VmwareDatacenterZoneMapVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) DiscoveredWithErrorException(com.cloud.exception.DiscoveredWithErrorException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) IOException(java.io.IOException) ResourceInUseException(com.cloud.exception.ResourceInUseException) URISyntaxException(java.net.URISyntaxException) DiscoveryException(com.cloud.exception.DiscoveryException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) RemoteException(java.rmi.RemoteException) ConfigurationException(javax.naming.ConfigurationException) VmwareContext(com.cloud.hypervisor.vmware.util.VmwareContext) VmwareDatacenterVO(com.cloud.hypervisor.vmware.VmwareDatacenterVO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) DiscoveryException(com.cloud.exception.DiscoveryException) DatacenterMO(com.cloud.hypervisor.vmware.mo.DatacenterMO)

Example 7 with DatacenterMO

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

the class VmwareStorageProcessor method createTemplateFromVolume.

@Override
public Answer createTemplateFromVolume(CopyCommand cmd) {
    VolumeObjectTO volume = (VolumeObjectTO) cmd.getSrcTO();
    TemplateObjectTO template = (TemplateObjectTO) cmd.getDestTO();
    DataStoreTO imageStore = template.getDataStore();
    if (!(imageStore instanceof NfsTO)) {
        return new CopyCmdAnswer("unsupported protocol");
    }
    NfsTO nfsImageStore = (NfsTO) imageStore;
    String secondaryStoragePoolURL = nfsImageStore.getUrl();
    String volumePath = volume.getPath();
    String details = null;
    VmwareContext context = hostService.getServiceContext(cmd);
    try {
        VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd);
        VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(volume.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(volume.getVmName());
            if (vmMo == null) {
                // This means either the volume is on a zone wide storage pool or VM is deleted by external entity.
                // Look for the VM in the datacenter.
                ManagedObjectReference dcMor = hyperHost.getHyperHostDatacenter();
                DatacenterMO dcMo = new DatacenterMO(context, dcMor);
                vmMo = dcMo.findVm(volume.getVmName());
            }
            if (vmMo == null) {
                String msg = "Unable to find the owner VM for volume operation. vm: " + volume.getVmName();
                s_logger.error(msg);
                throw new Exception(msg);
            }
        }
        Ternary<String, Long, Long> result = createTemplateFromVolume(vmMo, template.getPath(), template.getId(), template.getName(), secondaryStoragePoolURL, volumePath, hostService.getWorkerName(context, cmd, 0), _nfsVersion);
        TemplateObjectTO newTemplate = new TemplateObjectTO();
        newTemplate.setPath(result.first());
        newTemplate.setFormat(ImageFormat.OVA);
        newTemplate.setSize(result.third());
        newTemplate.setPhysicalSize(result.second());
        return new CopyCmdAnswer(newTemplate);
    } catch (Throwable e) {
        if (e instanceof RemoteException) {
            hostService.invalidateServiceContext(context);
        }
        s_logger.error("Unexpecpted exception ", e);
        details = "create template from volume exception: " + VmwareHelper.getExceptionMessage(e);
        return new CopyCmdAnswer(details);
    }
}
Also used : 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) NfsTO(com.cloud.agent.api.to.NfsTO) RemoteException(java.rmi.RemoteException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VmwareContext(com.cloud.hypervisor.vmware.util.VmwareContext) VolumeObjectTO(org.apache.cloudstack.storage.to.VolumeObjectTO) TemplateObjectTO(org.apache.cloudstack.storage.to.TemplateObjectTO) RemoteException(java.rmi.RemoteException) CopyCmdAnswer(org.apache.cloudstack.storage.command.CopyCmdAnswer) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference) DatacenterMO(com.cloud.hypervisor.vmware.mo.DatacenterMO)

Example 8 with DatacenterMO

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

the class VmwareStorageProcessor method copyTemplateToPrimaryStorage.

@Override
public Answer copyTemplateToPrimaryStorage(CopyCommand cmd) {
    DataTO srcData = cmd.getSrcTO();
    TemplateObjectTO template = (TemplateObjectTO) srcData;
    DataStoreTO srcStore = srcData.getDataStore();
    if (!(srcStore instanceof NfsTO)) {
        return new CopyCmdAnswer("unsupported protocol");
    }
    NfsTO nfsImageStore = (NfsTO) srcStore;
    DataTO destData = cmd.getDestTO();
    DataStoreTO destStore = destData.getDataStore();
    DataStoreTO primaryStore = destStore;
    String secondaryStorageUrl = nfsImageStore.getUrl();
    assert (secondaryStorageUrl != null);
    boolean managed = false;
    String storageHost = null;
    int storagePort = Integer.MIN_VALUE;
    String managedStoragePoolName = null;
    String managedStoragePoolRootVolumeName = null;
    String chapInitiatorUsername = null;
    String chapInitiatorSecret = null;
    String chapTargetUsername = null;
    String chapTargetSecret = null;
    if (destStore instanceof PrimaryDataStoreTO) {
        PrimaryDataStoreTO destPrimaryDataStoreTo = (PrimaryDataStoreTO) destStore;
        Map<String, String> details = destPrimaryDataStoreTo.getDetails();
        if (details != null) {
            managed = Boolean.parseBoolean(details.get(PrimaryDataStoreTO.MANAGED));
            if (managed) {
                storageHost = details.get(PrimaryDataStoreTO.STORAGE_HOST);
                try {
                    storagePort = Integer.parseInt(details.get(PrimaryDataStoreTO.STORAGE_PORT));
                } catch (Exception ex) {
                    storagePort = 3260;
                }
                managedStoragePoolName = details.get(PrimaryDataStoreTO.MANAGED_STORE_TARGET);
                managedStoragePoolRootVolumeName = details.get(PrimaryDataStoreTO.MANAGED_STORE_TARGET_ROOT_VOLUME);
                chapInitiatorUsername = details.get(PrimaryDataStoreTO.CHAP_INITIATOR_USERNAME);
                chapInitiatorSecret = details.get(PrimaryDataStoreTO.CHAP_INITIATOR_SECRET);
                chapTargetUsername = details.get(PrimaryDataStoreTO.CHAP_TARGET_USERNAME);
                chapTargetSecret = details.get(PrimaryDataStoreTO.CHAP_TARGET_SECRET);
            }
        }
    }
    String templateUrl = secondaryStorageUrl + "/" + srcData.getPath();
    Pair<String, String> templateInfo = VmwareStorageLayoutHelper.decodeTemplateRelativePathAndNameFromUrl(secondaryStorageUrl, templateUrl, template.getName());
    VmwareContext context = hostService.getServiceContext(cmd);
    if (context == null) {
        return new CopyCmdAnswer("Failed to create a Vmware context, check the management server logs or the ssvm log for details");
    }
    try {
        VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd);
        String storageUuid = managed ? managedStoragePoolName : primaryStore.getUuid();
        String templateUuidName = deriveTemplateUuidOnHost(hyperHost, storageUuid, templateInfo.second());
        DatacenterMO dcMo = new DatacenterMO(context, hyperHost.getHyperHostDatacenter());
        VirtualMachineMO templateMo = VmwareHelper.pickOneVmOnRunningHost(dcMo.findVmByNameAndLabel(templateUuidName), true);
        DatastoreMO dsMo = null;
        Pair<VirtualMachineMO, Long> vmInfo = null;
        if (templateMo == null) {
            if (s_logger.isInfoEnabled()) {
                s_logger.info("Template " + templateInfo.second() + " is not setup yet. Set up template from secondary storage with uuid name: " + templateUuidName);
            }
            final ManagedObjectReference morDs;
            if (managed) {
                morDs = prepareManagedDatastore(context, hyperHost, null, managedStoragePoolName, storageHost, storagePort, chapInitiatorUsername, chapInitiatorSecret, chapTargetUsername, chapTargetSecret);
            } else {
                morDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, storageUuid);
            }
            assert (morDs != null);
            dsMo = new DatastoreMO(context, morDs);
            if (managed) {
                vmInfo = copyTemplateFromSecondaryToPrimary(hyperHost, dsMo, secondaryStorageUrl, templateInfo.first(), templateInfo.second(), managedStoragePoolRootVolumeName, false, _nfsVersion);
                VirtualMachineMO vmMo = vmInfo.first();
                vmMo.unregisterVm();
                String[] vmwareLayoutFilePair = VmwareStorageLayoutHelper.getVmdkFilePairDatastorePath(dsMo, managedStoragePoolRootVolumeName, managedStoragePoolRootVolumeName, VmwareStorageLayoutType.VMWARE, false);
                String[] legacyCloudStackLayoutFilePair = VmwareStorageLayoutHelper.getVmdkFilePairDatastorePath(dsMo, null, managedStoragePoolRootVolumeName, VmwareStorageLayoutType.CLOUDSTACK_LEGACY, false);
                dsMo.moveDatastoreFile(vmwareLayoutFilePair[0], dcMo.getMor(), dsMo.getMor(), legacyCloudStackLayoutFilePair[0], dcMo.getMor(), true);
                dsMo.moveDatastoreFile(vmwareLayoutFilePair[1], dcMo.getMor(), dsMo.getMor(), legacyCloudStackLayoutFilePair[1], dcMo.getMor(), true);
                String folderToDelete = dsMo.getDatastorePath(managedStoragePoolRootVolumeName, true);
                dsMo.deleteFolder(folderToDelete, dcMo.getMor());
            } else {
                vmInfo = copyTemplateFromSecondaryToPrimary(hyperHost, dsMo, secondaryStorageUrl, templateInfo.first(), templateInfo.second(), templateUuidName, true, _nfsVersion);
            }
        } else {
            s_logger.info("Template " + templateInfo.second() + " has already been setup, skip the template setup process in primary storage");
        }
        TemplateObjectTO newTemplate = new TemplateObjectTO();
        if (managed) {
            if (dsMo != null) {
                String path = dsMo.getDatastorePath(managedStoragePoolRootVolumeName + ".vmdk");
                newTemplate.setPath(path);
            }
        } else {
            newTemplate.setPath(templateUuidName);
        }
        newTemplate.setSize((vmInfo != null) ? vmInfo.second() : new Long(0));
        return new CopyCmdAnswer(newTemplate);
    } catch (Throwable e) {
        if (e instanceof RemoteException) {
            hostService.invalidateServiceContext(context);
        }
        String msg = "Unable to copy template to primary storage due to exception:" + VmwareHelper.getExceptionMessage(e);
        s_logger.error(msg, e);
        return new CopyCmdAnswer(msg);
    }
}
Also used : 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) NfsTO(com.cloud.agent.api.to.NfsTO) RemoteException(java.rmi.RemoteException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) DatastoreMO(com.cloud.hypervisor.vmware.mo.DatastoreMO) VmwareContext(com.cloud.hypervisor.vmware.util.VmwareContext) DataTO(com.cloud.agent.api.to.DataTO) PrimaryDataStoreTO(org.apache.cloudstack.storage.to.PrimaryDataStoreTO) TemplateObjectTO(org.apache.cloudstack.storage.to.TemplateObjectTO) RemoteException(java.rmi.RemoteException) CopyCmdAnswer(org.apache.cloudstack.storage.command.CopyCmdAnswer) DatacenterMO(com.cloud.hypervisor.vmware.mo.DatacenterMO) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference)

Example 9 with DatacenterMO

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

the class VmwareResource method registerVm.

/**
     * Registers the vm to the inventory given the vmx file.
     */
private void registerVm(String vmName, DatastoreMO dsMo) throws Exception {
    //1st param
    VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext());
    ManagedObjectReference dcMor = hyperHost.getHyperHostDatacenter();
    DatacenterMO dataCenterMo = new DatacenterMO(getServiceContext(), dcMor);
    ManagedObjectReference vmFolderMor = dataCenterMo.getVmFolder();
    //2nd param
    String vmxFilePath = dsMo.searchFileInSubFolders(vmName + ".vmx", false);
    // 5th param
    ManagedObjectReference morPool = hyperHost.getHyperHostOwnerResourcePool();
    ManagedObjectReference morTask = getServiceContext().getService().registerVMTask(vmFolderMor, vmxFilePath, vmName, false, morPool, hyperHost.getMor());
    boolean result = getServiceContext().getVimClient().waitForTask(morTask);
    if (!result) {
        throw new Exception("Unable to register vm due to " + TaskMO.getTaskFailureInfo(getServiceContext(), morTask));
    } else {
        getServiceContext().waitForTaskProgressDone(morTask);
    }
}
Also used : 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) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference) DatacenterMO(com.cloud.hypervisor.vmware.mo.DatacenterMO)

Example 10 with DatacenterMO

use of com.cloud.hypervisor.vmware.mo.DatacenterMO 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)

Aggregations

DatacenterMO (com.cloud.hypervisor.vmware.mo.DatacenterMO)20 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)16 RemoteException (java.rmi.RemoteException)16 ManagedObjectReference (com.vmware.vim25.ManagedObjectReference)14 VirtualMachineMO (com.cloud.hypervisor.vmware.mo.VirtualMachineMO)13 VmwareHypervisorHost (com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost)13 UnsupportedEncodingException (java.io.UnsupportedEncodingException)13 VmwareContext (com.cloud.hypervisor.vmware.util.VmwareContext)11 IOException (java.io.IOException)9 ConfigurationException (javax.naming.ConfigurationException)9 CloudException (com.cloud.exception.CloudException)8 InternalErrorException (com.cloud.exception.InternalErrorException)8 ConnectException (java.net.ConnectException)8 DatastoreMO (com.cloud.hypervisor.vmware.mo.DatastoreMO)7 DataStoreTO (com.cloud.agent.api.to.DataStoreTO)6 PrimaryDataStoreTO (org.apache.cloudstack.storage.to.PrimaryDataStoreTO)6 HostMO (com.cloud.hypervisor.vmware.mo.HostMO)5 ClusterMO (com.cloud.hypervisor.vmware.mo.ClusterMO)4 CopyCmdAnswer (org.apache.cloudstack.storage.command.CopyCmdAnswer)4 TemplateObjectTO (org.apache.cloudstack.storage.to.TemplateObjectTO)4