Skip to content

Commit 8570b25

Browse files
author
prachi
committed
NAAS: APIServer changes to introduce framework to read commands from pluggable components having separate commands.properties file
Changes: - Added a new interface 'PluggableService' - Any component that can be packaged separately from cloudstack, can implement this interface and provide its own property file listing the API commands the component supports - As an example have made VirtualNetworkApplianceService pluggable and a new configureRouter command is added - ComponentLocator reads all the pluggable service from componentLibrary or from components.xml and instantiates the services. - As an example, DefaultComponentLibrary adds the pluggable service 'VirtualNetworkApplianceService' - Also components.xml.in has an entry to show how a pluggable service can be added, but it is commented out. - APIServer now reads the commands for each pluggable service and when a command for such a service is called, APIServer sets the required instance of the pluggable service in the coomand. - To do this a new annotation '@PlugService' is added that is processed by APIServer. This eliminates the dependency on the BaseCmd to instantiate the service instances.
1 parent b2a007d commit 8570b25

15 files changed

Lines changed: 402 additions & 13 deletions

File tree

‎agent/src/com/cloud/agent/configuration/AgentComponentLibraryBase.java‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
import com.cloud.utils.component.ComponentLibraryBase;
2626
import com.cloud.utils.component.ComponentLocator.ComponentInfo;
2727
import com.cloud.utils.component.Manager;
28-
import com.cloud.utils.component.SystemIntegrityChecker;
28+
import com.cloud.utils.component.PluggableService;
2929
import com.cloud.utils.db.GenericDao;
3030

3131

@@ -63,5 +63,17 @@ protected void populateManagers() {
6363
protected void populateAdapters() {
6464

6565
}
66+
67+
protected void populateServices() {
68+
69+
}
70+
71+
@Override
72+
public Map<String, ComponentInfo<PluggableService>> getPluggableServices() {
73+
if (_pluggableServices.size() == 0) {
74+
populateServices();
75+
}
76+
return _pluggableServices;
77+
}
6678

6779
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
3+
*
4+
* This software is licensed under the GNU General Public License v3 or later.
5+
*
6+
* It is free software: you can redistribute it and/or modify
7+
* it under the terms of the GNU General Public License as published by
8+
* the Free Software Foundation, either version 3 of the License, or any later version.
9+
* This program is distributed in the hope that it will be useful,
10+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
* GNU General Public License for more details.
13+
*
14+
* You should have received a copy of the GNU General Public License
15+
* along with this program. If not, see <http://www.gnu.org/licenses/>.
16+
*
17+
*/
18+
package com.cloud.api;
19+
20+
import static java.lang.annotation.ElementType.FIELD;
21+
import static java.lang.annotation.RetentionPolicy.RUNTIME;
22+
23+
import java.lang.annotation.Retention;
24+
import java.lang.annotation.Target;
25+
26+
import com.cloud.utils.component.PluggableService;
27+
28+
@Target(FIELD)
29+
@Retention(RUNTIME)
30+
public @interface PlugService {
31+
Class<? extends PluggableService> pluggableService() default PluggableService.class;
32+
}
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
/**
2+
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
3+
*
4+
* This software is licensed under the GNU General Public License v3 or later.
5+
*
6+
* It is free software: you can redistribute it and/or modify
7+
* it under the terms of the GNU General Public License as published by
8+
* the Free Software Foundation, either version 3 of the License, or any later version.
9+
* This program is distributed in the hope that it will be useful,
10+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
* GNU General Public License for more details.
13+
*
14+
* You should have received a copy of the GNU General Public License
15+
* along with this program. If not, see <http://www.gnu.org/licenses/>.
16+
*
17+
*/
18+
19+
package com.cloud.api.commands;
20+
21+
import org.apache.log4j.Logger;
22+
23+
import com.cloud.api.ApiConstants;
24+
import com.cloud.api.BaseAsyncCmd;
25+
import com.cloud.api.BaseCmd;
26+
import com.cloud.api.Implementation;
27+
import com.cloud.api.Parameter;
28+
import com.cloud.api.PlugService;
29+
import com.cloud.api.ServerApiException;
30+
import com.cloud.api.response.DomainRouterResponse;
31+
import com.cloud.async.AsyncJob;
32+
import com.cloud.event.EventTypes;
33+
import com.cloud.exception.ConcurrentOperationException;
34+
import com.cloud.exception.InsufficientCapacityException;
35+
import com.cloud.exception.ResourceUnavailableException;
36+
import com.cloud.network.VirtualNetworkApplianceService;
37+
import com.cloud.network.router.VirtualRouter;
38+
import com.cloud.user.Account;
39+
import com.cloud.user.UserContext;
40+
41+
42+
43+
@Implementation(responseObject=DomainRouterResponse.class, description="Configures a router.")
44+
public class ConfigureRouterCmd extends BaseAsyncCmd {
45+
public static final Logger s_logger = Logger.getLogger(ConfigureRouterCmd.class.getName());
46+
private static final String s_name = "configurerouterresponse";
47+
48+
@PlugService
49+
private static VirtualNetworkApplianceService _myrouterService;
50+
51+
/////////////////////////////////////////////////////
52+
//////////////// API parameters /////////////////////
53+
/////////////////////////////////////////////////////
54+
55+
@Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the router")
56+
private Long id;
57+
58+
/////////////////////////////////////////////////////
59+
/////////////////// Accessors ///////////////////////
60+
/////////////////////////////////////////////////////
61+
62+
public Long getId() {
63+
return id;
64+
}
65+
66+
/////////////////////////////////////////////////////
67+
/////////////// API Implementation///////////////////
68+
/////////////////////////////////////////////////////
69+
70+
@Override
71+
public String getCommandName() {
72+
return s_name;
73+
}
74+
75+
public static String getResultObjectName() {
76+
return "router";
77+
}
78+
79+
@Override
80+
public long getEntityOwnerId() {
81+
VirtualRouter router = _entityMgr.findById(VirtualRouter.class, getId());
82+
if (router != null) {
83+
return router.getAccountId();
84+
}
85+
86+
return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked
87+
}
88+
89+
@Override
90+
public String getEventType() {
91+
return EventTypes.EVENT_ROUTER_START;
92+
}
93+
94+
@Override
95+
public String getEventDescription() {
96+
return "configuring router: " + getId();
97+
}
98+
99+
public AsyncJob.Type getInstanceType() {
100+
return AsyncJob.Type.DomainRouter;
101+
}
102+
103+
public Long getInstanceId() {
104+
return getId();
105+
}
106+
107+
@Override
108+
public void execute() throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException{
109+
UserContext.current().setEventDetails("Router Id: "+getId());
110+
//This should call the configure API. Calling startRouter for now.
111+
VirtualRouter result = _myrouterService.startRouter(id);
112+
if (result != null){
113+
DomainRouterResponse routerResponse = _responseGenerator.createDomainRouterResponse(result);
114+
routerResponse.setResponseName(getCommandName());
115+
this.setResponseObject(routerResponse);
116+
} else {
117+
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to start router");
118+
}
119+
}
120+
}

‎api/src/com/cloud/network/VirtualNetworkApplianceService.java‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,9 @@
2222
import com.cloud.exception.InsufficientCapacityException;
2323
import com.cloud.exception.ResourceUnavailableException;
2424
import com.cloud.network.router.VirtualRouter;
25+
import com.cloud.utils.component.PluggableService;
2526

26-
public interface VirtualNetworkApplianceService{
27+
public interface VirtualNetworkApplianceService extends PluggableService{
2728
/**
2829
* Starts domain router
2930
* @param cmd the command specifying router's id

‎client/tomcatconf/components.xml.in‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@
107107
<adapter name="ClusterBasedAgentLbPlanner" class="com.cloud.cluster.agentlb.ClusterBasedAgentLoadBalancerPlanner"/>
108108
</adapters>
109109

110+
<!-- pluggableservice name="VirtualRouterService" key="com.cloud.network.VirtualNetworkApplianceService" class="com.cloud.network.router.VirtualNetworkApplianceManagerImpl"/ -->
110111
</management-server>
111112

112113
<configuration-server class="com.cloud.server.ConfigurationServerImpl">
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
### bitmap of permissions at the end of each classname, 1 = ADMIN, 2 = RESOURCE_DOMAIN_ADMIN, 4 = DOMAIN_ADMIN, 8 = USER
2+
### Please standardize naming conventions to camel-case (even for acronyms).
3+
4+
#### router commands
5+
configureRouter=com.cloud.api.commands.ConfigureRouterCmd;7

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

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
import com.cloud.user.UserContext;
4646
import com.cloud.utils.DateUtil;
4747
import com.cloud.utils.component.ComponentLocator;
48+
import com.cloud.utils.component.PluggableService;
4849
import com.cloud.utils.exception.CloudRuntimeException;
4950

5051
/**
@@ -71,6 +72,7 @@ private ApiDispatcher() {
7172
public void dispatchCreateCmd(BaseAsyncCreateCmd cmd, Map<String, String> params) {
7273

7374
setupParameters(cmd, params);
75+
plugService(cmd);
7476

7577
try {
7678
UserContext ctx = UserContext.current();
@@ -113,6 +115,7 @@ public void dispatchCreateCmd(BaseAsyncCreateCmd cmd, Map<String, String> params
113115

114116
public void dispatch(BaseCmd cmd, Map<String, String> params) {
115117
setupParameters(cmd, params);
118+
ApiDispatcher.plugService(cmd);
116119
try {
117120
UserContext ctx = UserContext.current();
118121
ctx.setAccountId(cmd.getEntityOwnerId());
@@ -329,4 +332,44 @@ private static Date massageDate(Date date, int hourOfDay, int minute, int second
329332
cal.set(Calendar.SECOND, second);
330333
return cal.getTime();
331334
}
335+
336+
public static void plugService(BaseCmd cmd) {
337+
338+
if(!ApiServer.isPluggableServiceCommand(cmd.getClass().getName())){
339+
return;
340+
}
341+
Class<?> clazz = cmd.getClass();
342+
ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name);
343+
do {
344+
Field[] fields = clazz.getDeclaredFields();
345+
for (Field field : fields) {
346+
PlugService plugService = field.getAnnotation(PlugService.class);
347+
if (plugService == null) {
348+
continue;
349+
}
350+
Class<?> fc = field.getType();
351+
Object instance = null;
352+
if (PluggableService.class.isAssignableFrom(fc)) {
353+
instance = locator.getPluggableService(fc);
354+
}
355+
356+
if (instance == null) {
357+
throw new CloudRuntimeException("Unable to plug service " + fc.getSimpleName() + " in command " + clazz.getSimpleName());
358+
}
359+
360+
try {
361+
field.setAccessible(true);
362+
field.set(cmd, instance);
363+
} catch (IllegalArgumentException e) {
364+
s_logger.error("IllegalArgumentException at plugService for command " + cmd.getCommandName() + ", field " + field.getName());
365+
throw new CloudRuntimeException("Internal error at plugService for command " + cmd.getCommandName() + " [Illegal argumet at field " + field.getName() + "]");
366+
} catch (IllegalAccessException e) {
367+
s_logger.error("Error at plugService for command " + cmd.getCommandName() + ", field " + field.getName() + " is not accessible.");
368+
throw new CloudRuntimeException("Internal error at plugService for command " + cmd.getCommandName() + " [field " + field.getName() + " is not accessible]");
369+
}
370+
}
371+
clazz = clazz.getSuperclass();
372+
} while (clazz != Object.class && clazz != null);
373+
374+
}
332375
}

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

Lines changed: 45 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@
107107
import com.cloud.utils.Pair;
108108
import com.cloud.utils.PropertiesUtil;
109109
import com.cloud.utils.component.ComponentLocator;
110+
import com.cloud.utils.component.PluggableService;
110111
import com.cloud.utils.concurrency.NamedThreadFactory;
111112
import com.cloud.utils.db.SearchCriteria;
112113
import com.cloud.utils.db.Transaction;
@@ -138,6 +139,7 @@ public class ApiServer implements HttpRequestHandler {
138139
private static List<String> s_adminCommands = null;
139140
private static List<String> s_resourceDomainAdminCommands = null;
140141
private static List<String> s_allCommands = null;
142+
private static List<String> s_pluggableServiceCommands = null;
141143
private static final DateFormat _dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
142144

143145
private static ExecutorService _executor = new ThreadPoolExecutor(10, 150, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory("ApiServer"));
@@ -148,6 +150,7 @@ public class ApiServer implements HttpRequestHandler {
148150
s_adminCommands = new ArrayList<String>();
149151
s_resourceDomainAdminCommands = new ArrayList<String>();
150152
s_allCommands = new ArrayList<String>();
153+
s_pluggableServiceCommands = new ArrayList<String>();
151154
}
152155

153156
private ApiServer() {
@@ -168,12 +171,32 @@ public static ApiServer getInstance() {
168171
public Properties get_apiCommands() {
169172
return _apiCommands;
170173
}
174+
175+
public static boolean isPluggableServiceCommand(String cmdClassName){
176+
if(s_pluggableServiceCommands != null){
177+
if(s_pluggableServiceCommands.contains(cmdClassName)){
178+
return true;
179+
}
180+
}
181+
return false;
182+
}
171183

172-
public void init(String[] apiConfig) {
173-
try {
174-
BaseCmd.setComponents(new ApiResponseHelper());
175-
BaseListCmd.configure();
176-
_apiCommands = new Properties();
184+
private String[] getPluggableServicesApiConfigs(){
185+
List<String> pluggableServicesApiConfigs = new ArrayList<String>();
186+
187+
ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name);
188+
List<PluggableService> services = locator.getAllPluggableServices();
189+
for(PluggableService service : services){
190+
pluggableServicesApiConfigs.add(service.getPropertiesFile());
191+
}
192+
return pluggableServicesApiConfigs.toArray(new String[0]);
193+
}
194+
195+
private void processConfigFiles(String[] apiConfig, boolean pluggableServicesConfig){
196+
try{
197+
if(_apiCommands == null){
198+
_apiCommands = new Properties();
199+
}
177200
Properties preProcessedCommands = new Properties();
178201
if (apiConfig != null) {
179202
for (String configFile : apiConfig) {
@@ -184,6 +207,11 @@ public void init(String[] apiConfig) {
184207
String preProcessedCommand = preProcessedCommands.getProperty((String) key);
185208
String[] commandParts = preProcessedCommand.split(";");
186209
_apiCommands.put(key, commandParts[0]);
210+
211+
if(pluggableServicesConfig){
212+
s_pluggableServiceCommands.add(commandParts[0]);
213+
}
214+
187215
if (commandParts.length > 1) {
188216
try {
189217
short cmdPermissions = Short.parseShort(commandParts[1]);
@@ -204,7 +232,7 @@ public void init(String[] apiConfig) {
204232
}
205233
}
206234
}
207-
235+
208236
s_allCommands.addAll(s_adminCommands);
209237
s_allCommands.addAll(s_resourceDomainAdminCommands);
210238
s_allCommands.addAll(s_userCommands);
@@ -215,6 +243,16 @@ public void init(String[] apiConfig) {
215243
} catch (IOException ioex) {
216244
s_logger.error("Exception loading properties file", ioex);
217245
}
246+
}
247+
248+
public void init(String[] apiConfig) {
249+
BaseCmd.setComponents(new ApiResponseHelper());
250+
BaseListCmd.configure();
251+
processConfigFiles(apiConfig, false);
252+
253+
//get commands for all pluggable services
254+
String[] pluggableServicesApiConfigs = getPluggableServicesApiConfigs();
255+
processConfigFiles(pluggableServicesApiConfigs, true);
218256

219257
ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name);
220258
_accountMgr = locator.getManager(AccountManager.class);
@@ -400,6 +438,7 @@ private String queueCommand(BaseCmd cmdObj, Map<String, String> params) {
400438
params.put("id", objectId.toString());
401439
} else {
402440
ApiDispatcher.setupParameters(cmdObj, params);
441+
ApiDispatcher.plugService(cmdObj);
403442
}
404443

405444
BaseAsyncCmd asyncCmd = (BaseAsyncCmd) cmdObj;

0 commit comments

Comments
 (0)