Search in sources :

Example 16 with ServerApiException

use of org.apache.cloudstack.api.ServerApiException in project cloudstack by apache.

the class UpgradeVMCmdByAdmin method execute.

@Override
public void execute() throws ResourceAllocationException {
    CallContext.current().setEventDetails("Vm Id: " + getId());
    ServiceOffering serviceOffering = _entityMgr.findById(ServiceOffering.class, serviceOfferingId);
    if (serviceOffering == null) {
        throw new InvalidParameterValueException("Unable to find service offering: " + serviceOfferingId);
    }
    UserVm result = _userVmService.upgradeVirtualMachine(this);
    if (result != null) {
        UserVmResponse response = _responseGenerator.createUserVmResponse(ResponseView.Full, "virtualmachine", result).get(0);
        response.setResponseName(getCommandName());
        setResponseObject(response);
    } else {
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to upgrade vm");
    }
}
Also used : UserVm(com.cloud.uservm.UserVm) ServerApiException(org.apache.cloudstack.api.ServerApiException) ServiceOffering(com.cloud.offering.ServiceOffering) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) UserVmResponse(org.apache.cloudstack.api.response.UserVmResponse)

Example 17 with ServerApiException

use of org.apache.cloudstack.api.ServerApiException in project cloudstack by apache.

the class RevertToVMSnapshotCmdByAdmin method execute.

@Override
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException, ConcurrentOperationException {
    CallContext.current().setEventDetails("vmsnapshot id: " + getVmSnapShotId());
    UserVm result = _vmSnapshotService.revertToSnapshot(getVmSnapShotId());
    if (result != null) {
        UserVmResponse response = _responseGenerator.createUserVmResponse(ResponseView.Full, "virtualmachine", result).get(0);
        response.setResponseName(getCommandName());
        setResponseObject(response);
    } else {
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to revert VM snapshot");
    }
}
Also used : UserVm(com.cloud.uservm.UserVm) ServerApiException(org.apache.cloudstack.api.ServerApiException) UserVmResponse(org.apache.cloudstack.api.response.UserVmResponse)

Example 18 with ServerApiException

use of org.apache.cloudstack.api.ServerApiException in project cloudstack by apache.

the class ApiServer method verifyRequest.

@Override
public boolean verifyRequest(final Map<String, Object[]> requestParameters, final Long userId) throws ServerApiException {
    try {
        String apiKey = null;
        String secretKey = null;
        String signature = null;
        String unsignedRequest = null;
        final String[] command = (String[]) requestParameters.get(ApiConstants.COMMAND);
        if (command == null) {
            s_logger.info("missing command, ignoring request...");
            return false;
        }
        final String commandName = command[0];
        // if userId not null, that mean that user is logged in
        if (userId != null) {
            final User user = ApiDBUtils.findUserById(userId);
            try {
                checkCommandAvailable(user, commandName);
            } catch (final RequestLimitException ex) {
                s_logger.debug(ex.getMessage());
                throw new ServerApiException(ApiErrorCode.API_LIMIT_EXCEED, ex.getMessage());
            } catch (final PermissionDeniedException ex) {
                s_logger.debug("The user with id:" + userId + " is not allowed to request the API command or the API command does not exist: " + commandName);
                throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, "The user is not allowed to request the API command or the API command does not exist");
            }
            return true;
        } else {
            // check against every available command to see if the command exists or not
            if (!s_apiNameCmdClassMap.containsKey(commandName) && !commandName.equals("login") && !commandName.equals("logout")) {
                s_logger.debug("The user with id:" + userId + " is not allowed to request the API command or the API command does not exist: " + commandName);
                throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, "The user is not allowed to request the API command or the API command does not exist");
            }
        }
        // - build a request string with sorted params, make sure it's all lowercase
        // - sign the request, verify the signature is the same
        final List<String> parameterNames = new ArrayList<String>();
        for (final Object paramNameObj : requestParameters.keySet()) {
            // put the name in a list that we'll sort later
            parameterNames.add((String) paramNameObj);
        }
        Collections.sort(parameterNames);
        String signatureVersion = null;
        String expires = null;
        for (final String paramName : parameterNames) {
            // parameters come as name/value pairs in the form String/String[]
            final String paramValue = ((String[]) requestParameters.get(paramName))[0];
            if (ApiConstants.SIGNATURE.equalsIgnoreCase(paramName)) {
                signature = paramValue;
            } else {
                if (ApiConstants.API_KEY.equalsIgnoreCase(paramName)) {
                    apiKey = paramValue;
                } else if (ApiConstants.SIGNATURE_VERSION.equalsIgnoreCase(paramName)) {
                    signatureVersion = paramValue;
                } else if (ApiConstants.EXPIRES.equalsIgnoreCase(paramName)) {
                    expires = paramValue;
                }
                if (unsignedRequest == null) {
                    unsignedRequest = paramName + "=" + URLEncoder.encode(paramValue, HttpUtils.UTF_8).replaceAll("\\+", "%20");
                } else {
                    unsignedRequest = unsignedRequest + "&" + paramName + "=" + URLEncoder.encode(paramValue, HttpUtils.UTF_8).replaceAll("\\+", "%20");
                }
            }
        }
        // if api/secret key are passed to the parameters
        if ((signature == null) || (apiKey == null)) {
            s_logger.debug("Expired session, missing signature, or missing apiKey -- ignoring request. Signature: " + signature + ", apiKey: " + apiKey);
            // no signature, bad request
            return false;
        }
        Date expiresTS = null;
        // FIXME: Hard coded signature, why not have an enum
        if ("3".equals(signatureVersion)) {
            // New signature authentication. Check for expire parameter and its validity
            if (expires == null) {
                s_logger.debug("Missing Expires parameter -- ignoring request. Signature: " + signature + ", apiKey: " + apiKey);
                return false;
            }
            synchronized (DateFormatToUse) {
                try {
                    expiresTS = DateFormatToUse.parse(expires);
                } catch (final ParseException pe) {
                    s_logger.debug("Incorrect date format for Expires parameter", pe);
                    return false;
                }
            }
            final Date now = new Date(System.currentTimeMillis());
            if (expiresTS.before(now)) {
                s_logger.debug("Request expired -- ignoring ...sig: " + signature + ", apiKey: " + apiKey);
                return false;
            }
        }
        final TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB);
        txn.close();
        User user = null;
        // verify there is a user with this api key
        final Pair<User, Account> userAcctPair = accountMgr.findUserByApiKey(apiKey);
        if (userAcctPair == null) {
            s_logger.debug("apiKey does not map to a valid user -- ignoring request, apiKey: " + apiKey);
            return false;
        }
        user = userAcctPair.first();
        final Account account = userAcctPair.second();
        if (user.getState() != Account.State.enabled || !account.getState().equals(Account.State.enabled)) {
            s_logger.info("disabled or locked user accessing the api, userid = " + user.getId() + "; name = " + user.getUsername() + "; state: " + user.getState() + "; accountState: " + account.getState());
            return false;
        }
        try {
            checkCommandAvailable(user, commandName);
        } catch (final RequestLimitException ex) {
            s_logger.debug(ex.getMessage());
            throw new ServerApiException(ApiErrorCode.API_LIMIT_EXCEED, ex.getMessage());
        } catch (final PermissionDeniedException ex) {
            s_logger.debug("The given command:" + commandName + " does not exist or it is not available for user");
            throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, "The given command:" + commandName + " does not exist or it is not available for user with id:" + userId);
        }
        // verify secret key exists
        secretKey = user.getSecretKey();
        if (secretKey == null) {
            s_logger.info("User does not have a secret key associated with the account -- ignoring request, username: " + user.getUsername());
            return false;
        }
        unsignedRequest = unsignedRequest.toLowerCase();
        final Mac mac = Mac.getInstance("HmacSHA1");
        final SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
        mac.init(keySpec);
        mac.update(unsignedRequest.getBytes());
        final byte[] encryptedBytes = mac.doFinal();
        final String computedSignature = Base64.encodeBase64String(encryptedBytes);
        final boolean equalSig = ConstantTimeComparator.compareStrings(signature, computedSignature);
        if (!equalSig) {
            s_logger.info("User signature: " + signature + " is not equaled to computed signature: " + computedSignature);
        } else {
            CallContext.register(user, account);
        }
        return equalSig;
    } catch (final ServerApiException ex) {
        throw ex;
    } catch (final Exception ex) {
        s_logger.error("unable to verify request signature");
    }
    return false;
}
Also used : UserAccount(com.cloud.user.UserAccount) Account(com.cloud.user.Account) User(com.cloud.user.User) RequestLimitException(com.cloud.exception.RequestLimitException) ArrayList(java.util.ArrayList) Date(java.util.Date) ResponseDate(org.apache.http.protocol.ResponseDate) Mac(javax.crypto.Mac) AccountLimitException(com.cloud.exception.AccountLimitException) HttpException(org.apache.http.HttpException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) ServerApiException(org.apache.cloudstack.api.ServerApiException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) InterruptedIOException(java.io.InterruptedIOException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) CloudAuthenticationException(com.cloud.exception.CloudAuthenticationException) IOException(java.io.IOException) RequestLimitException(com.cloud.exception.RequestLimitException) URISyntaxException(java.net.URISyntaxException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ParseException(java.text.ParseException) EventBusException(org.apache.cloudstack.framework.events.EventBusException) ConfigurationException(javax.naming.ConfigurationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) ConnectionClosedException(org.apache.http.ConnectionClosedException) TransactionLegacy(com.cloud.utils.db.TransactionLegacy) ServerApiException(org.apache.cloudstack.api.ServerApiException) SecretKeySpec(javax.crypto.spec.SecretKeySpec) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ExceptionProxyObject(com.cloud.utils.exception.ExceptionProxyObject) ResponseObject(org.apache.cloudstack.api.ResponseObject) ParseException(java.text.ParseException)

Example 19 with ServerApiException

use of org.apache.cloudstack.api.ServerApiException in project cloudstack by apache.

the class AttachIsoCmdByAdmin method execute.

@Override
public void execute() {
    CallContext.current().setEventDetails("Vm Id: " + getVirtualMachineId() + " ISO Id: " + getId());
    boolean result = _templateService.attachIso(id, virtualMachineId);
    if (result) {
        UserVm userVm = _responseGenerator.findUserVmById(virtualMachineId);
        if (userVm != null) {
            UserVmResponse response = _responseGenerator.createUserVmResponse(ResponseView.Full, "virtualmachine", userVm).get(0);
            response.setResponseName(DeployVMCmd.getResultObjectName());
            setResponseObject(response);
        } else {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to attach iso");
        }
    } else {
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to attach iso");
    }
}
Also used : UserVm(com.cloud.uservm.UserVm) ServerApiException(org.apache.cloudstack.api.ServerApiException) UserVmResponse(org.apache.cloudstack.api.response.UserVmResponse)

Example 20 with ServerApiException

use of org.apache.cloudstack.api.ServerApiException in project cloudstack by apache.

the class ListVolumesOnFilerCmd method execute.

@Override
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException {
    try {
        List<NetappVolumeVO> volumes = netappMgr.listVolumesOnFiler(poolName);
        ListResponse<ListVolumesOnFilerCmdResponse> listResponse = new ListResponse<ListVolumesOnFilerCmdResponse>();
        List<ListVolumesOnFilerCmdResponse> responses = new ArrayList<ListVolumesOnFilerCmdResponse>();
        for (NetappVolumeVO volume : volumes) {
            ListVolumesOnFilerCmdResponse response = new ListVolumesOnFilerCmdResponse();
            response.setId(volume.getId());
            response.setIpAddress(volume.getIpAddress());
            response.setPoolName(volume.getPoolName());
            response.setAggrName(volume.getAggregateName());
            response.setVolumeName(volume.getVolumeName());
            response.setSnapshotPolicy(volume.getSnapshotPolicy());
            response.setSnapshotReservation(volume.getSnapshotReservation());
            response.setVolumeSize(volume.getVolumeSize());
            response.setObjectName("volume");
            responses.add(response);
        }
        listResponse.setResponses(responses);
        listResponse.setResponseName(getCommandName());
        this.setResponseObject(listResponse);
    } catch (InvalidParameterValueException e) {
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.toString());
    }
}
Also used : NetappVolumeVO(com.cloud.netapp.NetappVolumeVO) ListVolumesOnFilerCmdResponse(com.cloud.server.api.response.netapp.ListVolumesOnFilerCmdResponse) ListResponse(org.apache.cloudstack.api.response.ListResponse) ServerApiException(org.apache.cloudstack.api.ServerApiException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ArrayList(java.util.ArrayList)

Aggregations

ServerApiException (org.apache.cloudstack.api.ServerApiException)628 SuccessResponse (org.apache.cloudstack.api.response.SuccessResponse)154 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)143 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)104 ArrayList (java.util.ArrayList)74 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)55 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)51 ListResponse (org.apache.cloudstack.api.response.ListResponse)49 ResourceAllocationException (com.cloud.exception.ResourceAllocationException)47 UserVm (com.cloud.uservm.UserVm)47 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)43 UserVmResponse (org.apache.cloudstack.api.response.UserVmResponse)42 Account (com.cloud.user.Account)32 Host (com.cloud.host.Host)30 NetworkRuleConflictException (com.cloud.exception.NetworkRuleConflictException)29 Volume (com.cloud.storage.Volume)25 Test (org.junit.Test)23 VolumeResponse (org.apache.cloudstack.api.response.VolumeResponse)20 VirtualMachineTemplate (com.cloud.template.VirtualMachineTemplate)15 UserAccount (com.cloud.user.UserAccount)15