Skip to content

Commit f4caf14

Browse files
author
Kris McQueen
committed
Refactoring dispatching API commands from the scheduled async job. Instead of calling an executor, the dispatcher invokes the method on the manager directly. After the command is executed the response is serialized to the async job table so it can be queried later. Also serialize a response for async create commands that includes the id of the object being created.
1 parent a8112f6 commit f4caf14

6 files changed

Lines changed: 287 additions & 77 deletions

File tree

‎server/src/com/cloud/api/ApiDispatcher.java‎

Lines changed: 91 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,14 @@ public class ApiDispatcher {
3838
private StorageManager _storageMgr;
3939
private UserVmManager _userVmMgr;
4040

41-
public ApiDispatcher() {
41+
// singleton class
42+
private static ApiDispatcher s_instance = new ApiDispatcher();
43+
44+
public static ApiDispatcher getInstance() {
45+
return s_instance;
46+
}
47+
48+
private ApiDispatcher() {
4249
ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name);
4350
_mgmtServer = (ManagementServer)ComponentLocator.getComponent(ManagementServer.Name);
4451
_configMgr = locator.getManager(ConfigurationManager.class);
@@ -49,42 +56,55 @@ public ApiDispatcher() {
4956
_userVmMgr = locator.getManager(UserVmManager.class);
5057
}
5158

52-
public void dispatch(BaseCmd cmd, Map<String, String> params) {
53-
Map<String, Object> unpackedParams = cmd.unpackParams(params);
54-
Field[] fields = cmd.getClass().getDeclaredFields();
55-
for (Field field : fields) {
56-
Parameter parameterAnnotation = field.getAnnotation(Parameter.class);
57-
if (parameterAnnotation == null) {
58-
continue;
59-
}
60-
Object paramObj = unpackedParams.get(parameterAnnotation.name());
61-
if (paramObj == null) {
62-
if (parameterAnnotation.required()) {
63-
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to execute API command " + cmd.getName() + " due to missing parameter " + parameterAnnotation.name());
64-
}
65-
continue;
66-
}
59+
public Long dispatchCreateCmd(BaseAsyncCreateCmd cmd, Map<String, String> params) {
60+
setupParameters(cmd, params);
6761

68-
// marshall the parameter into the correct type and set the field value
69-
try {
70-
setFieldValue(field, cmd, paramObj, parameterAnnotation);
71-
} catch (IllegalArgumentException argEx) {
72-
if (s_logger.isDebugEnabled()) {
73-
s_logger.debug("Unable to execute API command " + cmd.getName() + " due to invalid value " + paramObj + " for parameter " + parameterAnnotation.name());
74-
}
75-
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to execute API command " + cmd.getName() + " due to invalid value " + paramObj + " for parameter " + parameterAnnotation.name());
76-
} catch (ParseException parseEx) {
77-
if (s_logger.isDebugEnabled()) {
78-
s_logger.debug("Invalid date parameter " + paramObj + " passed to command " + cmd.getName());
79-
}
80-
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to parse date " + paramObj + " for command " + cmd.getName() + ", please pass dates in the format yyyy-MM-dd");
81-
} catch (CloudRuntimeException cloudEx) {
82-
// FIXME: Better error message? This only happens if the API command is not executable, which typically means there was
83-
// and IllegalAccessException setting one of the parameters.
84-
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Internal error executing API command " + cmd.getName());
85-
}
62+
Implementation impl = cmd.getClass().getAnnotation(Implementation.class);
63+
String methodName = impl.createMethod();
64+
Object mgr = _mgmtServer;
65+
switch (impl.manager()) {
66+
case ConfigManager:
67+
mgr = _configMgr;
68+
break;
69+
case NetworkGroupManager:
70+
mgr = _networkGroupMgr;
71+
break;
72+
case NetworkManager:
73+
mgr = _networkMgr;
74+
break;
75+
case SnapshotManager:
76+
mgr = _snapshotMgr;
77+
break;
78+
case StorageManager:
79+
mgr = _storageMgr;
80+
break;
81+
case UserVmManager:
82+
mgr = _userVmMgr;
83+
break;
8684
}
8785

86+
try {
87+
Method method = mgr.getClass().getMethod(methodName, cmd.getClass());
88+
method.invoke(mgr, cmd);
89+
return cmd.getId();
90+
} catch (NoSuchMethodException nsme) {
91+
s_logger.warn("Exception executing method " + methodName + " for command " + cmd.getClass().getSimpleName(), nsme);
92+
throw new CloudRuntimeException("Unable to execute method " + methodName + " for command " + cmd.getClass().getSimpleName() + ", unable to find implementation.");
93+
} catch (InvocationTargetException ite) {
94+
s_logger.warn("Exception executing method " + methodName + " for command " + cmd.getClass().getSimpleName(), ite);
95+
throw new CloudRuntimeException("Unable to execute method " + methodName + " for command " + cmd.getClass().getSimpleName() + ", internal error in the implementation.");
96+
} catch (IllegalAccessException iae) {
97+
s_logger.warn("Exception executing method " + methodName + " for command " + cmd.getClass().getSimpleName(), iae);
98+
throw new CloudRuntimeException("Unable to execute method " + methodName + " for command " + cmd.getClass().getSimpleName() + ", internal error in the implementation.");
99+
} catch (IllegalArgumentException iArgEx) {
100+
s_logger.warn("Exception executing method " + methodName + " for command " + cmd.getClass().getSimpleName(), iArgEx);
101+
throw new CloudRuntimeException("Unable to execute method " + methodName + " for command " + cmd.getClass().getSimpleName() + ", internal error in the implementation.");
102+
}
103+
}
104+
105+
public void dispatch(BaseCmd cmd, Map<String, String> params) {
106+
setupParameters(cmd, params);
107+
88108
Implementation impl = cmd.getClass().getAnnotation(Implementation.class);
89109
String methodName = impl.method();
90110
Object mgr = _mgmtServer;
@@ -127,6 +147,43 @@ public void dispatch(BaseCmd cmd, Map<String, String> params) {
127147
}
128148
}
129149

150+
private void setupParameters(BaseCmd cmd, Map<String, String> params) {
151+
Map<String, Object> unpackedParams = cmd.unpackParams(params);
152+
Field[] fields = cmd.getClass().getDeclaredFields();
153+
for (Field field : fields) {
154+
Parameter parameterAnnotation = field.getAnnotation(Parameter.class);
155+
if (parameterAnnotation == null) {
156+
continue;
157+
}
158+
Object paramObj = unpackedParams.get(parameterAnnotation.name());
159+
if (paramObj == null) {
160+
if (parameterAnnotation.required()) {
161+
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to execute API command " + cmd.getName() + " due to missing parameter " + parameterAnnotation.name());
162+
}
163+
continue;
164+
}
165+
166+
// marshall the parameter into the correct type and set the field value
167+
try {
168+
setFieldValue(field, cmd, paramObj, parameterAnnotation);
169+
} catch (IllegalArgumentException argEx) {
170+
if (s_logger.isDebugEnabled()) {
171+
s_logger.debug("Unable to execute API command " + cmd.getName() + " due to invalid value " + paramObj + " for parameter " + parameterAnnotation.name());
172+
}
173+
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to execute API command " + cmd.getName() + " due to invalid value " + paramObj + " for parameter " + parameterAnnotation.name());
174+
} catch (ParseException parseEx) {
175+
if (s_logger.isDebugEnabled()) {
176+
s_logger.debug("Invalid date parameter " + paramObj + " passed to command " + cmd.getName());
177+
}
178+
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to parse date " + paramObj + " for command " + cmd.getName() + ", please pass dates in the format yyyy-MM-dd");
179+
} catch (CloudRuntimeException cloudEx) {
180+
// FIXME: Better error message? This only happens if the API command is not executable, which typically means there was
181+
// and IllegalAccessException setting one of the parameters.
182+
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Internal error executing API command " + cmd.getName());
183+
}
184+
}
185+
}
186+
130187
@SuppressWarnings({"unchecked", "rawtypes"})
131188
private void setFieldValue(Field field, BaseCmd cmdObj, Object paramObj, Parameter annotation) throws IllegalArgumentException, ParseException {
132189
try {

‎server/src/com/cloud/api/ApiServer.java‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ public void init(String[] apiConfig) {
186186
_ms = (ManagementServer)ComponentLocator.getComponent(ManagementServer.Name);
187187
ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name);
188188
_asyncMgr = locator.getManager(AsyncJobManager.class);
189-
_dispatcher = new ApiDispatcher();
189+
_dispatcher = ApiDispatcher.getInstance();
190190

191191
int apiPort = 8096; // default port
192192
ConfigurationDao configDao = locator.getDao(ConfigurationDao.class);
@@ -347,6 +347,10 @@ public String handleRequest(Map params, boolean decode, String responseType) thr
347347

348348
private String queueCommand(BaseCmd cmdObj, Map<String, String> params) {
349349
if (cmdObj instanceof BaseAsyncCmd) {
350+
Long objectId = null;
351+
if (cmdObj instanceof BaseAsyncCreateCmd) {
352+
objectId = _dispatcher.dispatchCreateCmd((BaseAsyncCreateCmd)cmdObj, params);
353+
}
350354
BaseAsyncCmd asyncCmd = (BaseAsyncCmd)cmdObj;
351355

352356
Gson gson = GsonHelper.getBuilder().create();
@@ -356,6 +360,9 @@ private String queueCommand(BaseCmd cmdObj, Map<String, String> params) {
356360
job.setCmd(cmdObj.getClass().getName());
357361
job.setCmdInfo(gson.toJson(params));
358362
long jobId = _asyncMgr.submitAsyncJob(job);
363+
if (objectId != null) {
364+
return ((BaseAsyncCreateCmd)asyncCmd).getResponse(jobId, objectId);
365+
}
359366
return asyncCmd.getResponse(jobId);
360367
} else {
361368
_dispatcher.dispatch(cmdObj, params);

‎server/src/com/cloud/api/BaseAsyncCreateCmd.java‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
package com.cloud.api;
22

3+
import com.cloud.api.response.CreateCmdResponse;
4+
import com.cloud.serializer.SerializerHelper;
5+
36
public abstract class BaseAsyncCreateCmd extends BaseAsyncCmd {
4-
@Parameter(name="portforwardingserviceid")
7+
@Parameter(name="id")
58
private Long id;
69

710
public Long getId() {
@@ -11,4 +14,11 @@ public Long getId() {
1114
public void setId(Long id) {
1215
this.id = id;
1316
}
17+
18+
public String getResponse(long jobId, long objectId) {
19+
CreateCmdResponse response = new CreateCmdResponse();
20+
response.setJobId(jobId);
21+
response.setId(objectId);
22+
return SerializerHelper.toSerializedString(response);
23+
}
1424
}

‎server/src/com/cloud/api/BaseCmd.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,7 @@ private Map<String, Object> lowercaseParams(Map<String, String> params, boolean
223223
}
224224

225225
// FIXME: move this to a utils method so that maps can be unpacked and integer/long values can be appropriately cast
226-
@SuppressWarnings("unchecked")
226+
@SuppressWarnings({"unchecked", "rawtypes"})
227227
public Map<String, Object> unpackParams(Map<String, String> params) {
228228
Map<String, Object> lowercaseParams = new HashMap<String, Object>();
229229
for (String key : params.keySet()) {
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.cloud.api.response;
2+
3+
import com.cloud.api.ResponseObject;
4+
import com.cloud.serializer.Param;
5+
6+
public class CreateCmdResponse implements ResponseObject {
7+
@Param(name="jobid")
8+
private Long jobId;
9+
10+
@Param(name="id")
11+
private Long id;
12+
13+
public Long getJobId() {
14+
return jobId;
15+
}
16+
17+
public void setJobId(Long jobId) {
18+
this.jobId = jobId;
19+
}
20+
21+
public Long getId() {
22+
return id;
23+
}
24+
25+
public void setId(Long id) {
26+
this.id = id;
27+
}
28+
}

0 commit comments

Comments
 (0)