Search in sources :

Example 16 with CloudException

use of com.cloud.exception.CloudException in project cloudstack by apache.

the class HypervisorHostHelper method importVmFromOVF.

public static void importVmFromOVF(VmwareHypervisorHost host, String ovfFilePath, String vmName, DatastoreMO dsMo, String diskOption, ManagedObjectReference morRp, ManagedObjectReference morHost) throws Exception {
    assert (morRp != null);
    OvfCreateImportSpecParams importSpecParams = new OvfCreateImportSpecParams();
    importSpecParams.setHostSystem(morHost);
    importSpecParams.setLocale("US");
    importSpecParams.setEntityName(vmName);
    importSpecParams.setDeploymentOption("");
    // diskOption: thin, thick, etc
    importSpecParams.setDiskProvisioning(diskOption);
    String ovfDescriptor = removeOVFNetwork(HttpNfcLeaseMO.readOvfContent(ovfFilePath));
    VmwareContext context = host.getContext();
    OvfCreateImportSpecResult ovfImportResult = context.getService().createImportSpec(context.getServiceContent().getOvfManager(), ovfDescriptor, morRp, dsMo.getMor(), importSpecParams);
    if (ovfImportResult == null) {
        String msg = "createImportSpec() failed. ovfFilePath: " + ovfFilePath + ", vmName: " + vmName + ", diskOption: " + diskOption;
        s_logger.error(msg);
        throw new Exception(msg);
    }
    if (!ovfImportResult.getError().isEmpty()) {
        for (LocalizedMethodFault fault : ovfImportResult.getError()) {
            s_logger.error("createImportSpec error: " + fault.getLocalizedMessage());
        }
        throw new CloudException("Failed to create an import spec from " + ovfFilePath + ". Check log for details.");
    }
    if (!ovfImportResult.getWarning().isEmpty()) {
        for (LocalizedMethodFault fault : ovfImportResult.getError()) {
            s_logger.warn("createImportSpec warning: " + fault.getLocalizedMessage());
        }
    }
    DatacenterMO dcMo = new DatacenterMO(context, host.getHyperHostDatacenter());
    ManagedObjectReference morLease = context.getService().importVApp(morRp, ovfImportResult.getImportSpec(), dcMo.getVmFolder(), morHost);
    if (morLease == null) {
        String msg = "importVApp() failed. ovfFilePath: " + ovfFilePath + ", vmName: " + vmName + ", diskOption: " + diskOption;
        s_logger.error(msg);
        throw new Exception(msg);
    }
    boolean importSuccess = true;
    final HttpNfcLeaseMO leaseMo = new HttpNfcLeaseMO(context, morLease);
    HttpNfcLeaseState state = leaseMo.waitState(new HttpNfcLeaseState[] { HttpNfcLeaseState.READY, HttpNfcLeaseState.ERROR });
    try {
        if (state == HttpNfcLeaseState.READY) {
            final long totalBytes = HttpNfcLeaseMO.calcTotalBytes(ovfImportResult);
            File ovfFile = new File(ovfFilePath);
            HttpNfcLeaseInfo httpNfcLeaseInfo = leaseMo.getLeaseInfo();
            List<HttpNfcLeaseDeviceUrl> deviceUrls = httpNfcLeaseInfo.getDeviceUrl();
            long bytesAlreadyWritten = 0;
            final HttpNfcLeaseMO.ProgressReporter progressReporter = leaseMo.createProgressReporter();
            try {
                for (HttpNfcLeaseDeviceUrl deviceUrl : deviceUrls) {
                    String deviceKey = deviceUrl.getImportKey();
                    for (OvfFileItem ovfFileItem : ovfImportResult.getFileItem()) {
                        if (deviceKey.equals(ovfFileItem.getDeviceId())) {
                            String absoluteFile = ovfFile.getParent() + File.separator + ovfFileItem.getPath();
                            String urlToPost = deviceUrl.getUrl();
                            urlToPost = resolveHostNameInUrl(dcMo, urlToPost);
                            context.uploadVmdkFile(ovfFileItem.isCreate() ? "PUT" : "POST", urlToPost, absoluteFile, bytesAlreadyWritten, new ActionDelegate<Long>() {

                                @Override
                                public void action(Long param) {
                                    progressReporter.reportProgress((int) (param * 100 / totalBytes));
                                }
                            });
                            bytesAlreadyWritten += ovfFileItem.getSize();
                        }
                    }
                }
            } catch (Exception e) {
                String erroMsg = "File upload task failed to complete due to: " + e.getMessage();
                s_logger.error(erroMsg);
                // Set flag to cleanup the stale template left due to failed import operation, if any
                importSuccess = false;
                throw new Exception(erroMsg);
            } catch (Throwable th) {
                String errorMsg = "throwable caught during file upload task: " + th.getMessage();
                s_logger.error(errorMsg);
                // Set flag to cleanup the stale template left due to failed import operation, if any
                importSuccess = false;
                throw new Exception(errorMsg, th);
            } finally {
                progressReporter.close();
            }
            if (bytesAlreadyWritten == totalBytes) {
                leaseMo.updateLeaseProgress(100);
            }
        } else if (state == HttpNfcLeaseState.ERROR) {
            LocalizedMethodFault error = leaseMo.getLeaseError();
            MethodFault fault = error.getFault();
            String erroMsg = "Object creation on vCenter failed due to: Exception: " + fault.getClass().getName() + ", message: " + error.getLocalizedMessage();
            s_logger.error(erroMsg);
            throw new Exception(erroMsg);
        }
    } finally {
        if (!importSuccess) {
            s_logger.error("Aborting the lease on " + vmName + " after import operation failed.");
            leaseMo.abortLease();
        } else {
            leaseMo.completeLease();
        }
    }
}
Also used : OvfFileItem(com.vmware.vim25.OvfFileItem) LocalizedMethodFault(com.vmware.vim25.LocalizedMethodFault) MethodFault(com.vmware.vim25.MethodFault) LocalizedMethodFault(com.vmware.vim25.LocalizedMethodFault) OvfCreateImportSpecResult(com.vmware.vim25.OvfCreateImportSpecResult) CloudException(com.cloud.exception.CloudException) URISyntaxException(java.net.URISyntaxException) InvalidParameterException(java.security.InvalidParameterException) CloudException(com.cloud.exception.CloudException) SAXException(org.xml.sax.SAXException) TransformerException(javax.xml.transform.TransformerException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) OvfCreateImportSpecParams(com.vmware.vim25.OvfCreateImportSpecParams) VmwareContext(com.cloud.hypervisor.vmware.util.VmwareContext) HttpNfcLeaseInfo(com.vmware.vim25.HttpNfcLeaseInfo) File(java.io.File) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference) HttpNfcLeaseState(com.vmware.vim25.HttpNfcLeaseState) HttpNfcLeaseDeviceUrl(com.vmware.vim25.HttpNfcLeaseDeviceUrl)

Example 17 with CloudException

use of com.cloud.exception.CloudException in project cloudstack by apache.

the class VmwareResource method getTargetSwitch.

// return Ternary <switch name, switch tyep, vlan tagging>
private Ternary<String, String, String> getTargetSwitch(NicTO nicTo) throws CloudException {
    TrafficType[] supportedTrafficTypes = new TrafficType[] { TrafficType.Guest, TrafficType.Public, TrafficType.Control, TrafficType.Management, TrafficType.Storage };
    TrafficType trafficType = nicTo.getType();
    if (!Arrays.asList(supportedTrafficTypes).contains(trafficType)) {
        throw new CloudException("Traffic type " + trafficType.toString() + " for nic " + nicTo.toString() + " is not supported.");
    }
    String switchName = null;
    VirtualSwitchType switchType = VirtualSwitchType.StandardVirtualSwitch;
    String vlanId = Vlan.UNTAGGED;
    if (nicTo.getName() != null && !nicTo.getName().isEmpty()) {
        // Format of network traffic label is <VSWITCH>,<VLANID>,<VSWITCHTYPE>
        // If all 3 fields are mentioned then number of tokens would be 3.
        // If only <VSWITCH>,<VLANID> are mentioned then number of tokens would be 2.
        // Get switch details from the nicTO object
        String networkName = nicTo.getName();
        VmwareTrafficLabel mgmtTrafficLabelObj = new VmwareTrafficLabel(networkName, trafficType);
        switchName = mgmtTrafficLabelObj.getVirtualSwitchName();
        vlanId = mgmtTrafficLabelObj.getVlanId();
        switchType = mgmtTrafficLabelObj.getVirtualSwitchType();
    } else {
        if (trafficType == TrafficType.Guest && _guestTrafficInfo != null) {
            switchType = _guestTrafficInfo.getVirtualSwitchType();
            switchName = _guestTrafficInfo.getVirtualSwitchName();
        } else if (trafficType == TrafficType.Public && _publicTrafficInfo != null) {
            switchType = _publicTrafficInfo.getVirtualSwitchType();
            switchName = _publicTrafficInfo.getVirtualSwitchName();
        }
    }
    if (switchName == null && (nicTo.getType() == Networks.TrafficType.Control || nicTo.getType() == Networks.TrafficType.Management || nicTo.getType() == Networks.TrafficType.Storage)) {
        switchName = _privateNetworkVSwitchName;
    }
    if (switchType == VirtualSwitchType.NexusDistributedVirtualSwitch) {
        if (trafficType == TrafficType.Management || trafficType == TrafficType.Storage) {
            throw new CloudException("Unable to configure NIC " + nicTo.toString() + " as traffic type " + trafficType.toString() + " is not supported over virtual switch type " + switchType + ". Please specify only supported type of virtual switches i.e. {vmwaresvs, vmwaredvs} in physical network traffic label.");
        }
    }
    return new Ternary<String, String, String>(switchName, switchType.toString(), vlanId);
}
Also used : VmwareTrafficLabel(com.cloud.network.VmwareTrafficLabel) Ternary(com.cloud.utils.Ternary) CloudException(com.cloud.exception.CloudException) VirtualSwitchType(com.cloud.hypervisor.vmware.mo.VirtualSwitchType) TrafficType(com.cloud.network.Networks.TrafficType)

Example 18 with CloudException

use of com.cloud.exception.CloudException in project cloudstack by apache.

the class UserVmManagerImpl method destroyVm.

@Override
public UserVm destroyVm(long vmId, boolean expunge) throws ResourceUnavailableException, ConcurrentOperationException {
    // Account caller = CallContext.current().getCallingAccount();
    // Long userId = CallContext.current().getCallingUserId();
    Long userId = 2L;
    // Verify input parameters
    UserVmVO vm = _vmDao.findById(vmId);
    if (vm == null || vm.getRemoved() != null) {
        InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a virtual machine with specified vmId");
        throw ex;
    }
    if (vm.getState() == State.Destroyed || vm.getState() == State.Expunging) {
        s_logger.trace("Vm id=" + vmId + " is already destroyed");
        return vm;
    }
    boolean status;
    State vmState = vm.getState();
    try {
        VirtualMachineEntity vmEntity = _orchSrvc.getVirtualMachine(vm.getUuid());
        status = vmEntity.destroy(Long.toString(userId), expunge);
    } catch (CloudException e) {
        CloudRuntimeException ex = new CloudRuntimeException("Unable to destroy with specified vmId", e);
        ex.addProxyObject(vm.getUuid(), "vmId");
        throw ex;
    }
    if (status) {
        // Mark the account's volumes as destroyed
        List<VolumeVO> volumes = _volsDao.findByInstance(vmId);
        for (VolumeVO volume : volumes) {
            if (volume.getVolumeType().equals(Volume.Type.ROOT)) {
                UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_DELETE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), Volume.class.getName(), volume.getUuid(), volume.isDisplayVolume());
            }
        }
        if (vmState != State.Error) {
            // Get serviceOffering for Virtual Machine
            ServiceOfferingVO offering = _serviceOfferingDao.findByIdIncludingRemoved(vm.getId(), vm.getServiceOfferingId());
            //Update Resource Count for the given account
            resourceCountDecrement(vm.getAccountId(), vm.isDisplayVm(), new Long(offering.getCpu()), new Long(offering.getRamSize()));
        }
        return _vmDao.findById(vmId);
    } else {
        CloudRuntimeException ex = new CloudRuntimeException("Failed to destroy vm with specified vmId");
        ex.addProxyObject(vm.getUuid(), "vmId");
        throw ex;
    }
}
Also used : VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) Volume(com.cloud.storage.Volume) ResourceState(com.cloud.resource.ResourceState) State(com.cloud.vm.VirtualMachine.State) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VirtualMachineEntity(org.apache.cloudstack.engine.cloud.entity.api.VirtualMachineEntity) CloudException(com.cloud.exception.CloudException) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO)

Aggregations

CloudException (com.cloud.exception.CloudException)18 TransactionLegacy (com.cloud.utils.db.TransactionLegacy)11 PreparedStatement (java.sql.PreparedStatement)11 SQLException (java.sql.SQLException)11 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)4 VirtualMachineEntity (org.apache.cloudstack.engine.cloud.entity.api.VirtualMachineEntity)3 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)2 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)2 Account (com.cloud.user.Account)2 ResultSet (java.sql.ResultSet)2 DataCenter (com.cloud.dc.DataCenter)1 ActionEvent (com.cloud.event.ActionEvent)1 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)1 VirtualSwitchType (com.cloud.hypervisor.vmware.mo.VirtualSwitchType)1 VmwareContext (com.cloud.hypervisor.vmware.util.VmwareContext)1 Network (com.cloud.network.Network)1 TrafficType (com.cloud.network.Networks.TrafficType)1 VmwareTrafficLabel (com.cloud.network.VmwareTrafficLabel)1 ResourceState (com.cloud.resource.ResourceState)1 ServiceOfferingVO (com.cloud.service.ServiceOfferingVO)1