You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by ah...@apache.org on 2013/01/19 01:00:12 UTC
[36/51] [abbrv] All merge conflicts resolved
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/10d9c019/server/src/com/cloud/api/ApiDispatcher.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/api/ApiDispatcher.java
index 1ab6ee2,129ef7d..91ffd87
--- a/server/src/com/cloud/api/ApiDispatcher.java
+++ b/server/src/com/cloud/api/ApiDispatcher.java
@@@ -83,58 -83,35 +83,25 @@@ public class ApiDispatcher
return s_instance;
}
- protected ApiDispatcher() {
- super();
- _locator = ComponentLocator.getLocator(ManagementServer.Name);
- ConfigurationDao configDao = _locator.getDao(ConfigurationDao.class);
- Map<String, String> configs = configDao.getConfiguration();
- String strSnapshotLimit = configs.get(Config.ConcurrentSnapshotsThresholdPerHost.key());
- if (strSnapshotLimit != null) {
- Long snapshotLimit = NumbersUtil.parseLong(strSnapshotLimit, 1L);
- if (snapshotLimit <= 0) {
- s_logger.debug("Global config parameter " + Config.ConcurrentSnapshotsThresholdPerHost.toString()
- + " is less or equal 0; defaulting to unlimited");
- } else {
- _createSnapshotQueueSizeLimit = snapshotLimit;
- }
- }
- _daoNameMap.put("com.cloud.network.Network", NetworkDao.class);
- _daoNameMap.put("com.cloud.template.VirtualMachineTemplate", VMTemplateDao.class);
+ public ApiDispatcher() {
+ }
+
+ @PostConstruct
+ void init() {
+ s_instance = this;
+ }
+
+ public void setCreateSnapshotQueueSizeLimit(Long snapshotLimit) {
+ _createSnapshotQueueSizeLimit = snapshotLimit;
}
- public void dispatchCreateCmd(BaseAsyncCreateCmd cmd, Map<String, String> params) {
+ public void dispatchCreateCmd(BaseAsyncCreateCmd cmd, Map<String, String> params) throws Exception {
processParameters(cmd, params);
- try {
- UserContext ctx = UserContext.current();
- ctx.setAccountId(cmd.getEntityOwnerId());
- cmd.create();
+ UserContext ctx = UserContext.current();
+ ctx.setAccountId(cmd.getEntityOwnerId());
+ cmd.create();
- } catch (Throwable t) {
- if (t instanceof InvalidParameterValueException || t instanceof IllegalArgumentException) {
- s_logger.info(t.getMessage());
- throw new ServerApiException(BaseCmd.PARAM_ERROR, t.getMessage());
- } else if (t instanceof PermissionDeniedException) {
- s_logger.info("PermissionDenied: " + t.getMessage());
- throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, t.getMessage());
- } else if (t instanceof AccountLimitException) {
- s_logger.info(t.getMessage());
- throw new ServerApiException(BaseCmd.ACCOUNT_RESOURCE_LIMIT_ERROR, t.getMessage());
- } else if (t instanceof InsufficientCapacityException) {
- s_logger.info(t.getMessage());
- throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, t.getMessage());
- } else if (t instanceof ResourceAllocationException) {
- s_logger.info(t.getMessage());
- throw new ServerApiException(BaseCmd.RESOURCE_ALLOCATION_ERROR, t.getMessage());
- } else if (t instanceof ResourceUnavailableException) {
- s_logger.warn("Exception: ", t);
- throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, t.getMessage());
- } else if (t instanceof AsyncCommandQueued) {
- throw (AsyncCommandQueued) t;
- } else if (t instanceof ServerApiException) {
- s_logger.warn(t.getClass() + " : " + ((ServerApiException) t).getDescription());
- throw (ServerApiException) t;
- } else {
- s_logger.error("Exception while executing " + cmd.getClass().getSimpleName() + ":", t);
- if (UserContext.current().getCaller().getType() == Account.ACCOUNT_TYPE_ADMIN) {
- throw new ServerApiException(BaseCmd.INTERNAL_ERROR, t.getMessage());
- } else {
- throw new ServerApiException(BaseCmd.INTERNAL_ERROR, BaseCmd.USER_ERROR_MESSAGE);
- }
- }
- }
+
}
private void doAccessChecks(BaseCmd cmd, List<Object> entitiesToAccess) {
@@@ -160,164 -137,36 +127,36 @@@
}
}
- public void dispatch(BaseCmd cmd, Map<String, String> params) {
- try {
+ public void dispatch(BaseCmd cmd, Map<String, String> params) throws Exception {
- processParameters(cmd, params);
- UserContext ctx = UserContext.current();
- ctx.setAccountId(cmd.getEntityOwnerId());
- if (cmd instanceof BaseAsyncCmd) {
-
- BaseAsyncCmd asyncCmd = (BaseAsyncCmd) cmd;
- String startEventId = params.get("ctxStartEventId");
- ctx.setStartEventId(Long.valueOf(startEventId));
-
- // Synchronise job on the object if needed
- if (asyncCmd.getJob() != null && asyncCmd.getSyncObjId() != null && asyncCmd.getSyncObjType() != null) {
- Long queueSizeLimit = null;
- if (asyncCmd.getSyncObjType() != null && asyncCmd.getSyncObjType().equalsIgnoreCase(BaseAsyncCmd.snapshotHostSyncObject)) {
- queueSizeLimit = _createSnapshotQueueSizeLimit;
- } else {
- queueSizeLimit = 1L;
- }
+ processParameters(cmd, params);
+ UserContext ctx = UserContext.current();
+ ctx.setAccountId(cmd.getEntityOwnerId());
+ if (cmd instanceof BaseAsyncCmd) {
+
+ BaseAsyncCmd asyncCmd = (BaseAsyncCmd) cmd;
+ String startEventId = params.get("ctxStartEventId");
+ ctx.setStartEventId(Long.valueOf(startEventId));
+
+ // Synchronise job on the object if needed
+ if (asyncCmd.getJob() != null && asyncCmd.getSyncObjId() != null && asyncCmd.getSyncObjType() != null) {
+ Long queueSizeLimit = null;
+ if (asyncCmd.getSyncObjType() != null && asyncCmd.getSyncObjType().equalsIgnoreCase(BaseAsyncCmd.snapshotHostSyncObject)) {
+ queueSizeLimit = _createSnapshotQueueSizeLimit;
+ } else {
+ queueSizeLimit = 1L;
+ }
- if (queueSizeLimit != null) {
+ if (queueSizeLimit != null) {
- _asyncMgr.syncAsyncJobExecution(asyncCmd.getJob(), asyncCmd.getSyncObjType(),
- asyncCmd.getSyncObjId().longValue(), queueSizeLimit);
+ _asyncMgr
+ .syncAsyncJobExecution(asyncCmd.getJob(), asyncCmd.getSyncObjType(), asyncCmd.getSyncObjId().longValue(), queueSizeLimit);
- } else {
- s_logger.trace("The queue size is unlimited, skipping the synchronizing");
+ } else {
+ s_logger.trace("The queue size is unlimited, skipping the synchronizing");
+ }
}
}
- }
- cmd.execute();
+ cmd.execute();
- } catch (Throwable t) {
- if (t instanceof InvalidParameterValueException) {
- // earlier, we'd log the db id as part of the log message, but now since we've pushed
- // the id into a IdentityProxy object, we would need to dump that object alongwith the
- // message.
- InvalidParameterValueException ref = (InvalidParameterValueException) t;
- ServerApiException ex = new ServerApiException(BaseCmd.PARAM_ERROR, t.getMessage());
- // copy over the IdentityProxy information as well and throw the serverapiexception.
- ArrayList<String> idList = ref.getIdProxyList();
- if (idList != null) {
- // Iterate through entire arraylist and copy over each proxy id.
- for (int i = 0 ; i < idList.size(); i++) {
- ex.addProxyObject(idList.get(i));
- s_logger.info(t.getMessage() + " uuid: " + idList.get(i));
- }
- } else {
- s_logger.info(t.getMessage());
- }
- // Also copy over the cserror code.
- ex.setCSErrorCode(ref.getCSErrorCode());
- throw ex;
- } else if(t instanceof IllegalArgumentException) {
- throw new ServerApiException(BaseCmd.PARAM_ERROR, t.getMessage());
- } else if (t instanceof PermissionDeniedException) {
- PermissionDeniedException ref = (PermissionDeniedException)t;
- ServerApiException ex = new ServerApiException(BaseCmd.ACCOUNT_ERROR, t.getMessage());
- // copy over the IdentityProxy information as well and throw the serverapiexception.
- ArrayList<String> idList = ref.getIdProxyList();
- if (idList != null) {
- // Iterate through entire arraylist and copy over each proxy id.
- for (int i = 0 ; i < idList.size(); i++) {
- ex.addProxyObject(idList.get(i));
- s_logger.info("PermissionDenied: " + t.getMessage() + "uuid: " + idList.get(i));
- }
- } else {
- s_logger.info("PermissionDenied: " + t.getMessage());
- }
- // Also copy over the cserror code.
- ex.setCSErrorCode(ref.getCSErrorCode());
- throw ex;
- } else if (t instanceof AccountLimitException) {
- AccountLimitException ref = (AccountLimitException)t;
- ServerApiException ex = new ServerApiException(BaseCmd.ACCOUNT_RESOURCE_LIMIT_ERROR, t.getMessage());
- // copy over the IdentityProxy information as well and throw the serverapiexception.
- ArrayList<String> idList = ref.getIdProxyList();
- if (idList != null) {
- // Iterate through entire arraylist and copy over each proxy id.
- for (int i = 0 ; i < idList.size(); i++) {
- ex.addProxyObject(idList.get(i));
- s_logger.info(t.getMessage() + "uuid: " + idList.get(i));
- }
- } else {
- s_logger.info(t.getMessage());
- }
- // Also copy over the cserror code.
- ex.setCSErrorCode(ref.getCSErrorCode());
- throw ex;
- } else if (t instanceof InsufficientCapacityException) {
- InsufficientCapacityException ref = (InsufficientCapacityException)t;
- ServerApiException ex = new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, t.getMessage());
- // copy over the IdentityProxy information as well and throw the serverapiexception.
- ArrayList<String> idList = ref.getIdProxyList();
- if (idList != null) {
- // Iterate through entire arraylist and copy over each proxy id.
- for (int i = 0 ; i < idList.size(); i++) {
- ex.addProxyObject(idList.get(i));
- s_logger.info(t.getMessage() + "uuid: " + idList.get(i));
- }
- } else {
- s_logger.info(t.getMessage());
- }
- // Also copy over the cserror code
- ex.setCSErrorCode(ref.getCSErrorCode());
- throw ex;
- } else if (t instanceof ResourceAllocationException) {
- ResourceAllocationException ref = (ResourceAllocationException)t;
- ServerApiException ex = new ServerApiException(BaseCmd.RESOURCE_ALLOCATION_ERROR, t.getMessage());
- // copy over the IdentityProxy information as well and throw the serverapiexception.
- ArrayList<String> idList = ref.getIdProxyList();
- if (idList != null) {
- // Iterate through entire arraylist and copy over each proxy id.
- for (int i = 0 ; i < idList.size(); i++) {
- String id = idList.get(i);
- ex.addProxyObject(id);
- s_logger.warn("Exception: " + t.getMessage() + "uuid: " + id);
- }
- } else {
- s_logger.warn("Exception: ", t);
- }
- // Also copy over the cserror code.
- ex.setCSErrorCode(ref.getCSErrorCode());
- throw ex;
- } else if (t instanceof ResourceUnavailableException) {
- ResourceUnavailableException ref = (ResourceUnavailableException)t;
- ServerApiException ex = new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, t.getMessage());
- // copy over the IdentityProxy information as well and throw the serverapiexception.
- ArrayList<String> idList = ref.getIdProxyList();
- if (idList != null) {
- // Iterate through entire arraylist and copy over each proxy id.
- for (int i = 0 ; i < idList.size(); i++) {
- String id = idList.get(i);
- ex.addProxyObject(id);
- s_logger.warn("Exception: " + t.getMessage() + "uuid: " + id);
- }
- } else {
- s_logger.warn("Exception: ", t);
- }
- // Also copy over the cserror code.
- ex.setCSErrorCode(ref.getCSErrorCode());
- throw ex;
- } else if (t instanceof AsyncCommandQueued) {
- throw (AsyncCommandQueued) t;
- } else if (t instanceof ServerApiException) {
- s_logger.warn(t.getClass() + " : " + ((ServerApiException) t).getDescription());
- throw (ServerApiException) t;
- } else {
- s_logger.error("Exception while executing " + cmd.getClass().getSimpleName() + ":", t);
- ServerApiException ex;
- if (UserContext.current().getCaller().getType() == Account.ACCOUNT_TYPE_ADMIN) {
- ex = new ServerApiException(BaseCmd.INTERNAL_ERROR, t.getMessage());
- } else {
- ex = new ServerApiException(BaseCmd.INTERNAL_ERROR, BaseCmd.USER_ERROR_MESSAGE);
- }
- ex.setCSErrorCode(CSExceptionErrorCode.getCSErrCode(ex.getClass().getName()));
- throw ex;
- }
- }
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@@@ -335,11 -182,11 +174,11 @@@
}
if ((unpackedParams.get(ApiConstants.PAGE) == null) && (pageSize != null && pageSize != BaseListCmd.PAGESIZE_UNLIMITED)) {
- ServerApiException ex = new ServerApiException(BaseCmd.PARAM_ERROR, "\"page\" parameter is required when \"pagesize\" is specified");
+ ServerApiException ex = new ServerApiException(ApiErrorCode.PARAM_ERROR, "\"page\" parameter is required when \"pagesize\" is specified");
ex.setCSErrorCode(CSExceptionErrorCode.getCSErrCode(ex.getClass().getName()));
- throw ex;
+ throw ex;
} else if (pageSize == null && (unpackedParams.get(ApiConstants.PAGE) != null)) {
- throw new ServerApiException(BaseCmd.PARAM_ERROR, "\"pagesize\" parameter is required when \"page\" is specified");
+ throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "\"pagesize\" parameter is required when \"page\" is specified");
}
}
@@@ -377,17 -229,16 +216,17 @@@
if (s_logger.isDebugEnabled()) {
s_logger.debug("Invalid date parameter " + paramObj + " passed to command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8));
}
- throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to parse date " + paramObj + " for command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8)
+ throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Unable to parse date " + paramObj + " for command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8)
+ ", please pass dates in the format mentioned in the api documentation");
} catch (InvalidParameterValueException invEx) {
- throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to execute API command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8) + " due to invalid value. " + invEx.getMessage());
+ throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Unable to execute API command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8) + " due to invalid value. " + invEx.getMessage());
} catch (CloudRuntimeException cloudEx) {
+ s_logger.error("CloudRuntimeException", cloudEx);
// FIXME: Better error message? This only happens if the API command is not executable, which typically
- //means
+ //means
// there was
// and IllegalAccessException setting one of the parameters.
- throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Internal error executing API command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8));
+ throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Internal error executing API command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8));
}
//check access on the resource this field points to
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/10d9c019/server/src/com/cloud/api/ApiServer.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/api/ApiServer.java
index 15d3095,33ae007..f103e30
--- a/server/src/com/cloud/api/ApiServer.java
+++ b/server/src/com/cloud/api/ApiServer.java
@@@ -52,19 -50,10 +52,19 @@@ import javax.inject.Inject
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
-import com.cloud.utils.ReflectUtil;
import org.apache.cloudstack.acl.APIChecker;
--import org.apache.cloudstack.acl.RoleType;
-import org.apache.cloudstack.api.*;
+import org.apache.cloudstack.api.APICommand;
++import org.apache.cloudstack.api.ApiErrorCode;
+import org.apache.cloudstack.api.BaseAsyncCmd;
+import org.apache.cloudstack.api.BaseAsyncCreateCmd;
+import org.apache.cloudstack.api.BaseCmd;
+import org.apache.cloudstack.api.BaseListCmd;
+import org.apache.cloudstack.api.ResponseObject;
+import org.apache.cloudstack.api.ServerApiException;
+import org.apache.cloudstack.api.command.admin.host.ListHostsCmd;
+import org.apache.cloudstack.api.command.admin.router.ListRoutersCmd;
+import org.apache.cloudstack.api.command.admin.storage.ListStoragePoolsCmd;
+import org.apache.cloudstack.api.command.admin.user.ListUsersCmd;
import org.apache.cloudstack.api.command.user.account.ListAccountsCmd;
import org.apache.cloudstack.api.command.user.account.ListProjectAccountsCmd;
import org.apache.cloudstack.api.command.user.event.ListEventsCmd;
@@@ -106,9 -89,20 +106,10 @@@ import org.apache.http.protocol.Respons
import org.apache.http.protocol.ResponseDate;
import org.apache.http.protocol.ResponseServer;
import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
-import org.apache.cloudstack.api.command.admin.host.ListHostsCmd;
-import org.apache.cloudstack.api.command.admin.router.ListRoutersCmd;
-import org.apache.cloudstack.api.command.admin.storage.ListStoragePoolsCmd;
-import org.apache.cloudstack.api.command.admin.user.ListUsersCmd;
-import org.apache.cloudstack.api.command.user.project.ListProjectInvitationsCmd;
-import org.apache.cloudstack.api.command.user.project.ListProjectsCmd;
-import org.apache.cloudstack.api.command.user.securitygroup.ListSecurityGroupsCmd;
-import org.apache.cloudstack.api.command.user.tag.ListTagsCmd;
import com.cloud.api.response.ApiResponseSerializer;
-import org.apache.cloudstack.api.response.ExceptionResponse;
-import org.apache.cloudstack.api.response.ListResponse;
-
+ import com.cloud.async.AsyncCommandQueued;
import com.cloud.async.AsyncJob;
import com.cloud.async.AsyncJobManager;
import com.cloud.async.AsyncJobVO;
@@@ -118,9 -113,14 +119,13 @@@ import com.cloud.configuration.dao.Conf
import com.cloud.domain.Domain;
import com.cloud.domain.DomainVO;
import com.cloud.event.EventUtils;
+ import com.cloud.exception.AccountLimitException;
import com.cloud.exception.CloudAuthenticationException;
+ import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.PermissionDeniedException;
+ import com.cloud.exception.ResourceAllocationException;
+ import com.cloud.exception.ResourceUnavailableException;
-import com.cloud.server.ManagementServer;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.DomainManager;
@@@ -128,18 -128,16 +133,18 @@@ import com.cloud.user.User
import com.cloud.user.UserAccount;
import com.cloud.user.UserContext;
import com.cloud.user.UserVO;
- import com.cloud.utils.Pair;
+import com.cloud.utils.NumbersUtil;
+ import com.cloud.utils.Pair;
-import com.cloud.utils.component.Adapters;
+import com.cloud.utils.ReflectUtil;
import com.cloud.utils.StringUtils;
-import com.cloud.utils.component.ComponentLocator;
-import com.cloud.utils.component.Inject;
+import com.cloud.utils.component.ComponentContext;
+import com.cloud.utils.component.PluggableService;
import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.Transaction;
- import com.cloud.utils.exception.CSExceptionErrorCode;
+
+@Component
public class ApiServer implements HttpRequestHandler {
private static final Logger s_logger = Logger.getLogger(ApiServer.class.getName());
private static final Logger s_accessLogger = Logger.getLogger("apiserver." + ApiServer.class.getName());
@@@ -166,13 -162,16 +171,13 @@@
private static ExecutorService _executor = new ThreadPoolExecutor(10, 150, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory("ApiServer"));
- protected ApiServer() {
- super();
+ public ApiServer() {
}
-
+
- public static void initApiServer() {
- if (s_instance == null) {
- //Injection will create ApiServer and all its fields which have @Inject
- s_instance = ComponentLocator.inject(ApiServer.class);
- s_instance.init();
- }
+ @PostConstruct
+ void initComponent() {
- s_instance = this;
- init();
++ s_instance = this;
++ init();
}
public static ApiServer getInstance() {
@@@ -344,11 -340,8 +349,11 @@@
Class<?> cmdClass = getCmdClass(command[0]);
if (cmdClass != null) {
BaseCmd cmdObj = (BaseCmd) cmdClass.newInstance();
+ cmdObj = ComponentContext.inject(cmdObj);
+ cmdObj.configure();
cmdObj.setFullUrlParams(paramMap);
cmdObj.setResponseType(responseType);
-
++
// This is where the command is either serialized, or directly dispatched
response = queueCommand(cmdObj, paramMap);
buildAuditTrail(auditTrailSb, command[0], response);
@@@ -361,43 -354,73 +366,73 @@@
}
}
}
- } catch (Exception ex) {
- if (ex instanceof InvalidParameterValueException) {
- InvalidParameterValueException ref = (InvalidParameterValueException)ex;
- ServerApiException e = new ServerApiException(BaseCmd.PARAM_ERROR, ex.getMessage());
- // copy over the IdentityProxy information as well and throw the serverapiexception.
- ArrayList<String> idList = ref.getIdProxyList();
- if (idList != null) {
- // Iterate through entire arraylist and copy over each proxy id.
- for (int i = 0 ; i < idList.size(); i++) {
- e.addProxyObject(idList.get(i));
- }
- }
- // Also copy over the cserror code and the function/layer in which it was thrown.
- e.setCSErrorCode(ref.getCSErrorCode());
- throw e;
- } else if (ex instanceof PermissionDeniedException) {
- PermissionDeniedException ref = (PermissionDeniedException)ex;
- ServerApiException e = new ServerApiException(BaseCmd.ACCOUNT_ERROR, ex.getMessage());
- // copy over the IdentityProxy information as well and throw the serverapiexception.
- ArrayList<String> idList = ref.getIdProxyList();
- if (idList != null) {
- // Iterate through entire arraylist and copy over each proxy id.
- for (int i = 0 ; i < idList.size(); i++) {
- e.addProxyObject(idList.get(i));
- }
- }
- e.setCSErrorCode(ref.getCSErrorCode());
- throw e;
- } else if (ex instanceof ServerApiException) {
- throw (ServerApiException) ex;
+ }
+ catch (InvalidParameterValueException ex){
+ s_logger.info(ex.getMessage());
+ throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex.getMessage(), ex);
+ }
+ catch (IllegalArgumentException ex){
+ s_logger.info(ex.getMessage());
+ throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex.getMessage(), ex);
+ }
+ catch (PermissionDeniedException ex){
+ ArrayList<String> idList = ex.getIdProxyList();
+ if (idList != null) {
+ s_logger.info("PermissionDenied: " + ex.getMessage() + " on uuids: [" + StringUtils.listToCsvTags(idList) + "]");
- } else {
+ } else {
- s_logger.error("unhandled exception executing api command: " + ((command == null) ? "null" : command[0]), ex);
- ServerApiException e = new ServerApiException(BaseCmd.INTERNAL_ERROR, "Internal server error, unable to execute request.");
- e.setCSErrorCode(CSExceptionErrorCode.getCSErrCode("ServerApiException"));
- throw e;
+ s_logger.info("PermissionDenied: " + ex.getMessage());
- }
+ }
+ throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, ex.getMessage(), ex);
}
+ catch (AccountLimitException ex){
+ s_logger.info(ex.getMessage());
+ throw new ServerApiException(ApiErrorCode.ACCOUNT_RESOURCE_LIMIT_ERROR, ex.getMessage(), ex);
+ }
+ catch (InsufficientCapacityException ex){
+ s_logger.info(ex.getMessage());
+ String errorMsg = ex.getMessage();
+ if (UserContext.current().getCaller().getType() != Account.ACCOUNT_TYPE_ADMIN){
+ // hide internal details to non-admin user for security reason
+ errorMsg = BaseCmd.USER_ERROR_MESSAGE;
+ }
+ throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, errorMsg, ex);
+ }
+ catch (ResourceAllocationException ex){
+ s_logger.info(ex.getMessage());
+ String errorMsg = ex.getMessage();
+ if (UserContext.current().getCaller().getType() != Account.ACCOUNT_TYPE_ADMIN){
+ // hide internal details to non-admin user for security reason
+ errorMsg = BaseCmd.USER_ERROR_MESSAGE;
+ }
+ throw new ServerApiException(ApiErrorCode.RESOURCE_ALLOCATION_ERROR, errorMsg, ex);
+ }
+ catch (ResourceUnavailableException ex){
+ s_logger.info(ex.getMessage());
+ String errorMsg = ex.getMessage();
+ if (UserContext.current().getCaller().getType() != Account.ACCOUNT_TYPE_ADMIN){
+ // hide internal details to non-admin user for security reason
+ errorMsg = BaseCmd.USER_ERROR_MESSAGE;
+ }
+ throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, errorMsg, ex);
+ }
+ catch (AsyncCommandQueued ex){
+ s_logger.error("unhandled exception executing api command: " + ((command == null) ? "null" : command[0]), ex);
+ throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Internal server error, unable to execute request.");
+ }
+ catch (ServerApiException ex){
+ s_logger.info(ex.getDescription());
+ throw ex;
+ }
+ catch (Exception ex){
+ s_logger.error("unhandled exception executing api command: " + ((command == null) ? "null" : command[0]), ex);
+ String errorMsg = ex.getMessage();
+ if (UserContext.current().getCaller().getType() != Account.ACCOUNT_TYPE_ADMIN){
+ // hide internal details to non-admin user for security reason
+ errorMsg = BaseCmd.USER_ERROR_MESSAGE;
+ }
+ throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, errorMsg, ex);
+ }
+
return response;
}
@@@ -405,9 -428,7 +440,9 @@@
UserContext ctx = UserContext.current();
Long callerUserId = ctx.getCallerUserId();
Account caller = ctx.getCaller();
-
+
+ BaseCmd realCmdObj = ComponentContext.getTargetObject(cmdObj);
-
++
// Queue command based on Cmd super class:
// BaseCmd: cmd is dispatched to ApiDispatcher, executed, serialized and returned.
// BaseAsyncCreateCmd: cmd params are processed and create() is called, then same workflow as BaseAsyncCmd.
@@@ -563,10 -584,13 +598,13 @@@
// if userId not null, that mean that user is logged in
if (userId != null) {
- User user = ApiDBUtils.findUserById(userId);
- try{
- checkCommandAvailable(user, commandName);
- }
- catch (PermissionDeniedException ex){
+ User user = ApiDBUtils.findUserById(userId);
- if (!isCommandAvailable(user, commandName)) {
++ try{
++ checkCommandAvailable(user, commandName);
++ }
++ catch (PermissionDeniedException ex){
s_logger.debug("The given command:" + commandName + " does not exist or it is not available for user with id:" + userId);
- throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "The given command does not exist or it is not available for user");
+ throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, "The given command does not exist or it is not available for user");
}
return true;
} else {
@@@ -689,11 -716,10 +730,10 @@@
s_logger.info("User signature: " + signature + " is not equaled to computed signature: " + computedSignature);
}
return equalSig;
+ } catch (ServerApiException ex){
+ throw ex;
- } catch (Exception ex){
+ } catch (Exception ex) {
- if (ex instanceof ServerApiException && ((ServerApiException) ex).getErrorCode() == BaseCmd.UNSUPPORTED_ACTION_ERROR) {
- throw (ServerApiException) ex;
- }
- s_logger.error("unable to verify request signature", ex);
+ s_logger.error("unable to verify request signature");
}
return false;
}
@@@ -966,48 -991,55 +1001,55 @@@
apiResponse.setErrorCode(errorCode);
apiResponse.setErrorText(errorText);
apiResponse.setResponseName(responseName);
- // Also copy over the IdentityProxy object List into this new apiResponse, from
- // the exception caught. When invoked from handle(), the exception here can
- // be either ServerApiException, PermissionDeniedException or InvalidParameterValue
- // Exception. When invoked from ApiServlet's processRequest(), this can be
- // a standard exception like NumberFormatException. We'll leave the standard ones alone.
- if (ex != null) {
- if (ex instanceof ServerApiException || ex instanceof PermissionDeniedException
- || ex instanceof InvalidParameterValueException) {
- // Cast the exception appropriately and retrieve the IdentityProxy
- if (ex instanceof ServerApiException) {
- ServerApiException ref = (ServerApiException) ex;
- ArrayList<String> idList = ref.getIdProxyList();
- if (idList != null) {
- for (int i=0; i < idList.size(); i++) {
- apiResponse.addProxyObject(idList.get(i));
- }
- }
- // Also copy over the cserror code and the function/layer in which it was thrown.
- apiResponse.setCSErrorCode(ref.getCSErrorCode());
- } else if (ex instanceof PermissionDeniedException) {
- PermissionDeniedException ref = (PermissionDeniedException) ex;
- ArrayList<String> idList = ref.getIdProxyList();
- if (idList != null) {
- for (int i=0; i < idList.size(); i++) {
- apiResponse.addProxyObject(idList.get(i));
- }
- }
- // Also copy over the cserror code and the function/layer in which it was thrown.
- apiResponse.setCSErrorCode(ref.getCSErrorCode());
- } else if (ex instanceof InvalidParameterValueException) {
- InvalidParameterValueException ref = (InvalidParameterValueException) ex;
- ArrayList<String> idList = ref.getIdProxyList();
- if (idList != null) {
- for (int i=0; i < idList.size(); i++) {
- apiResponse.addProxyObject(idList.get(i));
- }
- }
- // Also copy over the cserror code and the function/layer in which it was thrown.
- apiResponse.setCSErrorCode(ref.getCSErrorCode());
+ SerializationContext.current().setUuidTranslation(true);
+ responseText = ApiResponseSerializer.toSerializedString(apiResponse, responseType);
+
+ } catch (Exception e) {
+ s_logger.error("Exception responding to http request", e);
- }
++ }
+ return responseText;
+ }
+
+ public String getSerializedApiError(ServerApiException ex, Map<String, Object[]> apiCommandParams, String responseType) {
+ String responseName = null;
+ Class<?> cmdClass = null;
+ String responseText = null;
+
+ if (ex == null){
+ // this call should not be invoked with null exception
+ return getSerializedApiError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Some internal error happened", apiCommandParams, responseType);
- }
++ }
+ try {
+ if (ex.getErrorCode() == ApiErrorCode.UNSUPPORTED_ACTION_ERROR || apiCommandParams == null || apiCommandParams.isEmpty()) {
+ responseName = "errorresponse";
+ } else {
+ Object cmdObj = apiCommandParams.get("command");
+ // cmd name can be null when "command" parameter is missing in
+ // the request
+ if (cmdObj != null) {
+ String cmdName = ((String[]) cmdObj)[0];
+ cmdClass = getCmdClass(cmdName);
+ if (cmdClass != null) {
+ responseName = ((BaseCmd) cmdClass.newInstance()).getCommandName();
+ } else {
+ responseName = "errorresponse";
}
}
}
+ ExceptionResponse apiResponse = new ExceptionResponse();
+ apiResponse.setErrorCode(ex.getErrorCode().getHttpCode());
+ apiResponse.setErrorText(ex.getDescription());
+ apiResponse.setResponseName(responseName);
+ ArrayList<String> idList = ex.getIdProxyList();
+ if (idList != null) {
- for (int i = 0; i < idList.size(); i++) {
++ for (int i=0; i < idList.size(); i++) {
+ apiResponse.addProxyObject(idList.get(i));
- }
++ }
+ }
+ // Also copy over the cserror code and the function/layer in which
+ // it was thrown.
+ apiResponse.setCSErrorCode(ex.getCSErrorCode());
+
SerializationContext.current().setUuidTranslation(true);
responseText = ApiResponseSerializer.toSerializedString(apiResponse, responseType);
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/10d9c019/server/src/com/cloud/api/ApiServlet.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/api/ApiServlet.java
index 35bb7cc,92d3137..c816404
--- a/server/src/com/cloud/api/ApiServlet.java
+++ b/server/src/com/cloud/api/ApiServlet.java
@@@ -297,17 -306,11 +298,11 @@@ public class ApiServlet extends HttpSer
auditTrailSb.insert(0,
"(userId=" + UserContext.current().getCallerUserId() + " accountId=" + UserContext.current().getCaller().getId() + " sessionId=" + (session != null ? session.getId() : null)
- + ")");
+ + ")");
- try {
- String response = _apiServer.handleRequest(params, false, responseType, auditTrailSb);
- writeResponse(resp, response != null ? response : "", HttpServletResponse.SC_OK, responseType);
+ String response = _apiServer.handleRequest(params, false, responseType, auditTrailSb);
+ writeResponse(resp, response != null ? response : "", HttpServletResponse.SC_OK, responseType);
- } catch (ServerApiException se) {
- String serializedResponseText = _apiServer.getSerializedApiError(se.getErrorCode(), se.getDescription(), params, responseType, null);
- resp.setHeader("X-Description", se.getDescription());
- writeResponse(resp, serializedResponseText, se.getErrorCode(), responseType);
- auditTrailSb.append(" " + se.getErrorCode() + " " + se.getDescription());
- }
+
} else {
if (session != null) {
try {
@@@ -321,17 -324,14 +316,14 @@@
writeResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType);
}
- } catch (Exception ex) {
- if (ex instanceof ServerApiException && ((ServerApiException) ex).getErrorCode() == BaseCmd.UNSUPPORTED_ACTION_ERROR) {
- ServerApiException se = (ServerApiException) ex;
- String serializedResponseText = _apiServer.getSerializedApiError(se.getErrorCode(), se.getDescription(), params, responseType, null);
+ } catch (ServerApiException se) {
+ String serializedResponseText = _apiServer.getSerializedApiError(se, params, responseType);
- resp.setHeader("X-Description", se.getDescription());
+ resp.setHeader("X-Description", se.getDescription());
- writeResponse(resp, serializedResponseText, se.getErrorCode(), responseType);
+ writeResponse(resp, serializedResponseText, se.getErrorCode().getHttpCode(), responseType);
- auditTrailSb.append(" " + se.getErrorCode() + " " + se.getDescription());
+ auditTrailSb.append(" " + se.getErrorCode() + " " + se.getDescription());
- } else {
+ } catch (Exception ex) {
- s_logger.error("unknown exception writing api response", ex);
- auditTrailSb.append(" unknown exception writing api response");
+ s_logger.error("unknown exception writing api response", ex);
+ auditTrailSb.append(" unknown exception writing api response");
- }
} finally {
s_accessLogger.info(auditTrailSb.toString());
if (s_logger.isDebugEnabled()) {
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/10d9c019/server/src/com/cloud/api/commands/AddTrafficMonitorCmd.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/api/commands/AddTrafficMonitorCmd.java
index c80a62b,cdf83ae..e9e2bfb
--- a/server/src/com/cloud/api/commands/AddTrafficMonitorCmd.java
+++ b/server/src/com/cloud/api/commands/AddTrafficMonitorCmd.java
@@@ -89,20 -85,22 +89,20 @@@ public class AddTrafficMonitorCmd exten
public long getEntityOwnerId() {
return Account.ACCOUNT_ID_SYSTEM;
}
-
- @Override
+
+ @Override
public void execute(){
- try {
- ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name);
- NetworkUsageManager networkUsageMgr = locator.getManager(NetworkUsageManager.class);
- Host trafficMonitor = networkUsageMgr.addTrafficMonitor(this);
- TrafficMonitorResponse response = networkUsageMgr.getApiResponse(trafficMonitor);
- response.setObjectName("trafficmonitor");
- response.setResponseName(getCommandName());
- this.setResponseObject(response);
- } catch (InvalidParameterValueException ipve) {
+ try {
+ Host trafficMonitor = networkUsageMgr.addTrafficMonitor(this);
+ TrafficMonitorResponse response = networkUsageMgr.getApiResponse(trafficMonitor);
+ response.setObjectName("trafficmonitor");
+ response.setResponseName(getCommandName());
+ this.setResponseObject(response);
+ } catch (InvalidParameterValueException ipve) {
- throw new ServerApiException(BaseCmd.PARAM_ERROR, ipve.getMessage());
+ throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ipve.getMessage());
- } catch (CloudRuntimeException cre) {
+ } catch (CloudRuntimeException cre) {
- throw new ServerApiException(BaseCmd.INTERNAL_ERROR, cre.getMessage());
+ throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, cre.getMessage());
- }
+ }
}
}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/10d9c019/server/src/com/cloud/api/commands/DeleteTrafficMonitorCmd.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/api/commands/DeleteTrafficMonitorCmd.java
index 9e84f03,d39323a..081d0be
--- a/server/src/com/cloud/api/commands/DeleteTrafficMonitorCmd.java
+++ b/server/src/com/cloud/api/commands/DeleteTrafficMonitorCmd.java
@@@ -16,20 -16,21 +16,21 @@@
// under the License.
package com.cloud.api.commands;
-import org.apache.cloudstack.api.response.HostResponse;
-import org.apache.log4j.Logger;
+import javax.inject.Inject;
+import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
+ import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.BaseCmd;
-import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ServerApiException;
+import org.apache.cloudstack.api.response.HostResponse;
import org.apache.cloudstack.api.response.SuccessResponse;
+import org.apache.log4j.Logger;
+
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.network.NetworkUsageManager;
-import com.cloud.server.ManagementService;
import com.cloud.user.Account;
-import com.cloud.utils.component.ComponentLocator;
@APICommand(name = "deleteTrafficMonitor", description="Deletes an traffic monitor host.", responseObject = SuccessResponse.class)
public class DeleteTrafficMonitorCmd extends BaseCmd {
@@@ -67,19 -67,21 +68,19 @@@
return Account.ACCOUNT_ID_SYSTEM;
}
- @Override
+ @Override
public void execute(){
- try {
- ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name);
- NetworkUsageManager _networkUsageMgr = locator.getManager(NetworkUsageManager.class);
- boolean result = _networkUsageMgr.deleteTrafficMonitor(this);
- if (result) {
- SuccessResponse response = new SuccessResponse(getCommandName());
- response.setResponseName(getCommandName());
- this.setResponseObject(response);
- } else {
+ try {
+ boolean result = _networkUsageMgr.deleteTrafficMonitor(this);
+ if (result) {
+ SuccessResponse response = new SuccessResponse(getCommandName());
+ response.setResponseName(getCommandName());
+ this.setResponseObject(response);
+ } else {
- throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete traffic monitor.");
+ throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete traffic monitor.");
- }
- } catch (InvalidParameterValueException e) {
+ }
+ } catch (InvalidParameterValueException e) {
- throw new ServerApiException(BaseCmd.PARAM_ERROR, "Failed to delete traffic monitor.");
+ throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Failed to delete traffic monitor.");
- }
+ }
}
}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/10d9c019/server/src/com/cloud/async/AsyncJobExecutorContextImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/async/AsyncJobExecutorContextImpl.java
index 4181448,dee1f58..24d8c20
--- a/server/src/com/cloud/async/AsyncJobExecutorContextImpl.java
+++ b/server/src/com/cloud/async/AsyncJobExecutorContextImpl.java
@@@ -27,7 -24,8 +27,7 @@@ import org.springframework.stereotype.C
import com.cloud.agent.AgentManager;
import com.cloud.async.dao.AsyncJobDao;
import com.cloud.event.dao.EventDao;
--import com.cloud.network.NetworkManager;
+ import com.cloud.network.NetworkModel;
import com.cloud.network.dao.IPAddressDao;
import com.cloud.server.ManagementServer;
import com.cloud.storage.StorageManager;
@@@ -41,58 -40,57 +41,58 @@@ import com.cloud.vm.VirtualMachineManag
import com.cloud.vm.dao.DomainRouterDao;
import com.cloud.vm.dao.UserVmDao;
+@Component
@Local(value={AsyncJobExecutorContext.class})
public class AsyncJobExecutorContextImpl implements AsyncJobExecutorContext {
- private String _name;
-
- private AgentManager _agentMgr;
- private NetworkModel _networkMgr;
- private UserVmManager _vmMgr;
- private SnapshotManager _snapMgr;
- private AccountManager _accountMgr;
- private StorageManager _storageMgr;
- private EventDao _eventDao;
- private UserVmDao _vmDao;
- private AccountDao _accountDao;
- private VolumeDao _volumeDao;
- private DomainRouterDao _routerDao;
- private IPAddressDao _ipAddressDao;
- private AsyncJobDao _jobDao;
- private UserDao _userDao;
- private VirtualMachineManager _itMgr;
-
- private ManagementServer _managementServer;
-
- @Override
- public ManagementServer getManagementServer() {
- return _managementServer;
- }
-
- @Override
- public AgentManager getAgentMgr() {
- return _agentMgr;
- }
-
- @Override
- public NetworkModel getNetworkMgr() {
- return _networkMgr;
- }
-
- @Override
- public UserVmManager getVmMgr() {
- return _vmMgr;
- }
-
- @Override
- public StorageManager getStorageMgr() {
- return _storageMgr;
- }
-
- /**server/src/com/cloud/async/AsyncJobExecutorContext.java
+ private String _name;
+
+ @Inject private AgentManager _agentMgr;
- @Inject private NetworkManager _networkMgr;
++ @Inject private NetworkModel _networkMgr;
+ @Inject private UserVmManager _vmMgr;
+ @Inject private SnapshotManager _snapMgr;
+ @Inject private AccountManager _accountMgr;
+ @Inject private StorageManager _storageMgr;
+ @Inject private EventDao _eventDao;
+ @Inject private UserVmDao _vmDao;
+ @Inject private AccountDao _accountDao;
+ @Inject private VolumeDao _volumeDao;
+ @Inject private DomainRouterDao _routerDao;
+ @Inject private IPAddressDao _ipAddressDao;
+ @Inject private AsyncJobDao _jobDao;
+ @Inject private UserDao _userDao;
+ @Inject private VirtualMachineManager _itMgr;
+
+ @Inject private ManagementServer _managementServer;
+
+ @Override
+ public ManagementServer getManagementServer() {
+ return _managementServer;
+ }
+
+ @Override
+ public AgentManager getAgentMgr() {
+ return _agentMgr;
+ }
+
+ @Override
- public NetworkManager getNetworkMgr() {
++ public NetworkModel getNetworkMgr() {
+ return _networkMgr;
+ }
+
+ @Override
+ public UserVmManager getVmMgr() {
+ return _vmMgr;
+ }
+
+ @Override
+ public StorageManager getStorageMgr() {
+ return _storageMgr;
+ }
+
+ /**server/src/com/cloud/async/AsyncJobExecutorContext.java
* @return the _snapMgr
*/
- @Override
+ @Override
public SnapshotManager getSnapshotMgr() {
return _snapMgr;
}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/10d9c019/server/src/com/cloud/async/AsyncJobManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/async/AsyncJobManagerImpl.java
index c733d73,05d305e..bdf2b71
--- a/server/src/com/cloud/async/AsyncJobManagerImpl.java
+++ b/server/src/com/cloud/async/AsyncJobManagerImpl.java
@@@ -32,17 -32,11 +32,17 @@@ import java.util.concurrent.ScheduledEx
import java.util.concurrent.TimeUnit;
import javax.ejb.Local;
+import javax.inject.Inject;
import javax.naming.ConfigurationException;
++import org.apache.cloudstack.api.ApiErrorCode;
+import org.apache.cloudstack.api.BaseAsyncCmd;
- import org.apache.cloudstack.api.BaseCmd;
+import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.command.user.job.QueryAsyncJobResultCmd;
+import org.apache.cloudstack.api.response.ExceptionResponse;
import org.apache.log4j.Logger;
import org.apache.log4j.NDC;
+import org.springframework.stereotype.Component;
import com.cloud.api.ApiDispatcher;
import com.cloud.api.ApiGsonHelper;
@@@ -745,15 -783,15 +745,15 @@@ public class AsyncJobManagerImpl implem
}
@Override
- public void onManagementNodeIsolated() {
- }
-
- @Override
+ public void onManagementNodeIsolated() {
+ }
+
+ @Override
public boolean start() {
- try {
+ try {
List<SyncQueueItemVO> l = _queueMgr.getActiveQueueItems(getMsid(), false);
cleanupPendingJobs(l);
- _jobDao.resetJobProcess(getMsid(), BaseCmd.INTERNAL_ERROR, getSerializedErrorMessage("job cancelled because of management server restart"));
+ _jobDao.resetJobProcess(getMsid(), ApiErrorCode.INTERNAL_ERROR.getHttpCode(), getSerializedErrorMessage("job cancelled because of management server restart"));
} catch(Throwable e) {
s_logger.error("Unexpected exception " + e.getMessage(), e);
}
@@@ -767,10 -805,10 +767,10 @@@
}
private static ExceptionResponse getResetResultResponse(String errorMessage) {
- ExceptionResponse resultObject = new ExceptionResponse();
- resultObject.setErrorCode(ApiErrorCode.INTERNAL_ERROR.getHttpCode());
- resultObject.setErrorText(errorMessage);
- return resultObject;
+ ExceptionResponse resultObject = new ExceptionResponse();
- resultObject.setErrorCode(BaseCmd.INTERNAL_ERROR);
++ resultObject.setErrorCode(ApiErrorCode.INTERNAL_ERROR.getHttpCode());
+ resultObject.setErrorText(errorMessage);
+ return resultObject;
}
private static String getSerializedErrorMessage(String errorMessage) {
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/10d9c019/server/src/com/cloud/baremetal/BareMetalVmManagerImpl.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/10d9c019/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/configuration/ConfigurationManagerImpl.java
index a8c1743,df6642a..0e3363e
--- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
+++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
@@@ -2075,7 -2077,12 +2081,12 @@@ public class ConfigurationManagerImpl i
Long projectId = cmd.getProjectId();
Long domainId = cmd.getDomainId();
Account vlanOwner = null;
-
+
+ // if end ip is not specified, default it to startIp
+ if (endIP == null && startIP != null) {
+ endIP = startIP;
+ }
+
if (projectId != null) {
if (accountName != null) {
throw new InvalidParameterValueException("Account and projectId are mutually exclusive");
@@@ -2196,34 -2204,34 +2208,34 @@@
endIP = startIP;
}
- if (forVirtualNetwork || zone.getNetworkType() == DataCenter.NetworkType.Basic || zone.isSecurityGroupEnabled()) {
- if (vlanGateway == null || vlanNetmask == null || zoneId == null) {
- throw new InvalidParameterValueException("Gateway, netmask and zoneId have to be passed in for virtual and direct untagged networks");
+ if ( zone.getNetworkType() == DataCenter.NetworkType.Advanced ) {
+ if (network.getTrafficType() == TrafficType.Guest) {
+ if (network.getGuestType() != GuestType.Shared) {
+ throw new InvalidParameterValueException("Can execute createVLANIpRanges on shared guest network, but type of this guest network "
+ + network.getId() + " is " + network.getGuestType());
- }
+ }
- } else {
- // check if startIp and endIp belong to network Cidr
- String networkCidr = network.getCidr();
- String networkGateway = network.getGateway();
- Long networkZoneId = network.getDataCenterId();
- String networkNetmask = NetUtils.getCidrNetmask(networkCidr);
-
- // Check if ip addresses are in network range
- if (!NetUtils.sameSubnet(startIP, networkGateway, networkNetmask)) {
- throw new InvalidParameterValueException("Start ip is not in network cidr: " + networkCidr);
+ List<VlanVO> vlans = _vlanDao.listVlansByNetworkId(network.getId());
+ if ( vlans != null && vlans.size() > 0 ) {
+ VlanVO vlan = vlans.get(0);
+ if ( vlanId == null ) {
+ vlanId = vlan.getVlanTag();
+ } else if ( vlan.getVlanTag() != vlanId ) {
+ throw new InvalidParameterValueException("there is already one vlan " + vlan.getVlanTag() + " on network :" +
+ + network.getId() + ", only one vlan is allowed on guest network");
- }
+ }
-
- if (endIP != null) {
- if (!NetUtils.sameSubnet(endIP, networkGateway, networkNetmask)) {
- throw new InvalidParameterValueException("End ip is not in network cidr: " + networkCidr);
+ vlanGateway = vlan.getVlanGateway();
+ vlanNetmask = vlan.getVlanNetmask();
+ }
+ } else if (network.getTrafficType() == TrafficType.Management) {
+ throw new InvalidParameterValueException("Cannot execute createVLANIpRanges on management network");
+ }
}
- }
- // set gateway, netmask, zone from network object
- vlanGateway = networkGateway;
- vlanNetmask = networkNetmask;
- zoneId = networkZoneId;
+ if (vlanGateway == null || vlanNetmask == null || zoneId == null) {
+ throw new InvalidParameterValueException("Gateway, netmask and zoneId have to be passed in for virtual and direct untagged networks");
}
+
// if it's an account specific range, associate ip address list to the account
boolean associateIpRangeToAccount = false;
@@@ -2272,10 -2280,10 +2284,10 @@@
public Vlan createVlanAndPublicIpRange(long zoneId, long networkId, long physicalNetworkId, boolean forVirtualNetwork, Long podId,
String startIP, String endIP, String vlanGateway, String vlanNetmask,
String vlanId, Account vlanOwner) {
-
-
+
+
- Network network = _networkMgr.getNetwork(networkId);
+ Network network = _networkModel.getNetwork(networkId);
-
+
//Validate the zone
DataCenterVO zone = _zoneDao.findById(zoneId);
if (zone == null) {
@@@ -2514,8 -2522,8 +2526,8 @@@
throw new InvalidParameterValueException("Can't delete account specific vlan " + vlanDbId +
" as ip " + ip + " belonging to the range is used for static nat purposes. Cleanup the rules first");
}
-
+
- if (ip.isSourceNat() && _networkMgr.getNetwork(ip.getAssociatedWithNetworkId()) != null) {
+ if (ip.isSourceNat() && _networkModel.getNetwork(ip.getAssociatedWithNetworkId()) != null) {
throw new InvalidParameterValueException("Can't delete account specific vlan " + vlanDbId +
" as ip " + ip + " belonging to the range is a source nat ip for the network id=" + ip.getSourceNetworkId() +
". IP range with the source nat ip address can be removed either as a part of Network, or account removal");
@@@ -3170,24 -3176,13 +3180,13 @@@
for (Capability capability : staticNatServiceCapabilityMap.keySet()) {
String value = staticNatServiceCapabilityMap.get(capability);
if (capability == Capability.ElasticIp) {
- eipEnabled = value.contains("true");
- eipDisabled = value.contains("false");
- if (!eipEnabled && !eipDisabled) {
+ boolean enabled = value.contains("true");
+ boolean disabled = value.contains("false");
+ if (!enabled && !disabled) {
throw new InvalidParameterValueException("Unknown specified value for " + Capability.ElasticIp.getName());
}
- } else if (capability == Capability.AssociatePublicIP) {
- if (value.contains("true")) {
- associatePublicIP = true;
- } else if (value.contains("false")) {
- associatePublicIP = false;
- } else {
+ } else {
- throw new InvalidParameterValueException("Unknown specified value for " + Capability.AssociatePublicIP.getName());
- }
- } else {
- throw new InvalidParameterValueException("Only " + Capability.ElasticIp.getName() + " and " + Capability.AssociatePublicIP.getName() + " capabilitiy can be sepcified for static nat service");
- }
- if (eipDisabled && associatePublicIP) {
- throw new InvalidParameterValueException("Capability " + Capability.AssociatePublicIP.getName() + " can only be set when capability " + Capability.ElasticIp.getName() + " is true");
+ throw new InvalidParameterValueException("Only " + Capability.ElasticIp.getName() + " capability can be specified for static nat service");
}
}
}
@@@ -3259,10 -3253,10 +3257,10 @@@
if (param != null) {
elasticLb = param.contains("true");
}
-
+
String inlineMode = lbServiceCapabilityMap.get(Capability.InlineMode);
if (inlineMode != null) {
- _networkMgr.checkCapabilityForProvider(serviceProviderMap.get(Service.Lb), Service.Lb, Capability.InlineMode, inlineMode);
+ _networkModel.checkCapabilityForProvider(serviceProviderMap.get(Service.Lb), Service.Lb, Capability.InlineMode, inlineMode);
inline = inlineMode.contains("true");
} else {
inline = false;
@@@ -3545,9 -3535,9 +3539,9 @@@
}
if (sourceNatSupported != null) {
- addOffering = addOffering && (_networkMgr.areServicesSupportedByNetworkOffering(offering.getId(), Network.Service.SourceNat) == sourceNatSupported);
+ addOffering = addOffering && (_networkModel.areServicesSupportedByNetworkOffering(offering.getId(), Network.Service.SourceNat) == sourceNatSupported);
}
-
+
if (forVpc != null) {
addOffering = addOffering && (isOfferingForVpc(offering) == forVpc.booleanValue());
} else if (network != null){
@@@ -3670,10 -3660,10 +3664,10 @@@
} else {
if (availability == NetworkOffering.Availability.Required) {
boolean canOffBeRequired = (offeringToUpdate.getGuestType() == GuestType.Isolated
- && _networkMgr.areServicesSupportedByNetworkOffering(offeringToUpdate.getId(), Service.SourceNat));
+ && _networkModel.areServicesSupportedByNetworkOffering(offeringToUpdate.getId(), Service.SourceNat));
if (!canOffBeRequired) {
throw new InvalidParameterValueException("Availability can be " +
- NetworkOffering.Availability.Required + " only for networkOfferings of type " + GuestType.Isolated + " and with "
+ NetworkOffering.Availability.Required + " only for networkOfferings of type " + GuestType.Isolated + " and with "
+ Service.SourceNat.getName() + " enabled");
}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/10d9c019/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/10d9c019/server/src/com/cloud/ha/ManagementIPSystemVMInvestigator.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/ha/ManagementIPSystemVMInvestigator.java
index 81bdc73,ea96202..17f0355
--- a/server/src/com/cloud/ha/ManagementIPSystemVMInvestigator.java
+++ b/server/src/com/cloud/ha/ManagementIPSystemVMInvestigator.java
@@@ -28,8 -27,9 +28,8 @@@ import org.apache.log4j.Logger
import com.cloud.host.HostVO;
import com.cloud.host.Status;
import com.cloud.host.dao.HostDao;
- import com.cloud.network.NetworkManager;
+ import com.cloud.network.NetworkModel;
import com.cloud.network.Networks.TrafficType;
-import com.cloud.utils.component.Inject;
import com.cloud.vm.Nic;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine;
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/10d9c019/server/src/com/cloud/ha/UserVmDomRInvestigator.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/10d9c019/server/src/com/cloud/hypervisor/HypervisorGuruBase.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/10d9c019/server/src/com/cloud/hypervisor/kvm/discoverer/KvmServerDiscoverer.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/hypervisor/kvm/discoverer/KvmServerDiscoverer.java
index 84bb4ba,60b6e7f..128c20c
--- a/server/src/com/cloud/hypervisor/kvm/discoverer/KvmServerDiscoverer.java
+++ b/server/src/com/cloud/hypervisor/kvm/discoverer/KvmServerDiscoverer.java
@@@ -52,7 -51,8 +52,7 @@@ import com.cloud.host.Status
import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
- import com.cloud.network.NetworkManager;
-import com.cloud.hypervisor.kvm.discoverer.KvmDummyResourceBase;
+ import com.cloud.network.NetworkModel;
import com.cloud.network.PhysicalNetworkSetupInfo;
import com.cloud.resource.Discoverer;
import com.cloud.resource.DiscovererBase;
@@@ -64,82 -67,82 +64,82 @@@ import com.cloud.utils.ssh.SSHCmdHelper
@Local(value=Discoverer.class)
public class KvmServerDiscoverer extends DiscovererBase implements Discoverer,
- Listener, ResourceStateAdapter {
- private static final Logger s_logger = Logger.getLogger(KvmServerDiscoverer.class);
- private ConfigurationDao _configDao;
- private String _hostIp;
- private int _waitTime = 5; /*wait for 5 minutes*/
- private String _kvmPrivateNic;
- private String _kvmPublicNic;
- private String _kvmGuestNic;
- @Inject HostDao _hostDao = null;
- @Inject ClusterDao _clusterDao;
- @Inject ResourceManager _resourceMgr;
- @Inject AgentManager _agentMgr;
- @Inject NetworkModel _networkMgr;
-
- @Override
- public boolean processAnswers(long agentId, long seq, Answer[] answers) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public boolean processCommands(long agentId, long seq, Command[] commands) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public AgentControlAnswer processControlCommand(long agentId,
- AgentControlCommand cmd) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public void processConnect(HostVO host, StartupCommand cmd, boolean forRebalance) {
- }
-
- @Override
- public boolean processDisconnect(long agentId, Status state) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public boolean isRecurring() {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public int getTimeout() {
- // TODO Auto-generated method stub
- return 0;
- }
-
- @Override
- public boolean processTimeout(long agentId, long seq) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public Map<? extends ServerResource, Map<String, String>> find(long dcId,
- Long podId, Long clusterId, URI uri, String username,
- String password, List<String> hostTags) throws DiscoveryException {
-
+Listener, ResourceStateAdapter {
+ private static final Logger s_logger = Logger.getLogger(KvmServerDiscoverer.class);
+ private String _hostIp;
+ private final int _waitTime = 5; /*wait for 5 minutes*/
+ private String _kvmPrivateNic;
+ private String _kvmPublicNic;
+ private String _kvmGuestNic;
+ @Inject HostDao _hostDao = null;
+ @Inject ClusterDao _clusterDao;
+ @Inject ResourceManager _resourceMgr;
+ @Inject AgentManager _agentMgr;
- @Inject NetworkManager _networkMgr;
+ @Inject ConfigurationDao _configDao;
++ @Inject NetworkModel _networkMgr;
+
+ @Override
+ public boolean processAnswers(long agentId, long seq, Answer[] answers) {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public boolean processCommands(long agentId, long seq, Command[] commands) {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public AgentControlAnswer processControlCommand(long agentId,
+ AgentControlCommand cmd) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public void processConnect(HostVO host, StartupCommand cmd, boolean forRebalance) {
+ }
+
+ @Override
+ public boolean processDisconnect(long agentId, Status state) {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public boolean isRecurring() {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public int getTimeout() {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+
+ @Override
+ public boolean processTimeout(long agentId, long seq) {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public Map<? extends ServerResource, Map<String, String>> find(long dcId,
+ Long podId, Long clusterId, URI uri, String username,
+ String password, List<String> hostTags) throws DiscoveryException {
+
ClusterVO cluster = _clusterDao.findById(clusterId);
if(cluster == null || cluster.getHypervisorType() != HypervisorType.KVM) {
- if(s_logger.isInfoEnabled())
- s_logger.info("invalid cluster id or cluster is not for KVM hypervisors");
- return null;
+ if(s_logger.isInfoEnabled())
+ s_logger.info("invalid cluster id or cluster is not for KVM hypervisors");
+ return null;
}
-
- Map<KvmDummyResourceBase, Map<String, String>> resources = new HashMap<KvmDummyResourceBase, Map<String, String>>();
- Map<String, String> details = new HashMap<String, String>();
- if (!uri.getScheme().equals("http")) {
+
+ Map<KvmDummyResourceBase, Map<String, String>> resources = new HashMap<KvmDummyResourceBase, Map<String, String>>();
+ Map<String, String> details = new HashMap<String, String>();
+ if (!uri.getScheme().equals("http")) {
String msg = "urlString is not http so we're not taking care of the discovery for this: " + uri;
s_logger.debug(msg);
return null;
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/10d9c019/server/src/com/cloud/network/ExternalFirewallDeviceManagerImpl.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/10d9c019/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java
index ee082e0,275401c..d1e1faf
--- a/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java
+++ b/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java
@@@ -741,9 -743,9 +743,9 @@@ public abstract class ExternalLoadBalan
this.state = state;
}
};
-
+
private MappingNic getLoadBalancingIpNic(DataCenterVO zone, Network network, long sourceIpId, boolean revoked, String existedGuestIp) throws ResourceUnavailableException {
- String srcIp = _networkMgr.getIp(sourceIpId).getAddress().addr();
+ String srcIp = _networkModel.getIp(sourceIpId).getAddress().addr();
InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(srcIp);
NicVO loadBalancingIpNic = null;
MappingNic nic = new MappingNic();
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/10d9c019/server/src/com/cloud/network/ExternalLoadBalancerUsageManagerImpl.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/10d9c019/server/src/com/cloud/network/ExternalNetworkDeviceManagerImpl.java
----------------------------------------------------------------------