Search in sources :

Example 6 with CloudException

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

the class UsageStorageDaoImpl method update.

@Override
public void update(UsageStorageVO usage) {
    TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB);
    try {
        txn.start();
        if (usage.getDeleted() != null) {
            try (PreparedStatement pstmt = txn.prepareStatement(UPDATE_DELETED)) {
                if (pstmt != null) {
                    pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), usage.getDeleted()));
                    pstmt.setLong(2, usage.getAccountId());
                    pstmt.setLong(3, usage.getId());
                    pstmt.setInt(4, usage.getStorageType());
                    pstmt.setLong(5, usage.getZoneId());
                    pstmt.executeUpdate();
                }
            } catch (SQLException e) {
                throw new CloudException("UsageStorageVO update Error:" + e.getMessage(), e);
            }
        }
        txn.commit();
    } catch (Exception e) {
        txn.rollback();
        s_logger.error("Error updating UsageStorageVO:" + e.getMessage(), e);
    } finally {
        txn.close();
    }
}
Also used : TransactionLegacy(com.cloud.utils.db.TransactionLegacy) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) CloudException(com.cloud.exception.CloudException) SQLException(java.sql.SQLException) CloudException(com.cloud.exception.CloudException)

Example 7 with CloudException

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

the class UserVmManagerImpl method stopVirtualMachine.

@Override
public boolean stopVirtualMachine(long userId, long vmId) {
    boolean status = false;
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Stopping vm=" + vmId);
    }
    UserVmVO vm = _vmDao.findById(vmId);
    if (vm == null || vm.getRemoved() != null) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("VM is either removed or deleted.");
        }
        return true;
    }
    _userDao.findById(userId);
    try {
        VirtualMachineEntity vmEntity = _orchSrvc.getVirtualMachine(vm.getUuid());
        status = vmEntity.stop(Long.toString(userId));
    } catch (ResourceUnavailableException e) {
        s_logger.debug("Unable to stop due to ", e);
        status = false;
    } catch (CloudException e) {
        throw new CloudRuntimeException("Unable to contact the agent to stop the virtual machine " + vm, e);
    }
    return status;
}
Also used : CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VirtualMachineEntity(org.apache.cloudstack.engine.cloud.entity.api.VirtualMachineEntity) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) CloudException(com.cloud.exception.CloudException)

Example 8 with CloudException

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

the class UserVmManagerImpl method stopVirtualMachine.

@Override
@ActionEvent(eventType = EventTypes.EVENT_VM_STOP, eventDescription = "stopping Vm", async = true)
public UserVm stopVirtualMachine(long vmId, boolean forced) throws ConcurrentOperationException {
    // Input validation
    Account caller = CallContext.current().getCallingAccount();
    Long userId = CallContext.current().getCallingUserId();
    // if account is removed, return error
    if (caller != null && caller.getRemoved() != null) {
        throw new PermissionDeniedException("The account " + caller.getUuid() + " is removed");
    }
    UserVmVO vm = _vmDao.findById(vmId);
    if (vm == null) {
        throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId);
    }
    _userDao.findById(userId);
    boolean status = false;
    try {
        VirtualMachineEntity vmEntity = _orchSrvc.getVirtualMachine(vm.getUuid());
        if (forced) {
            status = vmEntity.stopForced(Long.toString(userId));
        } else {
            status = vmEntity.stop(Long.toString(userId));
        }
        if (status) {
            return _vmDao.findById(vmId);
        } else {
            return null;
        }
    } catch (ResourceUnavailableException e) {
        throw new CloudRuntimeException("Unable to contact the agent to stop the virtual machine " + vm, e);
    } catch (CloudException e) {
        throw new CloudRuntimeException("Unable to contact the agent to stop the virtual machine " + vm, e);
    }
}
Also used : Account(com.cloud.user.Account) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VirtualMachineEntity(org.apache.cloudstack.engine.cloud.entity.api.VirtualMachineEntity) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) CloudException(com.cloud.exception.CloudException) ActionEvent(com.cloud.event.ActionEvent)

Example 9 with CloudException

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

the class NetworkProviderTest method createTestNetwork.

private Network createTestNetwork(String name) {
    CreateNetworkCmd cmd = new CreateNetworkCmd();
    ComponentContext.inject(cmd);
    Account system = _accountMgr.getSystemAccount();
    DataCenter zone = _server.getZone();
    ManagementServerMock.setParameter(cmd, "accountName", BaseCmd.CommandType.STRING, system.getAccountName());
    ManagementServerMock.setParameter(cmd, ApiConstants.NAME, BaseCmd.CommandType.STRING, name);
    ManagementServerMock.setParameter(cmd, "displayText", BaseCmd.CommandType.STRING, "test network");
    ManagementServerMock.setParameter(cmd, "networkOfferingId", BaseCmd.CommandType.LONG, _contrailMgr.getRouterOffering().getId());
    ManagementServerMock.setParameter(cmd, "zoneId", BaseCmd.CommandType.LONG, zone.getId());
    ManagementServerMock.setParameter(cmd, ApiConstants.GATEWAY, BaseCmd.CommandType.STRING, "10.0.1.254");
    ManagementServerMock.setParameter(cmd, ApiConstants.NETMASK, BaseCmd.CommandType.STRING, "255.255.255.0");
    // Physical network id can't be specified for Guest traffic type.
    // SetParameter(cmd, "physicalNetworkId", BaseCmd.CommandType.LONG, _znet.getId());
    Network result = null;
    try {
        result = _networkService.createGuestNetwork(cmd);
    } catch (CloudException e) {
        e.printStackTrace();
        return null;
    }
    return result;
}
Also used : Account(com.cloud.user.Account) DataCenter(com.cloud.dc.DataCenter) VirtualNetwork(net.juniper.contrail.api.types.VirtualNetwork) Network(com.cloud.network.Network) CreateNetworkCmd(org.apache.cloudstack.api.command.user.network.CreateNetworkCmd) CloudException(com.cloud.exception.CloudException)

Example 10 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)

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