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");
}
}
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");
}
}
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;
}
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");
}
}
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());
}
}
Aggregations