Merge branch 'master' of ssh://git.cloud.com/var/lib/git/cloudstack-oss

This commit is contained in:
Sam Robertson 2012-02-03 16:59:25 -08:00
commit c358f469c0
176 changed files with 8083 additions and 7451 deletions

View File

@ -42,44 +42,58 @@ public interface SecurityChecker extends Adapter {
ModifyProject,
UseNetwork
}
/**
* Checks if the account owns the object.
*
* @param caller account to check against.
* @param object object that the account is trying to access.
* @param caller
* account to check against.
* @param object
* object that the account is trying to access.
* @return true if access allowed. false if this adapter cannot authenticate ownership.
* @throws PermissionDeniedException if this adapter is suppose to authenticate ownership and the check failed.
* @throws PermissionDeniedException
* if this adapter is suppose to authenticate ownership and the check failed.
*/
boolean checkAccess(Account caller, Domain domain) throws PermissionDeniedException;
/**
* Checks if the user belongs to an account that owns the object.
*
* @param user user to check against.
* @param object object that the account is trying to access.
* @param user
* user to check against.
* @param object
* object that the account is trying to access.
* @return true if access allowed. false if this adapter cannot authenticate ownership.
* @throws PermissionDeniedException if this adapter is suppose to authenticate ownership and the check failed.
* @throws PermissionDeniedException
* if this adapter is suppose to authenticate ownership and the check failed.
*/
boolean checkAccess(User user, Domain domain) throws PermissionDeniedException;
/**
* Checks if the account can access the object.
*
* @param caller account to check against.
* @param entity object that the account is trying to access.
* @param accessType TODO
* @param caller
* account to check against.
* @param entity
* object that the account is trying to access.
* @param accessType
* TODO
* @return true if access allowed. false if this adapter cannot provide permission.
* @throws PermissionDeniedException if this adapter is suppose to authenticate ownership and the check failed.
* @throws PermissionDeniedException
* if this adapter is suppose to authenticate ownership and the check failed.
*/
boolean checkAccess(Account caller, ControlledEntity entity, AccessType accessType) throws PermissionDeniedException;
/**
* Checks if the user belongs to an account that can access the object.
*
* @param user user to check against.
* @param entity object that the account is trying to access.
* @param user
* user to check against.
* @param entity
* object that the account is trying to access.
* @return true if access allowed. false if this adapter cannot authenticate ownership.
* @throws PermissionDeniedException if this adapter is suppose to authenticate ownership and the check failed.
* @throws PermissionDeniedException
* if this adapter is suppose to authenticate ownership and the check failed.
*/
boolean checkAccess(User user, ControlledEntity entity) throws PermissionDeniedException;

View File

@ -32,16 +32,16 @@ public abstract class BaseAsyncCmd extends BaseCmd {
public static final String ipAddressSyncObject = "ipaddress";
public static final String networkSyncObject = "network";
private AsyncJob job;
@Parameter(name="starteventid", type=CommandType.LONG)
@Parameter(name = "starteventid", type = CommandType.LONG)
private Long startEventId;
/**
* For proper tracking of async commands through the system, events must be generated when the command is
* scheduled, started, and completed. Commands should specify the type of event so that when the scheduled,
* started, and completed events are saved to the events table, they have the proper type information.
*
* @return a string representing the type of event, e.g. VM.START, VOLUME.CREATE.
*/
public abstract String getEventType();
@ -50,6 +50,7 @@ public abstract class BaseAsyncCmd extends BaseCmd {
* For proper tracking of async commands through the system, events must be generated when the command is
* scheduled, started, and completed. Commands should specify a description for these events so that when
* the scheduled, started, and completed events are saved to the events table, they have a meaningful description.
*
* @return a string representing a description of the event
*/
public abstract String getEventDescription();
@ -101,33 +102,34 @@ public abstract class BaseAsyncCmd extends BaseCmd {
return job;
}
protected long saveStartedEvent(){
return saveStartedEvent(getEventType(), "Executing job for "+getEventDescription(), getStartEventId());
protected long saveStartedEvent() {
return saveStartedEvent(getEventType(), "Executing job for " + getEventDescription(), getStartEventId());
}
protected long saveStartedEvent(String eventType, String description, Long startEventId){
protected long saveStartedEvent(String eventType, String description, Long startEventId) {
UserContext ctx = UserContext.current();
Long userId = ctx.getCallerUserId();
userId = (userId == null) ? User.UID_SYSTEM : userId;
Long startEvent = startEventId;
if(startEvent == null){
if (startEvent == null) {
startEvent = 0L;
}
return _mgr.saveStartedEvent((userId == null) ? User.UID_SYSTEM : userId, getEntityOwnerId(), eventType, description, startEvent);
}
protected long saveCompletedEvent(String level, String description){
protected long saveCompletedEvent(String level, String description) {
return saveCompletedEvent(level, getEventType(), description, getStartEventId());
}
protected long saveCompletedEvent(String level, String eventType, String description, Long startEventId){
protected long saveCompletedEvent(String level, String eventType, String description, Long startEventId) {
UserContext ctx = UserContext.current();
Long userId = ctx.getCallerUserId();
userId = (userId == null) ? User.UID_SYSTEM : userId;
Long startEvent = startEventId;
if(startEvent == null){
if (startEvent == null) {
startEvent = 0L;
}
return _mgr.saveCompletedEvent((userId == null) ? User.UID_SYSTEM : userId, getEntityOwnerId(), level, eventType, description, startEvent);
}
}

View File

@ -22,7 +22,7 @@ import com.cloud.api.response.CreateCmdResponse;
import com.cloud.exception.ResourceAllocationException;
public abstract class BaseAsyncCreateCmd extends BaseAsyncCmd {
@Parameter(name="id", type=CommandType.LONG)
@Parameter(name = "id", type = CommandType.LONG)
private Long id;
public abstract void create() throws ResourceAllocationException;
@ -53,4 +53,5 @@ public abstract class BaseAsyncCreateCmd extends BaseAsyncCmd {
public String getCreateEventDescription() {
return null;
}
}

View File

@ -28,7 +28,6 @@ import java.util.regex.Pattern;
import org.apache.log4j.Logger;
import com.cloud.api.response.TrafficTypeImplementorResponse;
import com.cloud.configuration.ConfigurationService;
import com.cloud.consoleproxy.ConsoleProxyService;
import com.cloud.dao.EntityManager;
@ -87,7 +86,7 @@ public abstract class BaseCmd {
// Server error codes
public static final int INTERNAL_ERROR = 530;
public static final int ACCOUNT_ERROR = 531;
public static final int ACCOUNT_RESOURCE_LIMIT_ERROR= 532;
public static final int ACCOUNT_RESOURCE_LIMIT_ERROR = 532;
public static final int INSUFFICIENT_CAPACITY_ERROR = 533;
public static final int RESOURCE_UNAVAILABLE_ERROR = 534;
public static final int RESOURCE_ALLOCATION_ERROR = 534;
@ -102,7 +101,7 @@ public abstract class BaseCmd {
private Object _responseObject = null;
private Map<String, String> fullUrlParams;
@Parameter(name="response", type=CommandType.STRING)
@Parameter(name = "response", type = CommandType.STRING)
private String responseType;
public static ComponentLocator s_locator;
@ -133,7 +132,7 @@ public abstract class BaseCmd {
static void setComponents(ResponseGenerator generator) {
ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name);
_mgr = (ManagementService)ComponentLocator.getComponent(ManagementService.Name);
_mgr = (ManagementService) ComponentLocator.getComponent(ManagementService.Name);
_accountService = locator.getManager(AccountService.class);
_configService = locator.getManager(ConfigurationService.class);
_userVmService = locator.getManager(UserVmService.class);
@ -177,6 +176,7 @@ public abstract class BaseCmd {
/**
* For commands the API framework needs to know the owner of the object being acted upon. This method is
* used to determine that information.
*
* @return the id of the account that owns the object being acted upon
*/
public abstract long getEntityOwnerId();
@ -194,21 +194,22 @@ public abstract class BaseCmd {
return "";
}
String formattedString = null;
synchronized(_outputFormat) {
synchronized (_outputFormat) {
formattedString = _outputFormat.format(date);
}
return formattedString;
}
// FIXME: move this to a utils method so that maps can be unpacked and integer/long values can be appropriately cast
@SuppressWarnings({"unchecked", "rawtypes"})
@SuppressWarnings({ "unchecked", "rawtypes" })
public Map<String, Object> unpackParams(Map<String, String> params) {
Map<String, Object> lowercaseParams = new HashMap<String, Object>();
for (String key : params.keySet()) {
int arrayStartIndex = key.indexOf('[');
int arrayStartLastIndex = key.lastIndexOf('[');
if (arrayStartIndex != arrayStartLastIndex) {
throw new ServerApiException(MALFORMED_PARAMETER_ERROR, "Unable to decode parameter " + key + "; if specifying an object array, please use parameter[index].field=XXX, e.g. userGroupList[0].group=httpGroup");
throw new ServerApiException(MALFORMED_PARAMETER_ERROR, "Unable to decode parameter " + key
+ "; if specifying an object array, please use parameter[index].field=XXX, e.g. userGroupList[0].group=httpGroup");
}
if (arrayStartIndex > 0) {
@ -216,14 +217,16 @@ public abstract class BaseCmd {
int arrayEndLastIndex = key.lastIndexOf(']');
if ((arrayEndIndex < arrayStartIndex) || (arrayEndIndex != arrayEndLastIndex)) {
// malformed parameter
throw new ServerApiException(MALFORMED_PARAMETER_ERROR, "Unable to decode parameter " + key + "; if specifying an object array, please use parameter[index].field=XXX, e.g. userGroupList[0].group=httpGroup");
throw new ServerApiException(MALFORMED_PARAMETER_ERROR, "Unable to decode parameter " + key
+ "; if specifying an object array, please use parameter[index].field=XXX, e.g. userGroupList[0].group=httpGroup");
}
// Now that we have an array object, check for a field name in the case of a complex object
int fieldIndex = key.indexOf('.');
String fieldName = null;
if (fieldIndex < arrayEndIndex) {
throw new ServerApiException(MALFORMED_PARAMETER_ERROR, "Unable to decode parameter " + key + "; if specifying an object array, please use parameter[index].field=XXX, e.g. userGroupList[0].group=httpGroup");
throw new ServerApiException(MALFORMED_PARAMETER_ERROR, "Unable to decode parameter " + key
+ "; if specifying an object array, please use parameter[index].field=XXX, e.g. userGroupList[0].group=httpGroup");
} else {
fieldName = key.substring(fieldIndex + 1);
}
@ -234,7 +237,7 @@ public abstract class BaseCmd {
Map<Integer, Map> mapArray = null;
Map<String, Object> mapValue = null;
String indexStr = key.substring(arrayStartIndex+1, arrayEndIndex);
String indexStr = key.substring(arrayStartIndex + 1, arrayEndIndex);
int index = 0;
boolean parsedIndex = false;
try {
@ -247,7 +250,8 @@ public abstract class BaseCmd {
}
if (!parsedIndex) {
throw new ServerApiException(MALFORMED_PARAMETER_ERROR, "Unable to decode parameter " + key + "; if specifying an object array, please use parameter[index].field=XXX, e.g. userGroupList[0].group=httpGroup");
throw new ServerApiException(MALFORMED_PARAMETER_ERROR, "Unable to decode parameter " + key
+ "; if specifying an object array, please use parameter[index].field=XXX, e.g. userGroupList[0].group=httpGroup");
}
Object value = lowercaseParams.get(paramName);
@ -257,7 +261,7 @@ public abstract class BaseCmd {
mapValue = new HashMap<String, Object>();
mapArray.put(Integer.valueOf(index), mapValue);
} else if (value instanceof Map) {
mapArray = (HashMap)value;
mapArray = (HashMap) value;
mapValue = mapArray.get(Integer.valueOf(index));
if (mapValue == null) {
mapValue = new HashMap<String, Object>();
@ -280,14 +284,14 @@ public abstract class BaseCmd {
StringBuffer sb = new StringBuffer();
if (RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
// JSON response
sb.append("{ \"" + getCommandName() + "\" : { " + "\"@attributes\":{\"cloud-stack-version\":\""+_mgr.getVersion()+"\"},");
sb.append("{ \"" + getCommandName() + "\" : { " + "\"@attributes\":{\"cloud-stack-version\":\"" + _mgr.getVersion() + "\"},");
sb.append("\"errorcode\" : \"" + apiException.getErrorCode() + "\", \"description\" : \"" + apiException.getDescription() + "\" } }");
} else {
sb.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
sb.append("<" + getCommandName() + ">");
sb.append("<errorcode>" + apiException.getErrorCode() + "</errorcode>");
sb.append("<description>" + escapeXml(apiException.getDescription()) + "</description>");
sb.append("</" + getCommandName() + " cloud-stack-version=\""+_mgr.getVersion()+ "\">");
sb.append("</" + getCommandName() + " cloud-stack-version=\"" + _mgr.getVersion() + "\">");
}
return sb.toString();
}
@ -298,10 +302,10 @@ public abstract class BaseCmd {
// set up the return value with the name of the response
if (RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
prefixSb.append("{ \"" + getCommandName() + "\" : { \"@attributes\":{\"cloud-stack-version\":\""+ _mgr.getVersion()+"\"},");
prefixSb.append("{ \"" + getCommandName() + "\" : { \"@attributes\":{\"cloud-stack-version\":\"" + _mgr.getVersion() + "\"},");
} else {
prefixSb.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
prefixSb.append("<" + getCommandName() + " cloud-stack-version=\""+_mgr.getVersion()+ "\">");
prefixSb.append("<" + getCommandName() + " cloud-stack-version=\"" + _mgr.getVersion() + "\">");
}
int i = 0;
@ -309,7 +313,7 @@ public abstract class BaseCmd {
String tagName = tagData.first();
Object tagValue = tagData.second();
if (tagValue instanceof Object[]) {
Object[] subObjects = (Object[])tagValue;
Object[] subObjects = (Object[]) tagValue;
if (subObjects.length < 1) {
continue;
}
@ -319,8 +323,9 @@ public abstract class BaseCmd {
}
}
if(suffixSb.length() > 0){
if (RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)){ // append comma only if we have some suffix else not as per strict Json syntax.
if (suffixSb.length() > 0) {
if (RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) { // append comma only if we have some suffix else
// not as per strict Json syntax.
prefixSb.append(",");
}
prefixSb.append(suffixSb);
@ -340,7 +345,7 @@ public abstract class BaseCmd {
}
if (tagValue instanceof Object[]) {
Object[] subObjects = (Object[])tagValue;
Object[] subObjects = (Object[]) tagValue;
if (subObjects.length < 1) {
return;
}
@ -364,7 +369,7 @@ public abstract class BaseCmd {
int j = 0;
for (Object subObject : subObjects) {
if (subObject instanceof List) {
List subObjList = (List)subObject;
List subObjList = (List) subObject;
writeSubObject(sb, tagName, subObjList, responseType, j++);
}
}
@ -385,8 +390,8 @@ public abstract class BaseCmd {
int i = 0;
for (Object tag : tagList) {
if (tag instanceof Pair) {
Pair nameValuePair = (Pair)tag;
writeNameValuePair(sb, (String)nameValuePair.first(), nameValuePair.second(), responseType, i++);
Pair nameValuePair = (Pair) tag;
writeNameValuePair(sb, (String) nameValuePair.first(), nameValuePair.second(), responseType, i++);
}
}
@ -404,8 +409,8 @@ public abstract class BaseCmd {
return true;
}
private String escapeXml(String xml){
if(!requireXmlEscape()){
private String escapeXml(String xml) {
if (!requireXmlEscape()) {
return xml;
}
int iLen = xml.length();
@ -449,8 +454,7 @@ public abstract class BaseCmd {
public static boolean isAdmin(short accountType) {
return ((accountType == Account.ACCOUNT_TYPE_ADMIN) ||
(accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) ||
(accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) ||
(accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN));
(accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN));
}
public static boolean isRootAdmin(short accountType) {

View File

@ -18,12 +18,11 @@
package com.cloud.api;
public abstract class BaseListAccountResourcesCmd extends BaseListDomainResourcesCmd{
public abstract class BaseListAccountResourcesCmd extends BaseListDomainResourcesCmd {
@Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="List resources by account. Must be used with the domainId parameter.")
@Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "List resources by account. Must be used with the domainId parameter.")
private String accountName;
public String getAccountName() {
return accountName;
}

View File

@ -40,8 +40,6 @@ public abstract class BaseListCmd extends BaseCmd {
@Parameter(name = ApiConstants.PAGE_SIZE, type = CommandType.INTEGER)
private Integer pageSize;
// ///////////////////////////////////////////////////
// ///////////////// Accessors ///////////////////////
// ///////////////////////////////////////////////////

View File

@ -18,16 +18,16 @@
package com.cloud.api;
public abstract class BaseListDomainResourcesCmd extends BaseListCmd{
public abstract class BaseListDomainResourcesCmd extends BaseListCmd {
@Parameter(name=ApiConstants.LIST_ALL, type=CommandType.BOOLEAN, description="If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false")
@Parameter(name = ApiConstants.LIST_ALL, type = CommandType.BOOLEAN, description = "If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false")
private Boolean listAll;
@IdentityMapper(entityTableName="domain")
@Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="list only resources belonging to the domain specified")
@IdentityMapper(entityTableName = "domain")
@Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.LONG, description = "list only resources belonging to the domain specified")
private Long domainId;
@Parameter(name=ApiConstants.IS_RECURSIVE, type=CommandType.BOOLEAN, description="defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.")
@Parameter(name = ApiConstants.IS_RECURSIVE, type = CommandType.BOOLEAN, description = "defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.")
private Boolean recursive;
public boolean listAll() {

View File

@ -18,10 +18,10 @@
package com.cloud.api;
public abstract class BaseListProjectAndAccountResourcesCmd extends BaseListAccountResourcesCmd{
public abstract class BaseListProjectAndAccountResourcesCmd extends BaseListAccountResourcesCmd {
@IdentityMapper(entityTableName="projects")
@Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="list firewall rules by project")
@IdentityMapper(entityTableName = "projects")
@Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.LONG, description = "list firewall rules by project")
private Long projectId;
public Long getProjectId() {

View File

@ -24,7 +24,7 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({FIELD})
@Target({ FIELD })
public @interface IdentityMapper {
String entityTableName();
}

View File

@ -44,4 +44,3 @@ public class IdentityProxy {
_value = value;
}
}

View File

@ -19,6 +19,8 @@ package com.cloud.api;
public interface IdentityService {
Long getIdentityId(IdentityMapper mapper, String identityString);
Long getIdentityId(String tableName, String identityString);
String getIdentityUuid(String tableName, String identityString);
}

View File

@ -25,11 +25,15 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE})
@Target({ TYPE })
public @interface Implementation {
Class<?> responseObject();
String description() default "";
String usage() default "";
boolean includeInApiDoc() default true;
String since() default "";
}

View File

@ -27,16 +27,23 @@ import java.lang.annotation.Target;
import com.cloud.api.BaseCmd.CommandType;
@Retention(RetentionPolicy.RUNTIME)
@Target({FIELD})
@Target({ FIELD })
public @interface Parameter {
String name() default "";
String description() default "";
boolean required() default false;
CommandType type() default CommandType.OBJECT;
CommandType collectionType() default CommandType.OBJECT;
boolean expose() default true;
boolean includeInApiDoc() default true;
int length() default 255;
String since() default "";
}

View File

@ -43,11 +43,9 @@ import com.cloud.api.response.IPAddressResponse;
import com.cloud.api.response.InstanceGroupResponse;
import com.cloud.api.response.IpForwardingRuleResponse;
import com.cloud.api.response.LBStickinessResponse;
import com.cloud.api.response.LDAPConfigResponse;
import com.cloud.api.response.ListResponse;
import com.cloud.api.response.LoadBalancerResponse;
import com.cloud.api.response.LBStickinessPolicyResponse;
import com.cloud.network.rules.StickinessPolicy;
import com.cloud.api.response.LDAPConfigResponse;
import com.cloud.api.response.NetworkOfferingResponse;
import com.cloud.api.response.NetworkResponse;
import com.cloud.api.response.PhysicalNetworkResponse;
@ -106,9 +104,10 @@ import com.cloud.network.rules.FirewallRule;
import com.cloud.network.rules.LoadBalancer;
import com.cloud.network.rules.PortForwardingRule;
import com.cloud.network.rules.StaticNatRule;
import com.cloud.network.security.SecurityRule;
import com.cloud.network.rules.StickinessPolicy;
import com.cloud.network.security.SecurityGroup;
import com.cloud.network.security.SecurityGroupRules;
import com.cloud.network.security.SecurityRule;
import com.cloud.offering.DiskOffering;
import com.cloud.offering.NetworkOffering;
import com.cloud.offering.ServiceOffering;
@ -170,7 +169,7 @@ public interface ResponseGenerator {
LBStickinessResponse createLBStickinessPolicyResponse(List<? extends StickinessPolicy> stickinessPolicies, LoadBalancer lb);
LBStickinessResponse createLBStickinessPolicyResponse( StickinessPolicy stickinessPolicy, LoadBalancer lb);
LBStickinessResponse createLBStickinessPolicyResponse(StickinessPolicy stickinessPolicy, LoadBalancer lb);
PodResponse createPodResponse(Pod pod, Boolean showCapacities);
@ -205,6 +204,7 @@ public interface ResponseGenerator {
VpnUsersResponse createVpnUserResponse(VpnUser user);
RemoteAccessVpnResponse createRemoteAccessVpnResponse(RemoteAccessVpn vpn);
List<TemplateResponse> createTemplateResponses(long templateId, Long zoneId, boolean readyOnly);
List<TemplateResponse> createTemplateResponses(long templateId, Long snapshotId, Long volumeId, boolean readyOnly);

View File

@ -21,24 +21,28 @@ package com.cloud.api;
public interface ResponseObject {
/**
* Get the name of the API response
*
* @return the name of the API response
*/
String getResponseName();
/**
* Set the name of the API response
*
* @param name
*/
void setResponseName(String name);
/**
* Get the name of the API object
*
* @return the name of the API object
*/
String getObjectName();
/**
* Set the name of the APIobject
*
* @param name
*/
void setObjectName(String name);
@ -50,18 +54,21 @@ public interface ResponseObject {
/**
* Returns the job id
*
* @return
*/
Long getJobId();
/**
* Sets the job id
*
* @param jobId
*/
void setJobId(Long jobId);
/**
* Returns the job status
*
* @return
*/
Integer getJobStatus();

View File

@ -36,6 +36,7 @@ public class ServerApiException extends RuntimeException {
public int getErrorCode() {
return _errorCode;
}
public void setErrorCode(int errorCode) {
_errorCode = errorCode;
}
@ -43,6 +44,7 @@ public class ServerApiException extends RuntimeException {
public String getDescription() {
return _description;
}
public void setDescription(String description) {
_description = description;
}

View File

@ -1,4 +1,5 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
@ -25,43 +26,41 @@ import com.cloud.api.IdentityMapper;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.api.BaseCmd.CommandType;
import com.cloud.api.response.SecurityGroupResponse;
import com.cloud.network.security.SecurityGroup;
import com.cloud.user.Account;
import com.cloud.user.UserContext;
@Implementation(responseObject=SecurityGroupResponse.class, description="Creates a security group")
@Implementation(responseObject = SecurityGroupResponse.class, description = "Creates a security group")
public class CreateSecurityGroupCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(CreateSecurityGroupCmd.class.getName());
private static final String s_name = "createsecuritygroupresponse";
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
/////////////////////////////////////////////////////
// ///////////////////////////////////////////////////
// ////////////// API parameters /////////////////////
// ///////////////////////////////////////////////////
@Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for the security group. Must be used with domainId.")
@Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "an optional account for the security group. Must be used with domainId.")
private String accountName;
@IdentityMapper(entityTableName="domain")
@Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId for the security group. If the account parameter is used, domainId must also be used.")
@IdentityMapper(entityTableName = "domain")
@Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.LONG, description = "an optional domainId for the security group. If the account parameter is used, domainId must also be used.")
private Long domainId;
@Parameter(name=ApiConstants.DESCRIPTION, type=CommandType.STRING, description="the description of the security group")
@Parameter(name = ApiConstants.DESCRIPTION, type = CommandType.STRING, description = "the description of the security group")
private String description;
@Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="name of the security group")
@Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true, description = "name of the security group")
private String securityGroupName;
@IdentityMapper(entityTableName="projects")
@Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="Deploy vm for the project")
@IdentityMapper(entityTableName = "projects")
@Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.LONG, description = "Deploy vm for the project")
private Long projectId;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
// ///////////////////////////////////////////////////
// ///////////////// Accessors ///////////////////////
// ///////////////////////////////////////////////////
public String getAccountName() {
return accountName;
@ -83,10 +82,9 @@ public class CreateSecurityGroupCmd extends BaseCmd {
return projectId;
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
// ///////////////////////////////////////////////////
// ///////////// API Implementation///////////////////
// ///////////////////////////////////////////////////
@Override
public String getCommandName() {
@ -109,11 +107,12 @@ public class CreateSecurityGroupCmd extends BaseCmd {
return account.getId();
}
return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked
return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are
// tracked
}
@Override
public void execute(){
public void execute() {
SecurityGroup group = _securityGroupService.createSecurityGroup(this);
if (group != null) {
SecurityGroupResponse response = _responseGenerator.createSecurityGroupResponse(group);

View File

@ -29,33 +29,33 @@ import com.cloud.api.response.InstanceGroupResponse;
import com.cloud.user.UserContext;
import com.cloud.vm.InstanceGroup;
@Implementation(description="Creates a vm group", responseObject=InstanceGroupResponse.class)
public class CreateVMGroupCmd extends BaseCmd{
@Implementation(description = "Creates a vm group", responseObject = InstanceGroupResponse.class)
public class CreateVMGroupCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(CreateVMGroupCmd.class.getName());
private static final String s_name = "createinstancegroupresponse";
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
/////////////////////////////////////////////////////
// ///////////////////////////////////////////////////
// ////////////// API parameters /////////////////////
// ///////////////////////////////////////////////////
@Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the instance group")
@Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true, description = "the name of the instance group")
private String groupName;
@Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="the account of the instance group. The account parameter must be used with the domainId parameter.")
@Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "the account of the instance group. The account parameter must be used with the domainId parameter.")
private String accountName;
@IdentityMapper(entityTableName="domain")
@Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the domain ID of account owning the instance group")
@IdentityMapper(entityTableName = "domain")
@Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.LONG, description = "the domain ID of account owning the instance group")
private Long domainId;
@IdentityMapper(entityTableName="projects")
@Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="The project of the instance group")
@IdentityMapper(entityTableName = "projects")
@Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.LONG, description = "The project of the instance group")
private Long projectId;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
// ///////////////////////////////////////////////////
// ///////////////// Accessors ///////////////////////
// ///////////////////////////////////////////////////
public String getGroupName() {
return groupName;
@ -73,9 +73,9 @@ public class CreateVMGroupCmd extends BaseCmd{
return projectId;
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
// ///////////////////////////////////////////////////
// ///////////// API Implementation///////////////////
// ///////////////////////////////////////////////////
@Override
public String getCommandName() {
@ -93,7 +93,7 @@ public class CreateVMGroupCmd extends BaseCmd{
}
@Override
public void execute(){
public void execute() {
InstanceGroup result = _userVmService.createVmGroup(this);
if (result != null) {
InstanceGroupResponse response = _responseGenerator.createInstanceGroupResponse(result);

View File

@ -21,7 +21,7 @@ import java.util.Date;
import com.cloud.api.Identity;
public interface AsyncJob extends Identity{
public interface AsyncJob extends Identity {
public enum Type {
None,
VirtualMachine,
@ -40,27 +40,50 @@ public interface AsyncJob extends Identity{
}
Long getId();
long getUserId();
long getAccountId();
String getCmd();
int getCmdVersion();
String getCmdInfo();
int getCallbackType();
String getCallbackAddress();
int getStatus();
int getProcessStatus();
int getResultCode();
String getResult();
Long getInitMsid();
Long getCompleteMsid();
Date getCreated();
Date getLastUpdated();
Date getLastPolled();
Date getRemoved();
Type getInstanceType();
Long getInstanceId();
String getSessionKey();
String getCmdOriginator();
boolean isFromPreviousSession();
SyncQueueItem getSyncSource();
}

View File

@ -21,6 +21,6 @@ package com.cloud.async;
public interface SyncQueueItem {
String getContentType();
Long getContentId();
Long getContentId();
}

View File

@ -36,14 +36,19 @@ public interface Capacity {
public long getId();
public Long getHostOrPoolId();
public long getDataCenterId();
public Long getPodId();
public Long getClusterId();
public long getUsedCapacity();
public long getTotalCapacity();
public short getCapacityType();
long getReservedCapacity();
}

View File

@ -16,18 +16,17 @@
*
*/
package com.cloud.cluster;
public interface ManagementServerHost {
public static enum State { Up, Starting, Down };
public static enum State {
Up, Starting, Down
};
long getMsid();
State getState();
String getVersion();
}

View File

@ -18,8 +18,7 @@
package com.cloud.configuration;
public interface Configuration{
public interface Configuration {
public String getCategory();
@ -33,5 +32,4 @@ public interface Configuration{
public String getDescription();
}

View File

@ -68,7 +68,8 @@ public interface ConfigurationService {
* Create a service offering through the API
*
* @param cmd
* the command object that specifies the name, number of cpu cores, amount of RAM, etc. for the service offering
* the command object that specifies the name, number of cpu cores, amount of RAM, etc. for the service
* offering
* @return the newly created service offering if successful, null otherwise
*/
ServiceOffering createServiceOffering(CreateServiceOfferingCmd cmd);
@ -130,13 +131,21 @@ public interface ConfigurationService {
/**
* Creates a new pod based on the parameters specified in the command object
* @param zoneId TODO
* @param name TODO
* @param startIp TODO
* @param endIp TODO
* @param gateway TODO
* @param netmask TODO
* @param allocationState TODO
*
* @param zoneId
* TODO
* @param name
* TODO
* @param startIp
* TODO
* @param endIp
* TODO
* @param gateway
* TODO
* @param netmask
* TODO
* @param allocationState
* TODO
* @return the new pod if successful, null otherwise
* @throws
* @throws
@ -188,12 +197,14 @@ public interface ConfigurationService {
boolean deleteZone(DeleteZoneCmd cmd);
/**
* Adds a VLAN to the database, along with an IP address range. Can add three types of VLANs: (1) zone-wide VLANs on the
* Adds a VLAN to the database, along with an IP address range. Can add three types of VLANs: (1) zone-wide VLANs on
* the
* virtual public network (2) pod-wide direct attached VLANs (3) account-specific direct attached VLANs
*
* @param userId
* @param vlanType
* - either "DomR" (VLAN for a virtual public network) or "DirectAttached" (VLAN for IPs that will be directly
* - either "DomR" (VLAN for a virtual public network) or "DirectAttached" (VLAN for IPs that will be
* directly
* attached to UserVMs)
* @param zoneId
* @param accountId

View File

@ -21,13 +21,13 @@ public interface Resource {
public static final short RESOURCE_UNLIMITED = -1;
public enum ResourceType{
user_vm ("user_vm", 0, ResourceOwnerType.Account, ResourceOwnerType.Domain),
public_ip ("public_ip", 1, ResourceOwnerType.Account, ResourceOwnerType.Domain),
volume ("volume", 2, ResourceOwnerType.Account, ResourceOwnerType.Domain),
snapshot ("snapshot", 3, ResourceOwnerType.Account, ResourceOwnerType.Domain),
template ("template", 4, ResourceOwnerType.Account, ResourceOwnerType.Domain),
project ("project", 5, ResourceOwnerType.Account, ResourceOwnerType.Domain);
public enum ResourceType {
user_vm("user_vm", 0, ResourceOwnerType.Account, ResourceOwnerType.Domain),
public_ip("public_ip", 1, ResourceOwnerType.Account, ResourceOwnerType.Domain),
volume("volume", 2, ResourceOwnerType.Account, ResourceOwnerType.Domain),
snapshot("snapshot", 3, ResourceOwnerType.Account, ResourceOwnerType.Domain),
template("template", 4, ResourceOwnerType.Account, ResourceOwnerType.Domain),
project("project", 5, ResourceOwnerType.Account, ResourceOwnerType.Domain);
private String name;
private ResourceOwnerType[] supportedOwners;
@ -51,7 +51,7 @@ public interface Resource {
boolean success = false;
if (supportedOwners != null) {
int length = supportedOwners.length;
for (int i = 0; i< length; i++) {
for (int i = 0; i < length; i++) {
if (supportedOwners[i].getName().equalsIgnoreCase(ownerType.getName())) {
success = true;
break;

View File

@ -18,7 +18,7 @@
package com.cloud.configuration;
public interface ResourceCount extends Resource{
public interface ResourceCount extends Resource {
public Long getId();

View File

@ -18,7 +18,7 @@
package com.cloud.configuration;
public interface ResourceLimit extends Resource{
public interface ResourceLimit extends Resource {
public Long getId();

View File

@ -72,3 +72,4 @@ public interface EntityManager {
public <T, K extends Serializable> void remove(Class<T> entityType, K id);
}

View File

@ -34,28 +34,49 @@ public interface DataCenter extends Grouping {
Basic,
Advanced,
}
long getId();
String getDns1();
String getDns2();
String getName();
Long getDomainId();
String getDescription();
String getDomain();
NetworkType getNetworkType();
String getInternalDns1();
String getInternalDns2();
String getDnsProvider();
String getGatewayProvider();
String getFirewallProvider();
String getDhcpProvider();
String getLoadBalancerProvider();
String getUserDataProvider();
String getVpnProvider();
boolean isSecurityGroupEnabled();
Map<String, String> getDetails();
void setDetails(Map<String, String> details);
AllocationState getAllocationState();
String getZoneToken();
}

View File

@ -22,7 +22,6 @@
package com.cloud.dc;
import com.cloud.org.Grouping;
import com.cloud.org.Grouping.AllocationState;
/**
* Represents one pod in the cloud stack.
@ -42,7 +41,7 @@ public interface Pod extends Grouping {
long getDataCenterId();
//String getUniqueName();
// String getUniqueName();
String getDescription();

View File

@ -58,7 +58,7 @@ public class DataCenterDeployment implements DeploymentPlan {
}
@Override
public Long getHostId(){
public Long getHostId() {
return _hostId;
}

View File

@ -66,7 +66,7 @@ public class DeployDestination {
}
public DeployDestination(DataCenter dc, Pod pod, Cluster cluster, Host host, Map<Volume, StoragePool> storage) {
this(dc,pod,cluster,host);
this(dc, pod, cluster, host);
_storage = storage;
}
@ -80,7 +80,7 @@ public class DeployDestination {
@Override
public boolean equals(Object obj) {
DeployDestination that = (DeployDestination)obj;
DeployDestination that = (DeployDestination) obj;
if (this._dc == null || that._dc == null) {
return false;
}
@ -135,13 +135,13 @@ public class DeployDestination {
destination.append("Cluster(").append(clusterId).append(")").append("-");
destination.append("Host(").append(hostId).append(")").append("-");
destination.append("Storage(");
if(_storage != null){
if (_storage != null) {
String storageStr = "";
for(Volume vol : _storage.keySet()){
if(!storageStr.equals("")){
for (Volume vol : _storage.keySet()) {
if (!storageStr.equals("")) {
storageStr = storageStr + ", ";
}
storageStr = storageStr + "Volume(" + vol.getId() + "|"+ vol.getVolumeType().name() + "-->Pool("+_storage.get(vol).getId()+")";
storageStr = storageStr + "Volume(" + vol.getId() + "|" + vol.getVolumeType().name() + "-->Pool(" + _storage.get(vol).getId() + ")";
}
destination.append(storageStr);
}

View File

@ -43,9 +43,12 @@ public interface DeploymentPlanner extends Adapter {
/**
* plan is called to determine where a virtual machine should be running.
*
* @param vm virtual machine.
* @param plan deployment plan that tells you where it's being deployed to.
* @param avoid avoid these data centers, pods, clusters, or hosts.
* @param vm
* virtual machine.
* @param plan
* deployment plan that tells you where it's being deployed to.
* @param avoid
* avoid these data centers, pods, clusters, or hosts.
* @return DeployDestination for that virtual machine.
*/
DeployDestination plan(VirtualMachineProfile<? extends VirtualMachine> vm, DeploymentPlan plan, ExcludeList avoid) throws InsufficientServerCapacityException;
@ -54,21 +57,30 @@ public interface DeploymentPlanner extends Adapter {
* check() is called right before the virtual machine starts to make sure
* the host has enough capacity.
*
* @param vm virtual machine in question.
* @param plan deployment plan used to determined the deploy destination.
* @param dest destination returned by plan.
* @param avoid what to avoid.
* @return true if it's okay to start; false if not. If false, the exclude list will include what should be excluded.
* @param vm
* virtual machine in question.
* @param plan
* deployment plan used to determined the deploy destination.
* @param dest
* destination returned by plan.
* @param avoid
* what to avoid.
* @return true if it's okay to start; false if not. If false, the exclude list will include what should be
* excluded.
*/
boolean check(VirtualMachineProfile<? extends VirtualMachine> vm, DeploymentPlan plan, DeployDestination dest, ExcludeList exclude);
/**
* canHandle is called before plan to determine if the plan can do the allocation. Planers should be exclusive so planner writer must
* canHandle is called before plan to determine if the plan can do the allocation. Planers should be exclusive so
* planner writer must
* make sure only one planer->canHandle return true in the planner list
*
* @param vm virtual machine.
* @param plan deployment plan that tells you where it's being deployed to.
* @param avoid avoid these data centers, pods, clusters, or hosts.
* @param vm
* virtual machine.
* @param plan
* deployment plan that tells you where it's being deployed to.
* @param avoid
* avoid these data centers, pods, clusters, or hosts.
* @return true if it's okay to allocate; false or not
*/
boolean canHandle(VirtualMachineProfile<? extends VirtualMachine> vm, DeploymentPlan plan, ExcludeList avoid);
@ -87,10 +99,10 @@ public interface DeploymentPlanner extends Adapter {
private Set<Long> _hostIds;
private Set<Long> _poolIds;
public ExcludeList(){
public ExcludeList() {
}
public ExcludeList(Set<Long> _dcIds, Set<Long> _podIds, Set<Long> _clusterIds, Set<Long> _hostIds, Set<Long> _poolIds){
public ExcludeList(Set<Long> _dcIds, Set<Long> _podIds, Set<Long> _clusterIds, Set<Long> _hostIds, Set<Long> _poolIds) {
this._dcIds = _dcIds;
this._podIds = _podIds;
this._clusterIds = _clusterIds;
@ -254,23 +266,23 @@ public interface DeploymentPlanner extends Adapter {
return false;
}
public Set<Long> getDataCentersToAvoid(){
public Set<Long> getDataCentersToAvoid() {
return _dcIds;
}
public Set<Long> getPodsToAvoid(){
public Set<Long> getPodsToAvoid() {
return _podIds;
}
public Set<Long> getClustersToAvoid(){
public Set<Long> getClustersToAvoid() {
return _clusterIds;
}
public Set<Long> getHostsToAvoid(){
public Set<Long> getHostsToAvoid() {
return _hostIds;
}
public Set<Long> getPoolsToAvoid(){
public Set<Long> getPoolsToAvoid() {
return _poolIds;
}
}

View File

@ -31,7 +31,9 @@ import com.cloud.user.OwnedBy;
public interface Domain extends OwnedBy {
public static final long ROOT_DOMAIN = 1L;
enum State {Active, Inactive};
enum State {
Active, Inactive
};
long getId();

View File

@ -24,11 +24,14 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Target({TYPE, METHOD})
@Target({ TYPE, METHOD })
@Retention(RUNTIME)
public @interface ActionEvent {
boolean create() default false;
boolean async() default false;
String eventType();
String eventDescription();
}

View File

@ -89,7 +89,7 @@ public class EventTypes {
public static final String EVENT_USER_ENABLE = "USER.ENABLE";
public static final String EVENT_USER_LOCK = "USER.LOCK";
//Template Events
// Template Events
public static final String EVENT_TEMPLATE_CREATE = "TEMPLATE.CREATE";
public static final String EVENT_TEMPLATE_DELETE = "TEMPLATE.DELETE";
public static final String EVENT_TEMPLATE_UPDATE = "TEMPLATE.UPDATE";
@ -131,7 +131,7 @@ public class EventTypes {
public static final String EVENT_ISO_EXTRACT = "ISO.EXTRACT";
public static final String EVENT_ISO_UPLOAD = "ISO.UPLOAD";
//SSVM
// SSVM
public static final String EVENT_SSVM_CREATE = "SSVM.CREATE";
public static final String EVENT_SSVM_DESTROY = "SSVM.DESTROY";
public static final String EVENT_SSVM_START = "SSVM.START";
@ -149,7 +149,7 @@ public class EventTypes {
public static final String EVENT_DISK_OFFERING_EDIT = "DISK.OFFERING.EDIT";
public static final String EVENT_DISK_OFFERING_DELETE = "DISK.OFFERING.DELETE";
//Network offerings
// Network offerings
public static final String EVENT_NETWORK_OFFERING_CREATE = "NETWORK.OFFERING.CREATE";
public static final String EVENT_NETWORK_OFFERING_ASSIGN = "NETWORK.OFFERING.ASSIGN";
public static final String EVENT_NETWORK_OFFERING_EDIT = "NETWORK.OFFERING.EDIT";
@ -194,26 +194,26 @@ public class EventTypes {
public static final String EVENT_MAINTENANCE_PREPARE = "MAINT.PREPARE";
public static final String EVENT_MAINTENANCE_PREPARE_PRIMARY_STORAGE = "MAINT.PREPARE.PS";
//VPN
// VPN
public static final String EVENT_REMOTE_ACCESS_VPN_CREATE = "VPN.REMOTE.ACCESS.CREATE";
public static final String EVENT_REMOTE_ACCESS_VPN_DESTROY = "VPN.REMOTE.ACCESS.DESTROY";
public static final String EVENT_VPN_USER_ADD = "VPN.USER.ADD";
public static final String EVENT_VPN_USER_REMOVE = "VPN.USER.REMOVE";
//Network
// Network
public static final String EVENT_NETWORK_RESTART = "NETWORK.RESTART";
//Custom certificates
// Custom certificates
public static final String EVENT_UPLOAD_CUSTOM_CERTIFICATE = "UPLOAD.CUSTOM.CERTIFICATE";
//OneToOnenat
// OneToOnenat
public static final String EVENT_ENABLE_STATIC_NAT = "STATICNAT.ENABLE";
public static final String EVENT_DISABLE_STATIC_NAT = "STATICNAT.DISABLE";
public static final String EVENT_ZONE_VLAN_ASSIGN = "ZONE.VLAN.ASSIGN";
public static final String EVENT_ZONE_VLAN_RELEASE = "ZONE.VLAN.RELEASE";
//Projects
// Projects
public static final String EVENT_PROJECT_CREATE = "PROJECT.CREATE";
public static final String EVENT_PROJECT_UPDATE = "PROJECT.UPDATE";
public static final String EVENT_PROJECT_DELETE = "PROJECT.DELETE";
@ -224,30 +224,30 @@ public class EventTypes {
public static final String EVENT_PROJECT_INVITATION_REMOVE = "PROJECT.INVITATION.REMOVE";
public static final String EVENT_PROJECT_ACCOUNT_REMOVE = "PROJECT.ACCOUNT.REMOVE";
//Network as a Service
// Network as a Service
public static final String EVENT_NETWORK_ELEMENT_CONFIGURE = "NETWORK.ELEMENT.CONFIGURE";
//Physical Network Events
// Physical Network Events
public static final String EVENT_PHYSICAL_NETWORK_CREATE = "PHYSICAL.NETWORK.CREATE";
public static final String EVENT_PHYSICAL_NETWORK_DELETE = "PHYSICAL.NETWORK.DELETE";
public static final String EVENT_PHYSICAL_NETWORK_UPDATE = "PHYSICAL.NETWORK.UPDATE";
//Physical Network Service Provider Events
// Physical Network Service Provider Events
public static final String EVENT_SERVICE_PROVIDER_CREATE = "SERVICE.PROVIDER.CREATE";
public static final String EVENT_SERVICE_PROVIDER_DELETE = "SERVICE.PROVIDER.DELETE";
public static final String EVENT_SERVICE_PROVIDER_UPDATE = "SERVICE.PROVIDER.UPDATE";
//Physical Network TrafficType Events
// Physical Network TrafficType Events
public static final String EVENT_TRAFFIC_TYPE_CREATE = "TRAFFIC.TYPE.CREATE";
public static final String EVENT_TRAFFIC_TYPE_DELETE = "TRAFFIC.TYPE.DELETE";
public static final String EVENT_TRAFFIC_TYPE_UPDATE = "TRAFFIC.TYPE.UPDATE";
// external network device events
public static final String EVENT_EXTERAL_LB_DEVICE_ADD = "PHYSICAL.LOADBALANCER.ADD" ;
public static final String EVENT_EXTERAL_LB_DEVICE_ADD = "PHYSICAL.LOADBALANCER.ADD";
public static final String EVENT_EXTERAL_LB_DEVICE_DELETE = "PHYSICAL.LOADBALANCER.DELETE";
public static final String EVENT_EXTERAL_LB_DEVICE_CONFIGURE = "PHYSICAL.LOADBALANCER.CONFIGURE";
public static final String EVENT_EXTERAL_FIREWALL_DEVICE_ADD = "PHYSICAL.FIREWALL.ADD" ;
public static final String EVENT_EXTERAL_FIREWALL_DEVICE_ADD = "PHYSICAL.FIREWALL.ADD";
public static final String EVENT_EXTERAL_FIREWALL_DEVICE_DELETE = "PHYSICAL.FIREWALL.DELETE";
public static final String EVENT_EXTERAL_FIREWALL_DEVICE_CONFIGURE = "PHYSICAL.FIREWALL.CONFIGURE";
}

View File

@ -37,5 +37,4 @@ public class AccountLimitException extends CloudRuntimeException {
}
// TODO: Add the actual thing that causes the exception. Is it ip address, vm, etc?
}

View File

@ -20,13 +20,10 @@ package com.cloud.exception;
public class InternalErrorException extends ManagementServerException {
private static final long serialVersionUID = -3070582946175427902L;
public InternalErrorException(String message) {
super(message);
}
}

View File

@ -25,20 +25,14 @@ import com.cloud.utils.SerialVersionUID;
*/
public class ManagementServerException extends Exception {
private static final long serialVersionUID = SerialVersionUID.ManagementServerException;
public ManagementServerException() {
}
public ManagementServerException(String message) {
super(message);
}
}

View File

@ -20,7 +20,7 @@ package com.cloud.exception;
import com.cloud.utils.exception.CloudRuntimeException;
public class UnsupportedServiceException extends CloudRuntimeException{
public class UnsupportedServiceException extends CloudRuntimeException {
public UnsupportedServiceException(String message) {
super(message);

View File

@ -37,7 +37,7 @@ import com.cloud.utils.net.Ip;
* - DomainId = domain of the account owner.
* - Allocated = time it was allocated.
*/
public interface IpAddress extends ControlledEntity{
public interface IpAddress extends ControlledEntity {
enum State {
Allocating, // The IP Address is being propagated to other network elements and is not ready for use yet.
Allocated, // The IP address is in used.

View File

@ -24,7 +24,6 @@ import com.cloud.network.Networks.BroadcastDomainType;
import com.cloud.network.Networks.Mode;
import com.cloud.network.Networks.TrafficType;
public class NetworkProfile implements Network {
private long id;
private long dataCenterId;
@ -184,7 +183,7 @@ public class NetworkProfile implements Network {
}
@Override
public Network.GuestType getGuestType(){
public Network.GuestType getGuestType() {
return guestType;
}

View File

@ -132,4 +132,5 @@ public interface NetworkService {
Network getExclusiveGuestNetwork(long zoneId);
List<Pair<TrafficType, String>> listTrafficTypeImplementor(ListTrafficTypeImplementorsCmd cmd);
}

View File

@ -30,7 +30,7 @@ public class Networks {
public enum RouterPrivateIpStrategy {
None,
DcGlobal, //global to data center
DcGlobal, // global to data center
HostLocal;
public static String DummyPrivateIp = "169.254.1.1";
@ -108,9 +108,9 @@ public class Networks {
Vpn;
public static boolean isSystemNetwork(TrafficType trafficType) {
if(Storage.equals(trafficType)
if (Storage.equals(trafficType)
|| Management.equals(trafficType)
|| Control.equals(trafficType)){
|| Control.equals(trafficType)) {
return true;
}
return false;
@ -161,7 +161,8 @@ public class Networks {
public <T> URI toUri(T value) {
try {
//assert(this!=Vlan || value.getClass().isAssignableFrom(Integer.class)) : "Why are you putting non integer into vlan url";
// assert(this!=Vlan || value.getClass().isAssignableFrom(Integer.class)) :
// "Why are you putting non integer into vlan url";
return new URI(scheme + "://" + value.toString());
} catch (URISyntaxException e) {
throw new CloudRuntimeException("Unable to convert to isolation type URI: " + value);

View File

@ -49,7 +49,7 @@ public interface PhysicalNetwork {
BroadcastDomainRange getBroadcastDomainRange();
//TrafficType getTrafficType();
// TrafficType getTrafficType();
long getDataCenterId();

View File

@ -25,8 +25,6 @@ import java.util.List;
import com.cloud.network.Network.Service;
/**
* This defines the specifics of a physical network service provider
*

View File

@ -17,23 +17,22 @@
*/
package com.cloud.network;
/**
* PhysicalNetworkNames provides the labels to identify per traffic type
* the physical networks available to the host .
*/
public class PhysicalNetworkSetupInfo {
//physical network ID as seen by Mgmt server
// physical network ID as seen by Mgmt server
Long physicalNetworkId;
String privateNetworkName;
String publicNetworkName;
String guestNetworkName;
String storageNetworkName;
//this is used by VmWare to identify the vlan to use for management traffic
// this is used by VmWare to identify the vlan to use for management traffic
String mgmtVlan;
public PhysicalNetworkSetupInfo(){
public PhysicalNetworkSetupInfo() {
}
public String getPrivateNetworkName() {
@ -84,5 +83,4 @@ public class PhysicalNetworkSetupInfo {
this.mgmtVlan = mgmtVlan;
}
}

View File

@ -23,8 +23,6 @@ package com.cloud.network;
import com.cloud.network.Networks.TrafficType;
/**
* This defines the specifics of a physical network traffic type
*

View File

@ -22,19 +22,22 @@ import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.router.VirtualRouter;
import com.cloud.utils.component.PluggableService;
public interface VirtualNetworkApplianceService {
/**
* Starts domain router
* @param cmd the command specifying router's id
*
* @param cmd
* the command specifying router's id
* @return DomainRouter object
*/
VirtualRouter startRouter(long routerId, boolean reprogramNetwork) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException;
/**
* Reboots domain router
* @param cmd the command specifying router's id
*
* @param cmd
* the command specifying router's id
* @return router if successful
*/
VirtualRouter rebootRouter(long routerId, boolean reprogramNetwork) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException;
@ -43,8 +46,11 @@ public interface VirtualNetworkApplianceService {
/**
* Stops domain router
* @param id of the router
* @param forced just do it. caller knows best.
*
* @param id
* of the router
* @param forced
* just do it. caller knows best.
* @return router if successful, null otherwise
* @throws ResourceUnavailableException
* @throws ConcurrentOperationException

View File

@ -23,8 +23,12 @@ public interface VirtualRouterProvider {
VirtualRouter,
ElasticLoadBalancerVm
}
public VirtualRouterProviderType getType();
public long getId();
public boolean isEnabled();
public long getNspId();
}

View File

@ -10,11 +10,14 @@ import com.cloud.user.Account;
public interface FirewallService {
FirewallRule createFirewallRule(FirewallRule rule) throws NetworkRuleConflictException;
List<? extends FirewallRule> listFirewallRules(ListFirewallRulesCmd cmd);
/**
* Revokes a firewall rule
* @param ruleId the id of the rule to revoke.
*
* @param ruleId
* the id of the rule to revoke.
* @return
*/
boolean revokeFirewallRule(long ruleId, boolean apply);
@ -24,4 +27,5 @@ public interface FirewallService {
FirewallRule getFirewallRule(long ruleId);
boolean revokeRelatedFirewallRule(long ruleId, boolean apply);
}

View File

@ -18,28 +18,28 @@
package com.cloud.network.lb;
import java.util.List;
import com.cloud.api.commands.CreateLBStickinessPolicyCmd;
import com.cloud.api.commands.CreateLoadBalancerRuleCmd;
import com.cloud.api.commands.ListLBStickinessPoliciesCmd;
import com.cloud.api.commands.ListLoadBalancerRuleInstancesCmd;
import com.cloud.api.commands.ListLoadBalancerRulesCmd;
import com.cloud.api.commands.UpdateLoadBalancerRuleCmd;
import com.cloud.exception.InsufficientAddressCapacityException;
import com.cloud.exception.NetworkRuleConflictException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.rules.StickinessPolicy;
import com.cloud.network.rules.LoadBalancer;
import com.cloud.network.rules.StickinessPolicy;
import com.cloud.uservm.UserVm;
public interface LoadBalancingRulesService {
/**
* Create a load balancer rule from the given ipAddress/port to the given private port
* @param openFirewall TODO
* @param cmd the command specifying the ip address, public port, protocol, private port, and algorithm
*
* @param openFirewall
* TODO
* @param cmd
* the command specifying the ip address, public port, protocol, private port, and algorithm
* @return the newly created LoadBalancerVO if successful, null otherwise
* @throws InsufficientAddressCapacityException
*/
@ -48,9 +48,14 @@ public interface LoadBalancingRulesService {
LoadBalancer updateLoadBalancerRule(UpdateLoadBalancerRuleCmd cmd);
boolean deleteLoadBalancerRule(long lbRuleId, boolean apply);
/**
* Create a stickiness policy to a load balancer from the given stickiness method name and parameters in (name,value) pairs.
* @param cmd the command specifying the stickiness method name, params (name,value pairs), policy name and description.
* Create a stickiness policy to a load balancer from the given stickiness method name and parameters in
* (name,value) pairs.
*
* @param cmd
* the command specifying the stickiness method name, params (name,value pairs), policy name and
* description.
* @return the newly created stickiness policy if successfull, null otherwise
* @thows NetworkRuleConflictException
*/
@ -59,6 +64,7 @@ public interface LoadBalancingRulesService {
public boolean applyLBStickinessPolicy(CreateLBStickinessPolicyCmd cmd) throws ResourceUnavailableException;
boolean deleteLBStickinessPolicy(long stickinessPolicyId);
/**
* Assign a virtual machine, or list of virtual machines, to a load balancer.
*/
@ -67,8 +73,11 @@ public interface LoadBalancingRulesService {
boolean removeFromLoadBalancer(long lbRuleId, List<Long> vmIds);
boolean applyLoadBalancerConfig(long lbRuleId) throws ResourceUnavailableException;
/**
* List instances that have either been applied to a load balancer or are eligible to be assigned to a load balancer.
* List instances that have either been applied to a load balancer or are eligible to be assigned to a load
* balancer.
*
* @param cmd
* @return list of vm instances that have been or can be applied to a load balancer
*/
@ -76,19 +85,24 @@ public interface LoadBalancingRulesService {
/**
* List load balancer rules based on the given criteria
* @param cmd the command that specifies the criteria to use for listing load balancers. Load balancers can be listed
*
* @param cmd
* the command that specifies the criteria to use for listing load balancers. Load balancers can be
* listed
* by id, name, public ip, and vm instance id
* @return list of load balancers that match the criteria
*/
List<? extends LoadBalancer> searchForLoadBalancers(ListLoadBalancerRulesCmd cmd);
/**
* List stickiness policies based on the given criteria
* @param cmd the command specifies the load balancing rule id.
*
* @param cmd
* the command specifies the load balancing rule id.
* @return list of stickiness policies that match the criteria.
*/
List<? extends StickinessPolicy> searchForLBStickinessPolicies(ListLBStickinessPoliciesCmd cmd);
List<LoadBalancingRule> listByNetworkId(long networkId);
LoadBalancer findById(long LoadBalancer);

View File

@ -37,7 +37,7 @@ public class OvsCreateGreTunnelAnswer extends Answer {
public OvsCreateGreTunnelAnswer(Command cmd, boolean success,
String details, String hostIp, String bridge) {
super(cmd, success, details);
OvsCreateGreTunnelCommand c = (OvsCreateGreTunnelCommand)cmd;
OvsCreateGreTunnelCommand c = (OvsCreateGreTunnelCommand) cmd;
this.hostIp = hostIp;
this.bridge = bridge;
this.remoteIp = c.getRemoteIp();

View File

@ -27,7 +27,7 @@ public class OvsCreateTunnelCommand extends Command {
Long to;
long account;
//for debug info
// for debug info
String fromIp;
@Override

View File

@ -27,7 +27,7 @@ public class OvsSetTagAndFlowAnswer extends Answer {
public OvsSetTagAndFlowAnswer(Command cmd, boolean success, String details) {
super(cmd, success, details);
OvsSetTagAndFlowCommand c = (OvsSetTagAndFlowCommand)cmd;
OvsSetTagAndFlowCommand c = (OvsSetTagAndFlowCommand) cmd;
this.vmId = c.getVmId();
this.seqno = Long.parseLong(c.getSeqNo());
}

View File

@ -31,24 +31,34 @@ public interface RulesService {
/**
* Creates a port forwarding rule between two ip addresses or between
* an ip address and a virtual machine.
* @param rule rule to be created.
* @param vmId vm to be linked to. If specified the destination ip address is ignored.
* @param openFirewall TODO
*
* @param rule
* rule to be created.
* @param vmId
* vm to be linked to. If specified the destination ip address is ignored.
* @param openFirewall
* TODO
* @return PortForwardingRule if created.
* @throws NetworkRuleConflictException if conflicts in the network rules are detected.
* @throws NetworkRuleConflictException
* if conflicts in the network rules are detected.
*/
PortForwardingRule createPortForwardingRule(PortForwardingRule rule, Long vmId, boolean openFirewall) throws NetworkRuleConflictException;
/**
* Revokes a port forwarding rule
* @param ruleId the id of the rule to revoke.
*
* @param ruleId
* the id of the rule to revoke.
* @param caller
* @return
*/
boolean revokePortForwardingRule(long ruleId, boolean apply);
/**
* List port forwarding rules assigned to an ip address
* @param cmd the command object holding the criteria for listing port forwarding rules (the ipAddress)
*
* @param cmd
* the command object holding the criteria for listing port forwarding rules (the ipAddress)
* @return list of port forwarding rules on the given address, empty list if no rules exist
*/
public List<? extends PortForwardingRule> listPortForwardingRules(ListPortForwardingRulesCmd cmd);
@ -58,6 +68,7 @@ public interface RulesService {
boolean enableStaticNat(long ipAddressId, long vmId) throws NetworkRuleConflictException, ResourceUnavailableException;
PortForwardingRule getPortForwardigRule(long ruleId);
FirewallRule getFirewallRule(long ruleId);
StaticNatRule createStaticNatRule(StaticNatRule rule, boolean openFirewall) throws NetworkRuleConflictException;

View File

@ -20,7 +20,7 @@ package com.cloud.network.rules;
import com.cloud.acl.ControlledEntity;
public interface StaticNatRule extends ControlledEntity, FirewallRule{
public interface StaticNatRule extends ControlledEntity, FirewallRule {
long getId();

View File

@ -21,7 +21,6 @@ import java.util.List;
import com.cloud.utils.Pair;
/**
* Definition for a StickinessPolicy
*/

View File

@ -19,7 +19,6 @@ package com.cloud.offering;
import java.util.Date;
/**
* Represents a disk offering that specifies what the end user needs in
* the disk offering.

View File

@ -44,7 +44,7 @@ public interface NetworkOffering {
public final static String DefaultSharedNetworkOfferingWithSGService = "DefaultSharedNetworkOfferingWithSGService";
public final static String DefaultIsolatedNetworkOfferingWithSourceNatService = "DefaultIsolatedNetworkOfferingWithSourceNatService";
public final static String DefaultSharedNetworkOffering = "DefaultSharedNetworkOffering";
public final static String DefaultIsolatedNetworkOffering= "DefaultIsolatedNetworkOffering";
public final static String DefaultIsolatedNetworkOffering = "DefaultIsolatedNetworkOffering";
public final static String DefaultSharedEIPandELBNetworkOffering = "DefaultSharedNetscalerEIPandELBNetworkOffering";
long getId();
@ -104,4 +104,5 @@ public interface NetworkOffering {
boolean getElasticLb();
boolean getSpecifyIpRanges();
}

View File

@ -31,18 +31,21 @@ package com.cloud.offering;
public interface OfferingManager {
/**
* Creates a service offering.
*
* @return ServiceOffering
*/
ServiceOffering createServiceOffering();
/**
* Creates a disk offering.
*
* @return DiskOffering
*/
DiskOffering createDiskOffering();
/**
* Creates a network offering.
*
* @return NetworkOffering
*/
NetworkOffering createNetworkOffering();

View File

@ -42,7 +42,6 @@ public interface ServiceOffering {
*/
String getName();
/**
* @return is this a system service offering
*/

View File

@ -33,11 +33,16 @@ public interface Cluster extends Grouping {
long getId();
String getName();
long getDataCenterId();
long getPodId();
HypervisorType getHypervisorType();
ClusterType getClusterType();
AllocationState getAllocationState();
ManagedState getManagedState();
}

View File

@ -23,8 +23,13 @@ import com.cloud.api.Identity;
import com.cloud.domain.PartOf;
public interface Project extends PartOf, Identity {
public enum State {Active, Disabled, Suspended}
public enum ListProjectResourcesCriteria {ListProjectResourcesOnly, SkipProjectResources}
public enum State {
Active, Disabled, Suspended
}
public enum ListProjectResourcesCriteria {
ListProjectResourcesOnly, SkipProjectResources
}
String getDisplayText();

View File

@ -1,8 +1,9 @@
package com.cloud.projects;
public interface ProjectAccount {
public enum Role {Admin, Regular};
public enum Role {
Admin, Regular
};
long getAccountId();

View File

@ -4,8 +4,10 @@ import java.util.Date;
import com.cloud.acl.ControlledEntity;
public interface ProjectInvitation extends ControlledEntity{
public enum State {Pending, Completed, Expired, Declined}
public interface ProjectInvitation extends ControlledEntity {
public enum State {
Pending, Completed, Expired, Declined
}
long getId();

View File

@ -8,15 +8,18 @@ import com.cloud.exception.ResourceUnavailableException;
import com.cloud.projects.ProjectAccount.Role;
import com.cloud.user.Account;
public interface ProjectService {
/**
* Creates a new project
*
* @param name - project name
* @param displayText - project display text
* @param accountName - account name of the project owner
* @param domainId - domainid of the project owner
* @param name
* - project name
* @param displayText
* - project display text
* @param accountName
* - account name of the project owner
* @param domainId
* - domainid of the project owner
* @return the project if created successfully, null otherwise
* @throws ResourceAllocationException
*/
@ -25,7 +28,8 @@ public interface ProjectService {
/**
* Deletes a project
*
* @param id - project id
* @param id
* - project id
* @return true if the project was deleted successfully, false otherwise
*/
boolean deleteProject(long id);
@ -33,7 +37,8 @@ public interface ProjectService {
/**
* Gets a project by id
*
* @param id - project id
* @param id
* - project id
* @return project object
*/
Project getProject(long id);
@ -58,7 +63,8 @@ public interface ProjectService {
List<? extends ProjectAccount> listProjectAccounts(long projectId, String accountName, String role, Long startIndex, Long pageSizeVal);
List<? extends ProjectInvitation> listProjectInvitations(Long id, Long projectId, String accountName, Long domainId, String state, boolean activeOnly, Long startIndex, Long pageSizeVal, boolean isRecursive, boolean listAll);
List<? extends ProjectInvitation> listProjectInvitations(Long id, Long projectId, String accountName, Long domainId, String state, boolean activeOnly, Long startIndex, Long pageSizeVal, boolean isRecursive,
boolean listAll);
boolean updateInvitation(long projectId, String accountName, String token, boolean accept);

View File

@ -3,7 +3,6 @@ package com.cloud.resource;
import java.util.List;
import java.util.Set;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.fsm.StateMachine;
public enum ResourceState {
@ -34,6 +33,7 @@ public enum ResourceState {
Unmanaged("Umanage a cluster");
private final String comment;
private Event(String comment) {
this.comment = comment;
}
@ -68,7 +68,7 @@ public enum ResourceState {
public static String[] toString(ResourceState... states) {
String[] strs = new String[states.length];
for (int i=0; i<states.length; i++) {
for (int i = 0; i < states.length; i++) {
strs[i] = states[i].toString();
}
return strs;

View File

@ -24,10 +24,13 @@ import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Param {
String name() default "";
String propName() default "";
String description() default "";
// 2 parameters below are used by cloudstack api
Class<?> responseObject() default Object.class;
boolean includeInApiDoc() default true;
}

View File

@ -100,7 +100,8 @@ public interface ManagementService {
static final String Name = "management-server";
/**
* Retrieves the list of data centers with search criteria. Currently the only search criteria is "available" zones for the
* Retrieves the list of data centers with search criteria. Currently the only search criteria is "available" zones
* for the
* account that invokes the API. By specifying available=true all zones which the account can access. By specifying
* available=false the zones where the account has virtual machine instances will be returned.
*
@ -140,7 +141,8 @@ public interface ManagementService {
List<? extends Pod> searchForPods(ListPodsByCmd cmd);
/**
* Searches for servers by the specified search criteria Can search by: "name", "type", "state", "dataCenterId", "podId"
* Searches for servers by the specified search criteria Can search by: "name", "type", "state", "dataCenterId",
* "podId"
*
* @param cmd
* @return List of Hosts
@ -158,7 +160,8 @@ public interface ManagementService {
VirtualMachineTemplate updateTemplate(UpdateTemplateCmd cmd);
/**
* Obtains a list of events by the specified search criteria. Can search by: "username", "type", "level", "startDate",
* Obtains a list of events by the specified search criteria. Can search by: "username", "type", "level",
* "startDate",
* "endDate"
*
* @param c
@ -167,7 +170,8 @@ public interface ManagementService {
List<? extends Event> searchForEvents(ListEventsCmd c);
/**
* Obtains a list of routers by the specified search criteria. Can search by: "userId", "name", "state", "dataCenterId",
* Obtains a list of routers by the specified search criteria. Can search by: "userId", "name", "state",
* "dataCenterId",
* "podId", "hostId"
*
* @param cmd
@ -175,9 +179,9 @@ public interface ManagementService {
*/
List<? extends VirtualRouter> searchForRouters(ListRoutersCmd cmd);
/**
* Obtains a list of IP Addresses by the specified search criteria. Can search by: "userId", "dataCenterId", "address"
* Obtains a list of IP Addresses by the specified search criteria. Can search by: "userId", "dataCenterId",
* "address"
*
* @param cmd
* the command that wraps the search criteria
@ -236,7 +240,8 @@ public interface ManagementService {
* List ISOs that match the specified criteria.
*
* @param cmd
* The command that wraps the (optional) templateId, name, keyword, templateFilter, bootable, account, and zoneId
* The command that wraps the (optional) templateId, name, keyword, templateFilter, bootable, account,
* and zoneId
* parameters.
* @return list of ISOs
*/
@ -246,7 +251,8 @@ public interface ManagementService {
* List templates that match the specified criteria.
*
* @param cmd
* The command that wraps the (optional) templateId, name, keyword, templateFilter, bootable, account, and zoneId
* The command that wraps the (optional) templateId, name, keyword, templateFilter, bootable, account,
* and zoneId
* parameters.
* @return list of ISOs
*/
@ -300,7 +306,8 @@ public interface ManagementService {
* Extracts the volume to a particular location.
*
* @param cmd
* the command specifying url (where the volume needs to be extracted to), zoneId (zone where the volume exists),
* the command specifying url (where the volume needs to be extracted to), zoneId (zone where the volume
* exists),
* id (the id of the volume)
* @throws URISyntaxException
* @throws InternalErrorException
@ -311,7 +318,9 @@ public interface ManagementService {
/**
* return an array of available hypervisors
* @param zoneId TODO
*
* @param zoneId
* TODO
*
* @return an array of available hypervisors in the cloud
*/
@ -381,7 +390,8 @@ public interface ManagementService {
*
* @param cmd
* The api command class.
* @return A VO containing the key pair name, finger print for the public key and the private key material of the key pair.
* @return A VO containing the key pair name, finger print for the public key and the private key material of the
* key pair.
*/
SSHKeyPair createSSHKeyPair(CreateSSHKeyPairCmd cmd);
@ -406,12 +416,15 @@ public interface ManagementService {
Type findSystemVMTypeById(long instanceId);
/**
* List hosts for migrating the given VM. The API returns list of all hosts in the VM's cluster minus the current host and
* List hosts for migrating the given VM. The API returns list of all hosts in the VM's cluster minus the current
* host and
* also a list of hosts that seem to have enough CPU and RAM capacity to host this VM.
*
* @param Long vmId
* @param Long
* vmId
* Id of The VM to migrate
* @return Pair<List<? extends Host>, List<? extends Host>> List of all Hosts in VM's cluster and list of Hosts with enough capacity
* @return Pair<List<? extends Host>, List<? extends Host>> List of all Hosts in VM's cluster and list of Hosts with
* enough capacity
*/
Pair<List<? extends Host>, List<? extends Host>> listHostsForMigrationOfVM(Long vmId, Long startIndex, Long pageSize);

View File

@ -21,7 +21,10 @@ package com.cloud.storage;
public interface GuestOS {
long getId();
String getName();
String getDisplayName();
long getCategoryId();
}

View File

@ -23,7 +23,7 @@ import java.util.Date;
import com.cloud.acl.ControlledEntity;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
public interface Snapshot extends ControlledEntity{
public interface Snapshot extends ControlledEntity {
public enum Type {
MANUAL,
RECURRING,
@ -70,15 +70,25 @@ public interface Snapshot extends ControlledEntity{
public static final long MANUAL_POLICY_ID = 0L;
Long getId();
long getAccountId();
long getVolumeId();
String getPath();
String getName();
Date getCreated();
Type getType();
Status getStatus();
HypervisorType getHypervisorType();
boolean isRecursive();
short getsnapshotType();
}

View File

@ -61,7 +61,7 @@ public class Storage {
}
public String getFileExtension() {
if(fileExtension == null)
if (fileExtension == null)
return toString().toLowerCase();
return fileExtension;
@ -84,17 +84,17 @@ public class Storage {
}
public static enum TemplateType {
SYSTEM, /*routing, system vm template*/
BUILTIN, /*buildin template*/
SYSTEM, /* routing, system vm template */
BUILTIN, /* buildin template */
PERHOST, /* every host has this template, don't need to install it in secondary storage */
USER /* User supplied template/iso */
}
public static enum StoragePoolType {
Filesystem(false), //local directory
NetworkFilesystem(true), //NFS or CIFS
IscsiLUN(true), //shared LUN, with a clusterfs overlay
Iscsi(true), //for e.g., ZFS Comstar
Filesystem(false), // local directory
NetworkFilesystem(true), // NFS or CIFS
IscsiLUN(true), // shared LUN, with a clusterfs overlay
Iscsi(true), // for e.g., ZFS Comstar
ISO(false), // for iso image
LVM(false), // XenServer local LVM SR
CLVM(true),
@ -114,10 +114,11 @@ public class Storage {
return shared;
}
}
public static List<StoragePoolType> getNonSharedStoragePoolTypes(){
public static List<StoragePoolType> getNonSharedStoragePoolTypes() {
List<StoragePoolType> nonSharedStoragePoolTypes = new ArrayList<StoragePoolType>();
for(StoragePoolType storagePoolType : StoragePoolType.values()){
if (!storagePoolType.isShared()){
for (StoragePoolType storagePoolType : StoragePoolType.values()) {
if (!storagePoolType.isShared()) {
nonSharedStoragePoolTypes.add(storagePoolType);
}
}
@ -125,5 +126,7 @@ public class Storage {
}
public static enum StorageResourceType {STORAGE_POOL, STORAGE_HOST, SECONDARY_STORAGE, LOCAL_SECONDARY_STORAGE}
public static enum StorageResourceType {
STORAGE_POOL, STORAGE_HOST, SECONDARY_STORAGE, LOCAL_SECONDARY_STORAGE
}
}

View File

@ -25,6 +25,8 @@ import com.cloud.utils.component.Adapter;
*/
public interface StorageGuru extends Adapter {
void createVolume();
void prepareVolume();
void destroyVolume();
}

View File

@ -19,7 +19,6 @@ package com.cloud.storage;
import java.util.Date;
import com.cloud.host.Status;
import com.cloud.storage.Storage.StoragePoolType;
/**
@ -60,7 +59,6 @@ public interface StoragePool {
*/
Date getUpdateTime();
/**
* @return availability zone.
*/
@ -71,13 +69,11 @@ public interface StoragePool {
*/
long getCapacityBytes();
/**
* @return available storage in bytes
*/
long getAvailableBytes();
Long getClusterId();
/**

View File

@ -38,7 +38,8 @@ public interface StorageService {
* Create StoragePool based on uri
*
* @param cmd
* the command object that specifies the zone, cluster/pod, URI, details, etc. to use to create the storage pool.
* the command object that specifies the zone, cluster/pod, URI, details, etc. to use to create the
* storage pool.
* @return
* @throws ResourceInUseException
* @throws IllegalArgumentException
@ -52,7 +53,8 @@ public interface StorageService {
* Creates the database object for a volume based on the given criteria
*
* @param cmd
* the API command wrapping the criteria (account/domainId [admin only], zone, diskOffering, snapshot, name)
* the API command wrapping the criteria (account/domainId [admin only], zone, diskOffering, snapshot,
* name)
* @return the volume object
* @throws PermissionDeniedException
*/
@ -62,7 +64,8 @@ public interface StorageService {
* Creates the volume based on the given criteria
*
* @param cmd
* the API command wrapping the criteria (account/domainId [admin only], zone, diskOffering, snapshot, name)
* the API command wrapping the criteria (account/domainId [admin only], zone, diskOffering, snapshot,
* name)
* @return the volume object
*/
Volume createVolume(CreateVolumeCmd cmd);

View File

@ -21,9 +21,14 @@ import com.cloud.agent.api.to.SwiftTO;
public interface Swift {
public long getId();
public String getUrl();
public String getAccount();
public String getUserName();
public String getKey();
public SwiftTO toSwiftTO();
}

View File

@ -22,9 +22,17 @@ import java.util.Date;
public interface Upload {
public static enum Status {UNKNOWN, ABANDONED, UPLOADED, NOT_UPLOADED, UPLOAD_ERROR, UPLOAD_IN_PROGRESS, NOT_COPIED, COPY_IN_PROGRESS, COPY_ERROR, COPY_COMPLETE, DOWNLOAD_URL_CREATED, DOWNLOAD_URL_NOT_CREATED, ERROR}
public static enum Type {VOLUME, TEMPLATE, ISO}
public static enum Mode {FTP_UPLOAD, HTTP_DOWNLOAD}
public static enum Status {
UNKNOWN, ABANDONED, UPLOADED, NOT_UPLOADED, UPLOAD_ERROR, UPLOAD_IN_PROGRESS, NOT_COPIED, COPY_IN_PROGRESS, COPY_ERROR, COPY_COMPLETE, DOWNLOAD_URL_CREATED, DOWNLOAD_URL_NOT_CREATED, ERROR
}
public static enum Type {
VOLUME, TEMPLATE, ISO
}
public static enum Mode {
FTP_UPLOAD, HTTP_DOWNLOAD
}
long getHostId();

View File

@ -24,7 +24,9 @@ import java.util.Date;
*
*/
public interface VMTemplateStorageResourceAssoc {
public static enum Status {UNKNOWN, DOWNLOAD_ERROR, NOT_DOWNLOADED, DOWNLOAD_IN_PROGRESS, DOWNLOADED, ABANDONED, UPLOADED, NOT_UPLOADED, UPLOAD_ERROR, UPLOAD_IN_PROGRESS}
public static enum Status {
UNKNOWN, DOWNLOAD_ERROR, NOT_DOWNLOADED, DOWNLOAD_IN_PROGRESS, DOWNLOADED, ABANDONED, UPLOADED, NOT_UPLOADED, UPLOAD_ERROR, UPLOAD_IN_PROGRESS
}
String getInstallPath();

View File

@ -42,19 +42,24 @@ public interface SnapshotService {
List<? extends Snapshot> listSnapshots(ListSnapshotsCmd cmd);
/**
* Delete specified snapshot from the specified. If no other policies are assigned it calls destroy snapshot. This will be
* Delete specified snapshot from the specified. If no other policies are assigned it calls destroy snapshot. This
* will be
* used for manual snapshots too.
* @param snapshotId TODO
*
* @param snapshotId
* TODO
*/
boolean deleteSnapshot(long snapshotId);
/**
* Creates a policy with specified schedule. maxSnaps specifies the number of most recent snapshots that are to be retained.
* Creates a policy with specified schedule. maxSnaps specifies the number of most recent snapshots that are to be
* retained.
* If the number of snapshots go beyond maxSnaps the oldest snapshot is deleted
*
* @param cmd
* the command that
* @param policyOwner TODO
* @param policyOwner
* TODO
* @return the newly created snapshot policy if success, null otherwise
*/
SnapshotPolicy createPolicy(CreateSnapshotPolicyCmd cmd, Account policyOwner);
@ -84,7 +89,9 @@ public interface SnapshotService {
/**
* Create a snapshot of a volume
* @param snapshotOwner TODO
*
* @param snapshotOwner
* TODO
* @param cmd
* the API command wrapping the parameters for creating the snapshot (mainly volumeId)
*

View File

@ -17,8 +17,6 @@
*/
package com.cloud.storage.template;
public class TemplateInfo {
String templateName;
String installPath;
@ -80,4 +78,5 @@ public class TemplateInfo {
public void setSize(long size) {
this.size = size;
}
}

View File

@ -41,7 +41,7 @@ public interface TemplateService {
VirtualMachineTemplate copyTemplate(CopyTemplateCmd cmd) throws StorageUnavailableException, ResourceAllocationException;
VirtualMachineTemplate prepareTemplate(long templateId, long zoneId) ;
VirtualMachineTemplate prepareTemplate(long templateId, long zoneId);
boolean detachIso(long vmId);

View File

@ -27,13 +27,17 @@ import com.cloud.storage.Storage.TemplateType;
public interface VirtualMachineTemplate extends ControlledEntity {
public static enum BootloaderType { PyGrub, HVM, External, CD };
public static enum BootloaderType {
PyGrub, HVM, External, CD
};
public enum TemplateFilter {
featured, // returns templates that have been marked as featured and public
self, // returns templates that have been registered or created by the calling user
selfexecutable, // same as self, but only returns templates that are ready to be deployed with
sharedexecutable, // ready templates that have been granted to the calling user by another user
executable, // templates that are owned by the calling user, or public templates, that can be used to deploy a new VM
executable, // templates that are owned by the calling user, or public templates, that can be used to deploy a
// new VM
community, // returns templates that have been marked as public but not featured
all // all templates (only usable by admins)
}

View File

@ -51,9 +51,14 @@ public interface Account extends ControlledEntity {
public static final long ACCOUNT_ID_SYSTEM = 1;
public long getId();
public String getAccountName();
public short getType();
public State getState();
public Date getRemoved();
public String getNetworkDomain();
}

View File

@ -38,24 +38,38 @@ public interface AccountService {
/**
* Creates a new user and account, stores the password as is so encrypted passwords are recommended.
* @param userName TODO
* @param password TODO
* @param firstName TODO
* @param lastName TODO
* @param email TODO
* @param timezone TODO
* @param accountName TODO
* @param accountType TODO
* @param domainId TODO
* @param networkDomain TODO
*
* @param userName
* TODO
* @param password
* TODO
* @param firstName
* TODO
* @param lastName
* TODO
* @param email
* TODO
* @param timezone
* TODO
* @param accountName
* TODO
* @param accountType
* TODO
* @param domainId
* TODO
* @param networkDomain
* TODO
*
* @return the user if created successfully, null otherwise
*/
UserAccount createUserAccount(String userName, String password, String firstName, String lastName, String email, String timezone, String accountName, short accountType, Long domainId, String networkDomain, Map<String, String> details);
UserAccount createUserAccount(String userName, String password, String firstName, String lastName, String email, String timezone, String accountName, short accountType, Long domainId, String networkDomain,
Map<String, String> details);
/**
* Deletes a user by userId
* @param accountId - id of the account do delete
*
* @param accountId
* - id of the account do delete
*
* @return true if delete was successful, false otherwise
*/
@ -64,7 +78,8 @@ public interface AccountService {
/**
* Disables a user by userId
*
* @param userId - the userId
* @param userId
* - the userId
* @return UserAccount object
*/
UserAccount disableUser(long userId);
@ -72,13 +87,15 @@ public interface AccountService {
/**
* Enables a user
*
* @param userId - the userId
* @param userId
* - the userId
* @return UserAccount object
*/
UserAccount enableUser(long userId);
/**
* Locks a user by userId. A locked user cannot access the API, but will still have running VMs/IP addresses allocated/etc.
* Locks a user by userId. A locked user cannot access the API, but will still have running VMs/IP addresses
* allocated/etc.
*
* @param userId
* @return UserAccount object
@ -95,8 +112,11 @@ public interface AccountService {
/**
* Disables an account by accountName and domainId
* @param accountName TODO
* @param domainId TODO
*
* @param accountName
* TODO
* @param domainId
* TODO
* @param accountId
* @param disabled
* account if success
@ -109,19 +129,22 @@ public interface AccountService {
*
* @param accountName
* - the enableAccount command defining the accountId to be deleted.
* @param domainId TODO
* @param domainId
* TODO
* @param accountId
* @return account object
*/
Account enableAccount(String accountName, Long domainId, Long accountId);
/**
* Locks an account by accountId. A locked account cannot access the API, but will still have running VMs/IP addresses
* Locks an account by accountId. A locked account cannot access the API, but will still have running VMs/IP
* addresses
* allocated/etc.
*
* @param accountName
* - the LockAccount command defining the accountId to be locked.
* @param domainId TODO
* @param domainId
* TODO
* @param accountId
* @return account object
*/
@ -142,13 +165,14 @@ public interface AccountService {
User getSystemUser();
User createUser(String userName, String password, String firstName, String lastName, String email, String timeZone, String accountName, Long domainId);
boolean deleteUser(DeleteUserCmd deleteUserCmd);
boolean isAdmin(short accountType);
Account finalizeOwner(Account caller, String accountName, Long domainId, Long projectId);
Pair<List<Long>,Long> finalizeAccountDomainForList(Account caller, String accountName, Long domainId, Long projectId);
Pair<List<Long>, Long> finalizeAccountDomainForList(Account caller, String accountName, Long domainId, Long projectId);
Account getActiveAccountByName(String accountName, Long domainId);

View File

@ -46,4 +46,5 @@ public interface DomainService {
List<? extends Domain> searchForDomainChildren(ListDomainChildrenCmd cmd)
throws PermissionDeniedException;
}

View File

@ -29,10 +29,15 @@ public interface ResourceLimitService {
/**
* Updates an existing resource limit with the specified details. If a limit doesn't exist, will create one.
* @param accountId TODO
* @param domainId TODO
* @param resourceType TODO
* @param max TODO
*
* @param accountId
* TODO
* @param domainId
* TODO
* @param resourceType
* TODO
* @param max
* TODO
*
* @return the updated/created resource limit
*/
@ -40,19 +45,28 @@ public interface ResourceLimitService {
/**
* Updates an existing resource count details for the account/domain
* @param accountId TODO
* @param domainId TODO
* @param typeId TODO
*
* @param accountId
* TODO
* @param domainId
* TODO
* @param typeId
* TODO
* @return the updated/created resource counts
*/
List<? extends ResourceCount> recalculateResourceCount(Long accountId, Long domainId, Integer typeId);
/**
* Search for resource limits for the given id and/or account and/or type and/or domain.
* @param id TODO
* @param accountId TODO
* @param domainId TODO
* @param type TODO
*
* @param id
* TODO
* @param accountId
* TODO
* @param domainId
* TODO
* @param type
* TODO
* @return a list of limits that match the criteria
*/
public List<? extends ResourceLimit> searchForLimits(Long id, Long accountId, Long domainId, Integer type, Long startIndex, Long pageSizeVal);
@ -60,6 +74,7 @@ public interface ResourceLimitService {
/**
* Finds the resource limit for a specified account and type. If the account has an infinite limit, will check
* the account's parent domain, and if that limit is also infinite, will return the ROOT domain's limit.
*
* @param account
* @param type
* @return resource limit
@ -69,6 +84,7 @@ public interface ResourceLimitService {
/**
* Finds the resource limit for a specified domain and type. If the domain has an infinite limit, will check
* up the domain hierarchy
*
* @param account
* @param type
* @return resource limit
@ -77,31 +93,37 @@ public interface ResourceLimitService {
/**
* Increments the resource count
*
* @param accountId
* @param type
* @param delta
*/
public void incrementResourceCount(long accountId, ResourceType type, Long...delta);
public void incrementResourceCount(long accountId, ResourceType type, Long... delta);
/**
* Decrements the resource count
*
* @param accountId
* @param type
* @param delta
*/
public void decrementResourceCount(long accountId, ResourceType type, Long...delta);
public void decrementResourceCount(long accountId, ResourceType type, Long... delta);
/**
* Checks if a limit has been exceeded for an account
*
* @param account
* @param type
* @param count the number of resources being allocated, count will be added to current allocation and compared against maximum allowed allocation
* @param count
* the number of resources being allocated, count will be added to current allocation and compared
* against maximum allowed allocation
* @throws ResourceAllocationException
*/
public void checkResourceLimit(Account account, ResourceCount.ResourceType type, long...count) throws ResourceAllocationException;
public void checkResourceLimit(Account account, ResourceCount.ResourceType type, long... count) throws ResourceAllocationException;
/**
* Gets the count of resources for a resource type and account
*
* @param account
* @param type
* @return count of resources

View File

@ -82,12 +82,13 @@ public class UserContext {
public static UserContext current() {
UserContext context = s_currentContext.get();
if(context == null) {
if (context == null) {
//
// TODO: we should enforce explicit UserContext setup at major entry-points for security concerns,
// however, there are many places that run background jobs assume the system context.
//
// If there is a security concern, all entry points from user (including the front end that takes HTTP request in and
// If there is a security concern, all entry points from user (including the front end that takes HTTP
// request in and
// the core async-job manager that runs commands from user) have explicitly setup the UserContext.
//
return s_adminContext;
@ -97,7 +98,7 @@ public class UserContext {
public static void updateContext(long userId, Account accountObject, String sessionId) {
UserContext context = current();
assert(context != null) : "Context should be already setup before you can call this one";
assert (context != null) : "Context should be already setup before you can call this one";
context.setCallerUserId(userId);
context.setCaller(accountObject);

View File

@ -18,7 +18,6 @@
package com.cloud.vm;
import com.cloud.exception.ResourceAllocationException;
public interface BareMetalVmService extends UserVmService {
}

View File

@ -105,6 +105,7 @@ public class DiskProfile {
public void setUseLocalStorage(boolean useLocalStorage) {
this.useLocalStorage = useLocalStorage;
}
/**
* @return Is this volume recreatable? A volume is recreatable if the disk's content can be
* reconstructed from the template.

View File

@ -23,8 +23,11 @@ import com.cloud.acl.ControlledEntity;
public interface InstanceGroup extends ControlledEntity {
long getId();
String getName();
Date getCreated();
Short getAccountType();
}

View File

@ -92,7 +92,8 @@ public interface Nic {
long getId();
/**
* @return reservation id returned by the allocation source. This can be the String version of the database id if the
* @return reservation id returned by the allocation source. This can be the String version of the database id if
* the
* allocation source does not need it's own implementation of the reservation id. This is passed back to the
* allocation source to release the resource.
*/

View File

@ -121,9 +121,11 @@ public interface UserVmService {
* Create a template database record in preparation for creating a private template.
*
* @param cmd
* the command object that defines the name, display text, snapshot/volume, bits, public/private, etc. for the
* the command object that defines the name, display text, snapshot/volume, bits, public/private, etc.
* for the
* private template
* @param templateOwner TODO
* @param templateOwner
* TODO
* @return the vm template object if successful, null otherwise
* @throws ResourceAllocationException
*/
@ -154,10 +156,14 @@ public interface UserVmService {
* @param displayName
* - an optional user generated name for the virtual machine
* @param diskOfferingId
* - the ID of the disk offering for the virtual machine. If the template is of ISO format, the diskOfferingId is
* for the root disk volume. Otherwise this parameter is used to indicate the offering for the data disk volume.
* If the templateId parameter passed is from a Template object, the diskOfferingId refers to a DATA Disk Volume
* created. If the templateId parameter passed is from an ISO object, the diskOfferingId refers to a ROOT Disk
* - the ID of the disk offering for the virtual machine. If the template is of ISO format, the
* diskOfferingId is
* for the root disk volume. Otherwise this parameter is used to indicate the offering for the data disk
* volume.
* If the templateId parameter passed is from a Template object, the diskOfferingId refers to a DATA Disk
* Volume
* created. If the templateId parameter passed is from an ISO object, the diskOfferingId refers to a ROOT
* Disk
* Volume created
* @param diskSize
* - the arbitrary size for the DATADISK volume. Mutually exclusive with diskOfferingId
@ -166,17 +172,22 @@ public interface UserVmService {
* @param hypervisor
* - the hypervisor on which to deploy the virtual machine
* @param userData
* - an optional binary data that can be sent to the virtual machine upon a successful deployment. This binary
* data must be base64 encoded before adding it to the request. Currently only HTTP GET is supported. Using HTTP
* - an optional binary data that can be sent to the virtual machine upon a successful deployment. This
* binary
* data must be base64 encoded before adding it to the request. Currently only HTTP GET is supported.
* Using HTTP
* GET (via querystring), you can send up to 2KB of data after base64 encoding
* @param sshKeyPair
* - name of the ssh key pair used to login to the virtual machine
* @param requestedIps TODO
* @param defaultIp TODO
* @param requestedIps
* TODO
* @param defaultIp
* TODO
* @param accountName
* - an optional account for the virtual machine. Must be used with domainId
* @param domainId
* - an optional domainId for the virtual machine. If the account parameter is used, domainId must also be used
* - an optional domainId for the virtual machine. If the account parameter is used, domainId must also
* be used
* @return UserVm object if successful.
*
* @throws InsufficientCapacityException
@ -192,7 +203,8 @@ public interface UserVmService {
throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException;
/**
* Creates a User VM in Advanced Zone (Security Group feature is enabled) in the database and returns the VM to the caller.
* Creates a User VM in Advanced Zone (Security Group feature is enabled) in the database and returns the VM to the
* caller.
*
* @param zone
* - availability zone for the virtual machine
@ -209,10 +221,14 @@ public interface UserVmService {
* @param displayName
* - an optional user generated name for the virtual machine
* @param diskOfferingId
* - the ID of the disk offering for the virtual machine. If the template is of ISO format, the diskOfferingId is
* for the root disk volume. Otherwise this parameter is used to indicate the offering for the data disk volume.
* If the templateId parameter passed is from a Template object, the diskOfferingId refers to a DATA Disk Volume
* created. If the templateId parameter passed is from an ISO object, the diskOfferingId refers to a ROOT Disk
* - the ID of the disk offering for the virtual machine. If the template is of ISO format, the
* diskOfferingId is
* for the root disk volume. Otherwise this parameter is used to indicate the offering for the data disk
* volume.
* If the templateId parameter passed is from a Template object, the diskOfferingId refers to a DATA Disk
* Volume
* created. If the templateId parameter passed is from an ISO object, the diskOfferingId refers to a ROOT
* Disk
* Volume created
* @param diskSize
* - the arbitrary size for the DATADISK volume. Mutually exclusive with diskOfferingId
@ -221,17 +237,22 @@ public interface UserVmService {
* @param hypervisor
* - the hypervisor on which to deploy the virtual machine
* @param userData
* - an optional binary data that can be sent to the virtual machine upon a successful deployment. This binary
* data must be base64 encoded before adding it to the request. Currently only HTTP GET is supported. Using HTTP
* - an optional binary data that can be sent to the virtual machine upon a successful deployment. This
* binary
* data must be base64 encoded before adding it to the request. Currently only HTTP GET is supported.
* Using HTTP
* GET (via querystring), you can send up to 2KB of data after base64 encoding
* @param sshKeyPair
* - name of the ssh key pair used to login to the virtual machine
* @param requestedIps TODO
* @param defaultIp TODO
* @param requestedIps
* TODO
* @param defaultIp
* TODO
* @param accountName
* - an optional account for the virtual machine. Must be used with domainId
* @param domainId
* - an optional domainId for the virtual machine. If the account parameter is used, domainId must also be used
* - an optional domainId for the virtual machine. If the account parameter is used, domainId must also
* be used
* @return UserVm object if successful.
*
* @throws InsufficientCapacityException
@ -243,11 +264,13 @@ public interface UserVmService {
* @throws InsufficientResourcesException
*/
UserVm createAdvancedSecurityGroupVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, List<Long> networkIdList, List<Long> securityGroupIdList,
Account owner, String hostName, String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, String userData, String sshKeyPair, Map<Long, String> requestedIps, String defaultIp, String keyboard)
Account owner, String hostName, String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, String userData, String sshKeyPair, Map<Long, String> requestedIps,
String defaultIp, String keyboard)
throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException;
/**
* Creates a User VM in Advanced Zone (Security Group feature is disabled) in the database and returns the VM to the caller.
* Creates a User VM in Advanced Zone (Security Group feature is disabled) in the database and returns the VM to the
* caller.
*
* @param zone
* - availability zone for the virtual machine
@ -262,10 +285,14 @@ public interface UserVmService {
* @param displayName
* - an optional user generated name for the virtual machine
* @param diskOfferingId
* - the ID of the disk offering for the virtual machine. If the template is of ISO format, the diskOfferingId is
* for the root disk volume. Otherwise this parameter is used to indicate the offering for the data disk volume.
* If the templateId parameter passed is from a Template object, the diskOfferingId refers to a DATA Disk Volume
* created. If the templateId parameter passed is from an ISO object, the diskOfferingId refers to a ROOT Disk
* - the ID of the disk offering for the virtual machine. If the template is of ISO format, the
* diskOfferingId is
* for the root disk volume. Otherwise this parameter is used to indicate the offering for the data disk
* volume.
* If the templateId parameter passed is from a Template object, the diskOfferingId refers to a DATA Disk
* Volume
* created. If the templateId parameter passed is from an ISO object, the diskOfferingId refers to a ROOT
* Disk
* Volume created
* @param diskSize
* - the arbitrary size for the DATADISK volume. Mutually exclusive with diskOfferingId
@ -274,17 +301,22 @@ public interface UserVmService {
* @param hypervisor
* - the hypervisor on which to deploy the virtual machine
* @param userData
* - an optional binary data that can be sent to the virtual machine upon a successful deployment. This binary
* data must be base64 encoded before adding it to the request. Currently only HTTP GET is supported. Using HTTP
* - an optional binary data that can be sent to the virtual machine upon a successful deployment. This
* binary
* data must be base64 encoded before adding it to the request. Currently only HTTP GET is supported.
* Using HTTP
* GET (via querystring), you can send up to 2KB of data after base64 encoding
* @param sshKeyPair
* - name of the ssh key pair used to login to the virtual machine
* @param requestedIps TODO
* @param defaultIp TODO
* @param requestedIps
* TODO
* @param defaultIp
* TODO
* @param accountName
* - an optional account for the virtual machine. Must be used with domainId
* @param domainId
* - an optional domainId for the virtual machine. If the account parameter is used, domainId must also be used
* - an optional domainId for the virtual machine. If the account parameter is used, domainId must also
* be used
* @return UserVm object if successful.
*
* @throws InsufficientCapacityException
@ -359,10 +391,14 @@ public interface UserVmService {
UserVm getUserVm(long vmId);
/**
* Migrate the given VM to the destination host provided. The API returns the migrated VM if migration succeeds. Only Root
* Migrate the given VM to the destination host provided. The API returns the migrated VM if migration succeeds.
* Only Root
* Admin can migrate a VM.
* @param destinationStorage TODO
* @param Long vmId
*
* @param destinationStorage
* TODO
* @param Long
* vmId
* vmId of The VM to migrate
* @param Host
* destinationHost to migrate the VM
@ -379,7 +415,7 @@ public interface UserVmService {
*/
VirtualMachine migrateVirtualMachine(Long vmId, Host destinationHost) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException;
UserVm moveVMToUser(AssignVMCmd moveUserVMCmd) throws ResourceAllocationException, ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException ;
UserVm moveVMToUser(AssignVMCmd moveUserVMCmd) throws ResourceAllocationException, ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException;
VirtualMachine vmStorageMigration(Long vmId, StoragePool destPool);

View File

@ -26,7 +26,6 @@ import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.utils.fsm.StateMachine2;
import com.cloud.utils.fsm.StateObject;
/**
* VirtualMachine describes the properties held by a virtual machine
*
@ -45,7 +44,6 @@ public interface VirtualMachine extends RunningOn, ControlledEntity, Identity, S
Unknown(false, "VM state is unknown."),
Shutdowned(false, "VM is shutdowned from inside");
private final boolean _transitional;
String _description;
@ -73,7 +71,8 @@ public interface VirtualMachine extends RunningOn, ControlledEntity, Identity, S
s_fsm.addTransition(State.Stopped, VirtualMachine.Event.StopRequested, State.Stopped);
s_fsm.addTransition(State.Stopped, VirtualMachine.Event.AgentReportStopped, State.Stopped);
// please pay attention about state transition to Error state, there should be only one case (failed in VM creation process)
// please pay attention about state transition to Error state, there should be only one case (failed in VM
// creation process)
// that can have such transition
s_fsm.addTransition(State.Stopped, VirtualMachine.Event.OperationFailedToError, State.Error);
@ -192,9 +191,9 @@ public interface VirtualMachine extends RunningOn, ControlledEntity, Identity, S
UserBareMetal;
public static boolean isSystemVM(VirtualMachine.Type vmtype) {
if(DomainRouter.equals(vmtype)
if (DomainRouter.equals(vmtype)
|| ConsoleProxy.equals(vmtype)
|| SecondaryStorageVm.equals(vmtype)){
|| SecondaryStorageVm.equals(vmtype)) {
return true;
}
return false;
@ -238,7 +237,7 @@ public interface VirtualMachine extends RunningOn, ControlledEntity, Identity, S
/**
* @return the state of the virtual machine
*/
//public State getState();
// public State getState();
/**
* @return template id.
@ -247,6 +246,7 @@ public interface VirtualMachine extends RunningOn, ControlledEntity, Identity, S
/**
* returns the guest OS ID
*
* @return guestOSId
*/
public long getGuestOSId();
@ -265,6 +265,7 @@ public interface VirtualMachine extends RunningOn, ControlledEntity, Identity, S
* @return id of the host it was assigned last time.
*/
public Long getLastHostId();
@Override
public Long getHostId();
@ -277,6 +278,7 @@ public interface VirtualMachine extends RunningOn, ControlledEntity, Identity, S
* @return should limit CPU usage to the service offering?
*/
public boolean limitCpuUse();
/**
* @return date when machine was created
*/

View File

@ -27,7 +27,6 @@ import com.cloud.template.VirtualMachineTemplate;
import com.cloud.template.VirtualMachineTemplate.BootloaderType;
import com.cloud.user.Account;
/**
* VirtualMachineProfile describes one virtual machine. This object
* is passed to various adapters to be processed. Anything that is
@ -37,11 +36,11 @@ import com.cloud.user.Account;
* on what the virtual machine profile should look like before it is
* actually started on the hypervisor.
*
* @param <T> a VirtualMachine
* @param <T>
* a VirtualMachine
*/
public interface VirtualMachineProfile<T extends VirtualMachine> {
public static class Param {
public static final Param VmPassword = new Param("VmPassword");
@ -52,7 +51,7 @@ public interface VirtualMachineProfile<T extends VirtualMachine> {
private String name;
public Param(String name) {
synchronized(Param.class) {
synchronized (Param.class) {
this.name = name;
}
}
@ -131,6 +130,7 @@ public interface VirtualMachineProfile<T extends VirtualMachine> {
void setParameter(Param name, Object value);
void setBootLoaderType(BootloaderType bootLoader);
BootloaderType getBootLoaderType();
Map<Param, Object> getParameters();

View File

@ -19,9 +19,11 @@
package com.cloud.vm;
public interface VmStats {
//vm related stats
// vm related stats
public double getCPUUtilization();
public double getNetworkReadKBs();
public double getNetworkWriteKBs();
}

View File

@ -28,28 +28,29 @@ import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="resource_limit")
@Table(name = "resource_limit")
public class ResourceLimitVO implements ResourceLimit {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id = null;
@Column(name="type")
@Column(name = "type")
@Enumerated(EnumType.STRING)
private ResourceCount.ResourceType type;
@Column(name="domain_id")
@Column(name = "domain_id")
private Long domainId;
@Column(name="account_id")
@Column(name = "account_id")
private Long accountId;
@Column(name="max")
@Column(name = "max")
private Long max;
public ResourceLimitVO() {}
public ResourceLimitVO() {
}
public ResourceLimitVO(ResourceCount.ResourceType type, Long max, long ownerId, ResourceOwnerType ownerType) {
this.type = type;

View File

@ -531,12 +531,13 @@ public class XenServerConnectionPool {
s_logger.debug(msg);
throw new CloudRuntimeException(msg);
}
Host host = null;
synchronized (poolUuid.intern()) {
// Let's see if it is an existing connection.
mConn = getConnect(poolUuid);
if (mConn != null){
try{
Host.getByUuid(mConn, hostUuid);
host = Host.getByUuid(mConn, hostUuid);
} catch (Types.SessionInvalid e) {
s_logger.debug("Session thgrough ip " + mConn.getIp() + " is invalid for pool(" + poolUuid + ") due to " + e.toString());
try {
@ -635,6 +636,45 @@ public class XenServerConnectionPool {
}
}
}
if ( mConn != null ) {
if (s_managePool) {
try {
Map<String, String> args = new HashMap<String, String>();
host.callPlugin(mConn, "echo", "main", args);
} catch (Types.SessionInvalid e) {
if (s_logger.isDebugEnabled()) {
String msg = "Catch Exception: " + e.getClass().getName() + " Can't connect host " + ipAddress + " due to " + e.toString();
s_logger.debug(msg);
}
PoolEmergencyResetMaster(ipAddress, mConn.getIp(), mConn.getUsername(), mConn.getPassword());
} catch (Types.CannotContactHost e ) {
if (s_logger.isDebugEnabled()) {
String msg = "Catch Exception: " + e.getClass().getName() + " Can't connect host " + ipAddress + " due to " + e.toString();
s_logger.debug(msg);
}
PoolEmergencyResetMaster(ipAddress, mConn.getIp(), mConn.getUsername(), mConn.getPassword());
} catch (Types.HostOffline e ) {
if (s_logger.isDebugEnabled()) {
String msg = "Catch Exception: " + e.getClass().getName() + " Host is offline " + ipAddress + " due to " + e.toString();
s_logger.debug(msg);
}
PoolEmergencyResetMaster(ipAddress, mConn.getIp(), mConn.getUsername(), mConn.getPassword());
} catch (Types.HostNotLive e ) {
String msg = "Catch Exception: " + e.getClass().getName() + " Host Not Live " + ipAddress + " due to " + e.toString();
if (s_logger.isDebugEnabled()) {
s_logger.debug(msg);
}
PoolEmergencyResetMaster(ipAddress, mConn.getIp(), mConn.getUsername(), mConn.getPassword());
} catch (Exception e) {
String msg = "Master can not talk to Slave " + hostUuid + " IP " + ipAddress;
if (s_logger.isDebugEnabled()) {
s_logger.debug(msg);
}
throw new CloudRuntimeException(msg);
}
}
}
return mConn;
}
@ -879,24 +919,6 @@ public class XenServerConnectionPool {
}
loginWithPassword(this, _username, _password, APIVersion.latest().toString());
method_params[0] = getSessionReference();
} catch (Types.CannotContactHost e ) {
if (s_logger.isDebugEnabled()) {
String msg = "Cannot Contact Host for method: " + method_call + " due to " + e.toString();
s_logger.debug(msg);
}
throw e;
} catch (Types.HostOffline e ) {
if (s_logger.isDebugEnabled()) {
String msg = "Host Offline for method: " + method_call + " due to " + e.toString();
s_logger.debug(msg);
}
throw e;
} catch (Types.HostNotLive e ) {
if (s_logger.isDebugEnabled()) {
String msg = "Host is Not alive for method: " + method_call + " due to " + e.toString();
s_logger.debug(msg);
}
throw e;
} catch (XmlRpcClientException e) {
s_logger.debug("XmlRpcClientException for method: " + method_call + " due to " + e.getMessage());
removeConnect(_poolUuid);

View File

@ -278,7 +278,8 @@ public class ApiResponseHelper implements ResponseGenerator {
Long ipTotal = ApiDBUtils.getResourceCount(ResourceType.public_ip, account.getId());
Long ips = ipLimit - ipTotal;
//check how many free ips are left, and if it's less than max allowed number of ips from account - use this value
// check how many free ips are left, and if it's less than max allowed number of ips from account - use this
// value
Long ipsLeft = ApiDBUtils.countFreePublicIps();
boolean unlimited = true;
if (ips.longValue() > ipsLeft.longValue()) {
@ -354,7 +355,6 @@ public class ApiResponseHelper implements ResponseGenerator {
return accountResponse;
}
@Override
public UserResponse createUserResponse(UserAccount user) {
UserResponse userResponse = new UserResponse();
@ -529,7 +529,6 @@ public class ApiResponseHelper implements ResponseGenerator {
return policyResponse;
}
@Override
public HostResponse createHostResponse(Host host) {
return createHostResponse(host, EnumSet.of(HostDetails.all));
@ -558,7 +557,7 @@ public class ApiResponseHelper implements ResponseGenerator {
hostResponse.setCreated(host.getCreated());
if (details.contains(HostDetails.all) || details.contains(HostDetails.capacity)
|| details.contains(HostDetails.stats) || details.contains(HostDetails.events) ){
|| details.contains(HostDetails.stats) || details.contains(HostDetails.events)) {
GuestOSCategoryVO guestOSCategory = ApiDBUtils.getHostGuestOSCategory(host.getId());
if (guestOSCategory != null) {
@ -584,10 +583,10 @@ public class ApiResponseHelper implements ResponseGenerator {
DecimalFormat decimalFormat = new DecimalFormat("#.##");
if (host.getType() == Host.Type.Routing) {
if (details.contains(HostDetails.all) || details.contains(HostDetails.capacity)){
//set allocated capacities
Long mem = ApiDBUtils.getMemoryOrCpuCapacitybyHost(host.getId(),Capacity.CAPACITY_TYPE_MEMORY);
Long cpu = ApiDBUtils.getMemoryOrCpuCapacitybyHost(host.getId(),Capacity.CAPACITY_TYPE_CPU);
if (details.contains(HostDetails.all) || details.contains(HostDetails.capacity)) {
// set allocated capacities
Long mem = ApiDBUtils.getMemoryOrCpuCapacitybyHost(host.getId(), Capacity.CAPACITY_TYPE_MEMORY);
Long cpu = ApiDBUtils.getMemoryOrCpuCapacitybyHost(host.getId(), Capacity.CAPACITY_TYPE_CPU);
hostResponse.setMemoryAllocated(mem);
hostResponse.setMemoryTotal(host.getTotalMemory());
@ -600,7 +599,7 @@ public class ApiResponseHelper implements ResponseGenerator {
hostResponse.setCpuWithOverprovisioning(cpuWithOverprovisioning);
}
if (details.contains(HostDetails.all) || details.contains(HostDetails.stats)){
if (details.contains(HostDetails.all) || details.contains(HostDetails.stats)) {
// set CPU/RAM/Network stats
String cpuUsed = null;
HostStats hostStats = ApiDBUtils.getHostStatistics(host.getId());
@ -608,16 +607,16 @@ public class ApiResponseHelper implements ResponseGenerator {
float cpuUtil = (float) hostStats.getCpuUtilization();
cpuUsed = decimalFormat.format(cpuUtil) + "%";
hostResponse.setCpuUsed(cpuUsed);
hostResponse.setMemoryUsed( (new Double(hostStats.getUsedMemory())).longValue());
hostResponse.setMemoryUsed((new Double(hostStats.getUsedMemory())).longValue());
hostResponse.setNetworkKbsRead((new Double(hostStats.getNetworkReadKBs())).longValue());
hostResponse.setNetworkKbsWrite((new Double(hostStats.getNetworkWriteKBs())).longValue());
}
}
}else if (host.getType() == Host.Type.SecondaryStorage){
} else if (host.getType() == Host.Type.SecondaryStorage) {
StorageStats secStorageStats = ApiDBUtils.getSecondaryStorageStatistics(host.getId());
if (secStorageStats != null){
if (secStorageStats != null) {
hostResponse.setDiskSizeTotal(secStorageStats.getCapacityBytes());
hostResponse.setDiskSizeAllocated(secStorageStats.getByteUsed());
}
@ -625,7 +624,7 @@ public class ApiResponseHelper implements ResponseGenerator {
hostResponse.setLocalStorageActive(ApiDBUtils.isLocalStorageActiveOnHost(host));
if (details.contains(HostDetails.all) || details.contains(HostDetails.events)){
if (details.contains(HostDetails.all) || details.contains(HostDetails.events)) {
Set<com.cloud.host.Status.Event> possibleEvents = host.getStatus().getPossibleEvents();
if ((possibleEvents != null) && !possibleEvents.isEmpty()) {
String events = "";
@ -809,22 +808,22 @@ public class ApiResponseHelper implements ResponseGenerator {
podResponse.setEndIp(((ipRange.length > 1) && (ipRange[1] != null)) ? ipRange[1] : "");
podResponse.setGateway(pod.getGateway());
podResponse.setAllocationState(pod.getAllocationState().toString());
if (showCapacities != null && showCapacities){
List<SummedCapacity> capacities = ApiDBUtils.getCapacityByClusterPodZone(null,pod.getId(),null);
if (showCapacities != null && showCapacities) {
List<SummedCapacity> capacities = ApiDBUtils.getCapacityByClusterPodZone(null, pod.getId(), null);
Set<CapacityResponse> capacityResponses = new HashSet<CapacityResponse>();
float cpuOverprovisioningFactor = ApiDBUtils.getCpuOverprovisioningFactor();
for (SummedCapacity capacity : capacities){
for (SummedCapacity capacity : capacities) {
CapacityResponse capacityResponse = new CapacityResponse();
capacityResponse.setCapacityType(capacity.getCapacityType());
capacityResponse.setCapacityUsed(capacity.getUsedCapacity());
if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_CPU){
capacityResponse.setCapacityTotal(new Long((long)(capacity.getTotalCapacity()*cpuOverprovisioningFactor)));
}else if(capacity.getCapacityType() == Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED){
List<SummedCapacity> c = ApiDBUtils.findNonSharedStorageForClusterPodZone(null, pod.getId() ,null);
if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_CPU) {
capacityResponse.setCapacityTotal(new Long((long) (capacity.getTotalCapacity() * cpuOverprovisioningFactor)));
} else if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED) {
List<SummedCapacity> c = ApiDBUtils.findNonSharedStorageForClusterPodZone(null, pod.getId(), null);
capacityResponse.setCapacityTotal(capacity.getTotalCapacity() - c.get(0).getTotalCapacity());
capacityResponse.setCapacityUsed(capacity.getUsedCapacity() - c.get(0).getUsedCapacity());
}else{
} else {
capacityResponse.setCapacityTotal(capacity.getTotalCapacity());
}
if (capacityResponse.getCapacityTotal() != 0) {
@ -862,22 +861,22 @@ public class ApiResponseHelper implements ResponseGenerator {
// FIXME zoneResponse.setVlan(dataCenter.get.getVnet());
}
if (showCapacities != null && showCapacities){
List<SummedCapacity> capacities = ApiDBUtils.getCapacityByClusterPodZone(dataCenter.getId(),null,null);
if (showCapacities != null && showCapacities) {
List<SummedCapacity> capacities = ApiDBUtils.getCapacityByClusterPodZone(dataCenter.getId(), null, null);
Set<CapacityResponse> capacityResponses = new HashSet<CapacityResponse>();
float cpuOverprovisioningFactor = ApiDBUtils.getCpuOverprovisioningFactor();
for (SummedCapacity capacity : capacities){
for (SummedCapacity capacity : capacities) {
CapacityResponse capacityResponse = new CapacityResponse();
capacityResponse.setCapacityType(capacity.getCapacityType());
capacityResponse.setCapacityUsed(capacity.getUsedCapacity());
if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_CPU){
capacityResponse.setCapacityTotal(new Long((long)(capacity.getTotalCapacity()*cpuOverprovisioningFactor)));
}else if(capacity.getCapacityType() == Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED){
List<SummedCapacity> c = ApiDBUtils.findNonSharedStorageForClusterPodZone(dataCenter.getId(), null ,null);
if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_CPU) {
capacityResponse.setCapacityTotal(new Long((long) (capacity.getTotalCapacity() * cpuOverprovisioningFactor)));
} else if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED) {
List<SummedCapacity> c = ApiDBUtils.findNonSharedStorageForClusterPodZone(dataCenter.getId(), null, null);
capacityResponse.setCapacityTotal(capacity.getTotalCapacity() - c.get(0).getTotalCapacity());
capacityResponse.setCapacityUsed(capacity.getUsedCapacity() - c.get(0).getUsedCapacity());
}else{
} else {
capacityResponse.setCapacityTotal(capacity.getTotalCapacity());
}
if (capacityResponse.getCapacityTotal() != 0) {
@ -893,10 +892,10 @@ public class ApiResponseHelper implements ResponseGenerator {
zoneResponse.setCapacitites(new ArrayList<CapacityResponse>(capacityResponses));
}
//set network domain info
// set network domain info
zoneResponse.setDomain(dataCenter.getDomain());
//set domain info
// set domain info
Long domainId = dataCenter.getDomainId();
if (domainId != null) {
Domain domain = ApiDBUtils.findDomainById(domainId);
@ -912,15 +911,15 @@ public class ApiResponseHelper implements ResponseGenerator {
return zoneResponse;
}
private List<CapacityResponse> getStatsCapacityresponse(Long poolId, Long clusterId, Long podId, Long zoneId){
private List<CapacityResponse> getStatsCapacityresponse(Long poolId, Long clusterId, Long podId, Long zoneId) {
List<CapacityVO> capacities = new ArrayList<CapacityVO>();
capacities.add(ApiDBUtils.getStoragePoolUsedStats(poolId, clusterId, podId, zoneId));
if(clusterId == null && podId == null){
if (clusterId == null && podId == null) {
capacities.add(ApiDBUtils.getSecondaryStorageUsedStats(poolId, zoneId));
}
List<CapacityResponse> capacityResponses = new ArrayList<CapacityResponse>();
for (CapacityVO capacity : capacities){
for (CapacityVO capacity : capacities) {
CapacityResponse capacityResponse = new CapacityResponse();
capacityResponse.setCapacityType(capacity.getCapacityType());
capacityResponse.setCapacityUsed(capacity.getUsedCapacity());
@ -956,7 +955,7 @@ public class ApiResponseHelper implements ResponseGenerator {
Long instanceId = volume.getInstanceId();
if (instanceId != null && volume.getState() != Volume.State.Destroy) {
VMInstanceVO vm = ApiDBUtils.findVMInstanceById(instanceId);
if(vm != null){
if (vm != null) {
volResponse.setVirtualMachineId(vm.getId());
volResponse.setVirtualMachineName(vm.getHostName());
UserVm userVm = ApiDBUtils.findUserVmById(vm.getId());
@ -964,10 +963,10 @@ public class ApiResponseHelper implements ResponseGenerator {
volResponse.setVirtualMachineDisplayName(userVm.getDisplayName());
volResponse.setVirtualMachineState(vm.getState().toString());
} else {
s_logger.error("User Vm with Id: "+instanceId+" does not exist for volume "+volume.getId());
s_logger.error("User Vm with Id: " + instanceId + " does not exist for volume " + volume.getId());
}
} else {
s_logger.error("Vm with Id: "+instanceId+" does not exist for volume "+volume.getId());
s_logger.error("Vm with Id: " + instanceId + " does not exist for volume " + volume.getId());
}
}
@ -1020,7 +1019,7 @@ public class ApiResponseHelper implements ResponseGenerator {
// volResponse.setSourceType(volume.getSourceType().toString());
// }
//return hypervisor for ROOT and Resource domain only
// return hypervisor for ROOT and Resource domain only
Account caller = UserContext.current().getCaller();
if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
volResponse.setHypervisor(ApiDBUtils.getVolumeHyperType(volume.getId()).toString());
@ -1073,7 +1072,7 @@ public class ApiResponseHelper implements ResponseGenerator {
}
StorageStats stats = ApiDBUtils.getStoragePoolStatistics(pool.getId());
long allocatedSize = ApiDBUtils.getStorageCapacitybyPool(pool.getId(),Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED);
long allocatedSize = ApiDBUtils.getStorageCapacitybyPool(pool.getId(), Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED);
poolResponse.setDiskSizeTotal(pool.getCapacityBytes());
poolResponse.setDiskSizeAllocated(allocatedSize);
@ -1109,23 +1108,23 @@ public class ApiResponseHelper implements ResponseGenerator {
}
DataCenterVO zone = ApiDBUtils.findZoneById(cluster.getDataCenterId());
clusterResponse.setZoneName(zone.getName());
if (showCapacities != null && showCapacities){
List<SummedCapacity> capacities = ApiDBUtils.getCapacityByClusterPodZone(null,null,cluster.getId());
if (showCapacities != null && showCapacities) {
List<SummedCapacity> capacities = ApiDBUtils.getCapacityByClusterPodZone(null, null, cluster.getId());
Set<CapacityResponse> capacityResponses = new HashSet<CapacityResponse>();
float cpuOverprovisioningFactor = ApiDBUtils.getCpuOverprovisioningFactor();
for (SummedCapacity capacity : capacities){
for (SummedCapacity capacity : capacities) {
CapacityResponse capacityResponse = new CapacityResponse();
capacityResponse.setCapacityType(capacity.getCapacityType());
capacityResponse.setCapacityUsed(capacity.getUsedCapacity());
if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_CPU){
capacityResponse.setCapacityTotal(new Long((long)(capacity.getTotalCapacity()*cpuOverprovisioningFactor)));
}else if(capacity.getCapacityType() == Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED){
if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_CPU) {
capacityResponse.setCapacityTotal(new Long((long) (capacity.getTotalCapacity() * cpuOverprovisioningFactor)));
} else if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED) {
List<SummedCapacity> c = ApiDBUtils.findNonSharedStorageForClusterPodZone(null, null, cluster.getId());
capacityResponse.setCapacityTotal(capacity.getTotalCapacity() - c.get(0).getTotalCapacity());
capacityResponse.setCapacityUsed(capacity.getUsedCapacity() - c.get(0).getUsedCapacity());
}else{
} else {
capacityResponse.setCapacityTotal(capacity.getTotalCapacity());
}
if (capacityResponse.getCapacityTotal() != 0) {
@ -1209,9 +1208,8 @@ public class ApiResponseHelper implements ResponseGenerator {
return response;
}
@Override
public List<UserVmResponse> createUserVmResponse(String objectName, EnumSet<VMDetails> details, UserVm...userVms) {
public List<UserVmResponse> createUserVmResponse(String objectName, EnumSet<VMDetails> details, UserVm... userVms) {
Account caller = UserContext.current().getCaller();
Map<Long, DataCenter> dataCenters = new HashMap<Long, DataCenter>();
Map<Long, Host> hosts = new HashMap<Long, Host>();
@ -1234,8 +1232,6 @@ public class ApiResponseHelper implements ResponseGenerator {
userVmResponse.setName(userVm.getHostName());
userVmResponse.setCreated(userVm.getCreated());
userVmResponse.setHaEnable(userVm.isHaEnabled());
if (userVm.getDisplayName() != null) {
@ -1246,7 +1242,7 @@ public class ApiResponseHelper implements ResponseGenerator {
userVmResponse.setPassword(userVm.getPassword());
}
if (details.contains(VMDetails.all) || details.contains(VMDetails.group)){
if (details.contains(VMDetails.all) || details.contains(VMDetails.group)) {
InstanceGroupVO group = ApiDBUtils.findInstanceGroupForVM(userVm.getId());
if (group != null) {
userVmResponse.setGroup(group.getName());
@ -1265,7 +1261,6 @@ public class ApiResponseHelper implements ResponseGenerator {
userVmResponse.setZoneId(zone.getId());
userVmResponse.setZoneName(zone.getName());
// if user is an admin, display host id
if (((caller == null) || (caller.getType() == Account.ACCOUNT_TYPE_ADMIN)) && (userVm.getHostId() != null)) {
Host host = hosts.get(userVm.getHostId());
@ -1298,12 +1293,12 @@ public class ApiResponseHelper implements ResponseGenerator {
}
if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
if (userVm.getHypervisorType() != null){
if (userVm.getHypervisorType() != null) {
userVmResponse.setHypervisor(userVm.getHypervisorType().toString());
}
}
if (details.contains(VMDetails.all) || details.contains(VMDetails.tmpl)){
if (details.contains(VMDetails.all) || details.contains(VMDetails.tmpl)) {
// Template Info
VMTemplateVO template = templates.get(userVm.getTemplateId());
if (template == null) {
@ -1326,8 +1321,7 @@ public class ApiResponseHelper implements ResponseGenerator {
}
}
if (details.contains(VMDetails.all) || details.contains(VMDetails.iso)){
if (details.contains(VMDetails.all) || details.contains(VMDetails.iso)) {
// ISO Info
VMTemplateVO iso = templates.get(userVm.getIsoId());
if (iso == null) {
@ -1343,7 +1337,7 @@ public class ApiResponseHelper implements ResponseGenerator {
}
}
if (details.contains(VMDetails.all) || details.contains(VMDetails.servoff)){
if (details.contains(VMDetails.all) || details.contains(VMDetails.servoff)) {
// Service Offering Info
ServiceOffering offering = serviceOfferings.get(userVm.getServiceOfferingId());
@ -1359,7 +1353,7 @@ public class ApiResponseHelper implements ResponseGenerator {
userVmResponse.setMemory(offering.getRamSize());
}
if (details.contains(VMDetails.all) || details.contains(VMDetails.volume)){
if (details.contains(VMDetails.all) || details.contains(VMDetails.volume)) {
VolumeVO rootVolume = ApiDBUtils.findRootVolume(userVm.getId());
if (rootVolume != null) {
userVmResponse.setRootDeviceId(rootVolume.getDeviceId());
@ -1372,7 +1366,7 @@ public class ApiResponseHelper implements ResponseGenerator {
}
}
if (details.contains(VMDetails.all) || details.contains(VMDetails.stats)){
if (details.contains(VMDetails.all) || details.contains(VMDetails.stats)) {
// stats calculation
DecimalFormat decimalFormat = new DecimalFormat("#.##");
String cpuUsed = null;
@ -1392,12 +1386,12 @@ public class ApiResponseHelper implements ResponseGenerator {
userVmResponse.setGuestOsId(userVm.getGuestOSId());
if (details.contains(VMDetails.all) || details.contains(VMDetails.secgrp)){
if (details.contains(VMDetails.all) || details.contains(VMDetails.secgrp)) {
// security groups - list only when zone is security group enabled
if (zone.isSecurityGroupEnabled()) {
List<SecurityGroupVO> securityGroups = ApiDBUtils.getSecurityGroupsForVm(userVm.getId());
List<SecurityGroupResponse> securityGroupResponse = new ArrayList<SecurityGroupResponse>();
for(SecurityGroupVO grp : securityGroups) {
for (SecurityGroupVO grp : securityGroups) {
SecurityGroupResponse resp = new SecurityGroupResponse();
resp.setId(grp.getId());
resp.setName(grp.getName());
@ -1409,7 +1403,7 @@ public class ApiResponseHelper implements ResponseGenerator {
}
}
if (details.contains(VMDetails.all) || details.contains(VMDetails.nics)){
if (details.contains(VMDetails.all) || details.contains(VMDetails.nics)) {
List<NicProfile> nicProfiles = ApiDBUtils.getNics(userVm);
List<NicResponse> nicResponses = new ArrayList<NicResponse>();
for (NicProfile singleNicProfile : nicProfiles) {
@ -1428,7 +1422,7 @@ public class ApiResponseHelper implements ResponseGenerator {
}
}
//Long networkId = singleNicProfile.getNetworkId();
// Long networkId = singleNicProfile.getNetworkId();
Network network = networks.get(singleNicProfile.getNetworkId());
if (network == null) {
network = ApiDBUtils.findNetworkById(singleNicProfile.getNetworkId());
@ -1465,10 +1459,10 @@ public class ApiResponseHelper implements ResponseGenerator {
vmDataList = ApiDBUtils.listVmDetails(vmDataList);
//initialize vmresponse from vmdatalist
// initialize vmresponse from vmdatalist
List<UserVmResponse> vmResponses = new ArrayList<UserVmResponse>();
DecimalFormat decimalFormat = new DecimalFormat("#.##");
for (UserVmData uvd: vmDataList.values()){
for (UserVmData uvd : vmDataList.values()) {
UserVmResponse userVmResponse = newUserVmResponse(uvd, caller_is_admin);
// stats calculation
@ -1493,7 +1487,6 @@ public class ApiResponseHelper implements ResponseGenerator {
return vmResponses;
}
@Override
public DomainRouterResponse createDomainRouterResponse(VirtualRouter router) {
Account caller = UserContext.current().getCaller();
@ -1553,7 +1546,6 @@ public class ApiResponseHelper implements ResponseGenerator {
populateOwner(routerResponse, router);
DataCenter zone = ApiDBUtils.findZoneById(router.getDataCenterIdToDeployIn());
if (zone != null) {
routerResponse.setZoneName(zone.getName());
@ -1592,7 +1584,7 @@ public class ApiResponseHelper implements ResponseGenerator {
// for console proxies, add the active sessions
if (vm.getType() == Type.ConsoleProxy) {
ConsoleProxyVO proxy = ApiDBUtils.findConsoleProxy(vm.getId());
//proxy can be already destroyed
// proxy can be already destroyed
if (proxy != null) {
vmResponse.setActiveViewerSessions(proxy.getActiveSession());
}
@ -1617,7 +1609,7 @@ public class ApiResponseHelper implements ResponseGenerator {
vmResponse.setLinkLocalIp(singleNicProfile.getIp4Address());
vmResponse.setLinkLocalMacAddress(singleNicProfile.getMacAddress());
vmResponse.setLinkLocalNetmask(singleNicProfile.getNetmask());
} else if (network.getTrafficType() == TrafficType.Public){
} else if (network.getTrafficType() == TrafficType.Public) {
vmResponse.setPublicIp(singleNicProfile.getIp4Address());
vmResponse.setPublicMacAddress(singleNicProfile.getMacAddress());
vmResponse.setPublicNetmask(singleNicProfile.getNetmask());
@ -1729,7 +1721,7 @@ public class ApiResponseHelper implements ResponseGenerator {
return responses;
}
dcs.addAll(ApiDBUtils.listZones());
for (DataCenterVO dc : dcs ) {
for (DataCenterVO dc : dcs) {
responses.addAll(createTemplateResponses(templateId, dc.getId(), readyOnly));
}
return responses;
@ -1910,12 +1902,13 @@ public class ApiResponseHelper implements ResponseGenerator {
responses.add(templateResponse);
return responses;
}
@Override
public List<TemplateResponse> createIsoResponses(long isoId, Long zoneId, boolean readyOnly) {
List<TemplateResponse> isoResponses = new ArrayList<TemplateResponse>();
VirtualMachineTemplate iso = findTemplateById(isoId);
if ( iso.getTemplateType() == TemplateType.PERHOST) {
if (iso.getTemplateType() == TemplateType.PERHOST) {
TemplateResponse isoResponse = new TemplateResponse();
isoResponse.setId(iso.getId());
isoResponse.setName(iso.getName());
@ -1941,14 +1934,14 @@ public class ApiResponseHelper implements ResponseGenerator {
isoResponses.add(isoResponse);
return isoResponses;
} else {
if (zoneId == null || zoneId == -1 ) {
if (zoneId == null || zoneId == -1) {
isoResponses = createSwiftIsoResponses(iso);
if (!isoResponses.isEmpty()) {
return isoResponses;
}
List<DataCenterVO> dcs = new ArrayList<DataCenterVO>();
dcs.addAll(ApiDBUtils.listZones());
for (DataCenterVO dc : dcs ) {
for (DataCenterVO dc : dcs) {
isoResponses.addAll(createIsoResponses(iso, dc.getId(), readyOnly));
}
return isoResponses;
@ -2016,7 +2009,7 @@ public class ApiResponseHelper implements ResponseGenerator {
long isoId = iso.getId();
List<TemplateResponse> isoResponses = new ArrayList<TemplateResponse>();
VMTemplateHostVO isoHost = ApiDBUtils.findTemplateHostRef(isoId, zoneId, readyOnly);
if( isoHost == null ) {
if (isoHost == null) {
return isoResponses;
}
TemplateResponse isoResponse = new TemplateResponse();
@ -2153,6 +2146,7 @@ public class ApiResponseHelper implements ResponseGenerator {
response.setResponses(netGrpResponses);
return response;
}
@Override
public SecurityGroupResponse createSecurityGroupResponse(SecurityGroup group) {
SecurityGroupResponse response = new SecurityGroupResponse();
@ -2225,7 +2219,6 @@ public class ApiResponseHelper implements ResponseGenerator {
}
}
jobResponse.setObjectName("asyncjobs");
return jobResponse;
}
@ -2272,7 +2265,6 @@ public class ApiResponseHelper implements ResponseGenerator {
return responseEvent;
}
private List<CapacityVO> sumCapacities(List<? extends Capacity> hostCapacities) {
Map<String, Long> totalCapacityMap = new HashMap<String, Long>();
Map<String, Long> usedCapacityMap = new HashMap<String, Long>();
@ -2293,7 +2285,7 @@ public class ApiResponseHelper implements ResponseGenerator {
// collect all the capacity types, sum allocated/used and sum total...get one capacity number for each
for (Capacity capacity : hostCapacities) {
//check if zone exist
// check if zone exist
DataCenter zone = ApiDBUtils.findZoneById(capacity.getDataCenterId());
if (zone == null) {
continue;
@ -2301,8 +2293,8 @@ public class ApiResponseHelper implements ResponseGenerator {
short capacityType = capacity.getCapacityType();
//If local storage then ignore
if ( (capacityType == Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED || capacityType == Capacity.CAPACITY_TYPE_STORAGE)
// If local storage then ignore
if ((capacityType == Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED || capacityType == Capacity.CAPACITY_TYPE_STORAGE)
&& poolIdsToIgnore.contains(capacity.getHostOrPoolId())) {
continue;
}
@ -2339,11 +2331,16 @@ public class ApiResponseHelper implements ResponseGenerator {
if (capacityType == Capacity.CAPACITY_TYPE_CPU || capacityType == Capacity.CAPACITY_TYPE_MEMORY) { // Reserved
// Capacity
// accounts for
// stopped vms
// that have been
// stopped within
// an interval
// accounts
// for
// stopped
// vms
// that
// have been
// stopped
// within
// an
// interval
usedCapacity += capacity.getReservedCapacity();
}
@ -2376,10 +2373,13 @@ public class ApiResponseHelper implements ResponseGenerator {
// accounts
// for
// stopped
// vms that
// have been
// vms
// that
// have
// been
// stopped
// within an
// within
// an
// interval
usedCapacity += capacity.getReservedCapacity();
}
@ -2411,7 +2411,7 @@ public class ApiResponseHelper implements ResponseGenerator {
@Override
public List<CapacityResponse> createCapacityResponse(List<? extends Capacity> result, DecimalFormat format) {
List<CapacityResponse> capacityResponses = new ArrayList<CapacityResponse>();
//List<CapacityVO> summedCapacities = sumCapacities(result);
// List<CapacityVO> summedCapacities = sumCapacities(result);
for (Capacity summedCapacity : result) {
CapacityResponse capacityResponse = new CapacityResponse();
capacityResponse.setCapacityTotal(summedCapacity.getTotalCapacity());
@ -2429,7 +2429,7 @@ public class ApiResponseHelper implements ResponseGenerator {
ClusterVO cluster = ApiDBUtils.findClusterById(summedCapacity.getClusterId());
if (cluster != null) {
capacityResponse.setClusterName(cluster.getName());
if (summedCapacity.getPodId() == null){
if (summedCapacity.getPodId() == null) {
long podId = cluster.getPodId();
capacityResponse.setPodId(podId);
capacityResponse.setPodName(ApiDBUtils.findPodById(podId).getName());
@ -2470,7 +2470,7 @@ public class ApiResponseHelper implements ResponseGenerator {
response.setDomainId(templateOwnerDomain);
}
//Set accounts
// Set accounts
List<String> projectIds = new ArrayList<String>();
List<String> regularAccounts = new ArrayList<String>();
for (String accountName : accountNames) {
@ -2478,10 +2478,10 @@ public class ApiResponseHelper implements ResponseGenerator {
if (account.getType() != Account.ACCOUNT_TYPE_PROJECT) {
regularAccounts.add(accountName);
} else {
//convert account to projectIds
// convert account to projectIds
Project project = ApiDBUtils.findProjectByProjectAccountId(account.getId());
if(project.getUuid() != null && !project.getUuid().isEmpty())
if (project.getUuid() != null && !project.getUuid().isEmpty())
projectIds.add(project.getUuid());
else
projectIds.add(String.valueOf(project.getId()));
@ -2610,7 +2610,7 @@ public class ApiResponseHelper implements ResponseGenerator {
List<ServiceResponse> serviceResponses = new ArrayList<ServiceResponse>();
for (Service service : serviceProviderMap.keySet()) {
ServiceResponse svcRsp = new ServiceResponse();
//skip gateway service
// skip gateway service
if (service == Service.Gateway) {
continue;
}
@ -2630,12 +2630,12 @@ public class ApiResponseHelper implements ResponseGenerator {
CapabilityResponse lbIsoaltion = new CapabilityResponse();
lbIsoaltion.setName(Capability.SupportedLBIsolation.getName());
lbIsoaltion.setValue(offering.getDedicatedLB()?"dedicated":"shared");
lbIsoaltion.setValue(offering.getDedicatedLB() ? "dedicated" : "shared");
lbCapResponse.add(lbIsoaltion);
CapabilityResponse eLb = new CapabilityResponse();
eLb.setName(Capability.ElasticLb.getName());
eLb.setValue(offering.getElasticLb()?"true":"false");
eLb.setValue(offering.getElasticLb() ? "true" : "false");
lbCapResponse.add(eLb);
svcRsp.setCapabilities(lbCapResponse);
@ -2643,12 +2643,12 @@ public class ApiResponseHelper implements ResponseGenerator {
List<CapabilityResponse> capabilities = new ArrayList<CapabilityResponse>();
CapabilityResponse sharedSourceNat = new CapabilityResponse();
sharedSourceNat.setName(Capability.SupportedSourceNatTypes.getName());
sharedSourceNat.setValue(offering.getSharedSourceNat()?"perzone":"peraccount");
sharedSourceNat.setValue(offering.getSharedSourceNat() ? "perzone" : "peraccount");
capabilities.add(sharedSourceNat);
CapabilityResponse redundantRouter = new CapabilityResponse();
redundantRouter.setName(Capability.RedundantRouter.getName());
redundantRouter.setValue(offering.getRedundantRouter()?"true":"false");
redundantRouter.setValue(offering.getRedundantRouter() ? "true" : "false");
capabilities.add(redundantRouter);
svcRsp.setCapabilities(capabilities);
@ -2657,7 +2657,7 @@ public class ApiResponseHelper implements ResponseGenerator {
CapabilityResponse eIp = new CapabilityResponse();
eIp.setName(Capability.ElasticIp.getName());
eIp.setValue(offering.getElasticLb()?"true":"false");
eIp.setValue(offering.getElasticLb() ? "true" : "false");
staticNatCapResponse.add(eIp);
svcRsp.setCapabilities(staticNatCapResponse);
@ -2692,13 +2692,13 @@ public class ApiResponseHelper implements ResponseGenerator {
response.setGateway(network.getGateway());
//FIXME - either set netmask or cidr
// FIXME - either set netmask or cidr
response.setCidr(network.getCidr());
if(network.getCidr() != null){
if (network.getCidr() != null) {
response.setNetmask(NetUtils.cidr2Netmask(network.getCidr()));
}
//FIXME - either set broadcast URI or vlan
// FIXME - either set broadcast URI or vlan
if (network.getBroadcastUri() != null) {
String broadcastUri = network.getBroadcastUri().toString();
response.setBroadcastUri(broadcastUri);
@ -2737,7 +2737,7 @@ public class ApiResponseHelper implements ResponseGenerator {
if (serviceCapabilitiesMap != null) {
for (Service service : serviceCapabilitiesMap.keySet()) {
ServiceResponse serviceResponse = new ServiceResponse();
//skip gateway service
// skip gateway service
if (service == Service.Gateway) {
continue;
}
@ -2767,7 +2767,7 @@ public class ApiResponseHelper implements ResponseGenerator {
if (network.getAclType() == null || network.getAclType() == ACLType.Account) {
populateOwner(response, network);
} else {
//get domain from network_domain table
// get domain from network_domain table
Pair<Long, Boolean> domainNetworkDetails = ApiDBUtils.getDomainNetworkDetails(network.getId());
response.setDomainId(domainNetworkDetails.first());
response.setSubdomainAccess(domainNetworkDetails.second());
@ -2787,7 +2787,7 @@ public class ApiResponseHelper implements ResponseGenerator {
}
@Override
public Long getSecurityGroupId (String groupName, long accountId) {
public Long getSecurityGroupId(String groupName, long accountId) {
SecurityGroup sg = ApiDBUtils.getSecurityGroup(groupName, accountId);
if (sg == null) {
return null;
@ -2814,7 +2814,6 @@ public class ApiResponseHelper implements ResponseGenerator {
return response;
}
@Override
public FirewallResponse createFirewallResponse(FirewallRule fwRule) {
FirewallResponse response = new FirewallResponse();
@ -2850,9 +2849,7 @@ public class ApiResponseHelper implements ResponseGenerator {
return response;
}
public UserVmData newUserVmData(UserVm userVm){
public UserVmData newUserVmData(UserVm userVm) {
UserVmData userVmData = new UserVmData();
userVmData.setId(userVm.getId());
userVmData.setName(userVm.getHostName());
@ -2880,7 +2877,7 @@ public class ApiResponseHelper implements ResponseGenerator {
return userVmData;
}
public UserVmResponse newUserVmResponse(UserVmData userVmData, boolean caller_is_admin){
public UserVmResponse newUserVmResponse(UserVmData userVmData, boolean caller_is_admin) {
UserVmResponse userVmResponse = new UserVmResponse();
userVmResponse.setHypervisor(userVmData.getHypervisor());
@ -2898,7 +2895,7 @@ public class ApiResponseHelper implements ResponseGenerator {
userVmResponse.setGroup(userVmData.getGroup());
userVmResponse.setZoneId(userVmData.getZoneId());
userVmResponse.setZoneName(userVmData.getZoneName());
if (caller_is_admin){
if (caller_is_admin) {
userVmResponse.setHostId(userVmData.getHostId());
userVmResponse.setHostName(userVmData.getHostName());
}
@ -2926,7 +2923,7 @@ public class ApiResponseHelper implements ResponseGenerator {
userVmResponse.setForVirtualNetwork(userVmData.getForVirtualNetwork());
Set<SecurityGroupResponse> securityGroupResponse = new HashSet<SecurityGroupResponse>();
for (SecurityGroupData sgd: userVmData.getSecurityGroupList()){
for (SecurityGroupData sgd : userVmData.getSecurityGroupList()) {
if (sgd.getId() != null) {
SecurityGroupResponse sgr = new SecurityGroupResponse();
sgr.setId(sgd.getId());
@ -2946,7 +2943,7 @@ public class ApiResponseHelper implements ResponseGenerator {
userVmResponse.setSecurityGroupList(new ArrayList<SecurityGroupResponse>(securityGroupResponse));
Set<NicResponse> nicResponses = new HashSet<NicResponse>();
for (NicData nd: userVmData.getNics()){
for (NicData nd : userVmData.getNics()) {
NicResponse nr = new NicResponse();
nr.setId(nd.getId());
nr.setNetworkid(nd.getNetworkid());
@ -2968,7 +2965,7 @@ public class ApiResponseHelper implements ResponseGenerator {
}
@Override
public HypervisorCapabilitiesResponse createHypervisorCapabilitiesResponse(HypervisorCapabilities hpvCapabilities){
public HypervisorCapabilitiesResponse createHypervisorCapabilitiesResponse(HypervisorCapabilities hpvCapabilities) {
HypervisorCapabilitiesResponse hpvCapabilitiesResponse = new HypervisorCapabilitiesResponse();
hpvCapabilitiesResponse.setId(hpvCapabilities.getId());
hpvCapabilitiesResponse.setHypervisor(hpvCapabilities.getHypervisorType());
@ -2982,7 +2979,7 @@ public class ApiResponseHelper implements ResponseGenerator {
Account account = ApiDBUtils.findAccountByIdIncludingRemoved(object.getAccountId());
if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
//find the project
// find the project
Project project = ApiDBUtils.findProjectByProjectAccountId(account.getId());
response.setProjectId(project.getId());
response.setProjectName(project.getName());
@ -2998,7 +2995,7 @@ public class ApiResponseHelper implements ResponseGenerator {
private void populateAccount(ControlledEntityResponse response, long accountId) {
Account account = ApiDBUtils.findAccountByIdIncludingRemoved(accountId);
if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
//find the project
// find the project
Project project = ApiDBUtils.findProjectByProjectAccountId(account.getId());
response.setProjectId(project.getId());
response.setProjectName(project.getName());
@ -3066,7 +3063,7 @@ public class ApiResponseHelper implements ResponseGenerator {
}
@Override
public SystemVmInstanceResponse createSystemVmInstanceResponse(VirtualMachine vm){
public SystemVmInstanceResponse createSystemVmInstanceResponse(VirtualMachine vm) {
SystemVmInstanceResponse vmResponse = new SystemVmInstanceResponse();
vmResponse.setId(vm.getId());
vmResponse.setSystemVmType(vm.getType().toString().toLowerCase());
@ -3078,8 +3075,8 @@ public class ApiResponseHelper implements ResponseGenerator {
vmResponse.setState(vm.getState().toString());
}
if (vm.getType() == Type.DomainRouter) {
VirtualRouter router = (VirtualRouter)vm;
if(router.getRole() != null){
VirtualRouter router = (VirtualRouter) vm;
if (router.getRole() != null) {
vmResponse.setRole(router.getRole().toString());
}
}
@ -3096,12 +3093,12 @@ public class ApiResponseHelper implements ResponseGenerator {
response.setVlan(result.getVnet());
response.setDomainId(result.getDomainId());
response.setId(result.getUuid());
if(result.getBroadcastDomainRange() != null){
if (result.getBroadcastDomainRange() != null) {
response.setBroadcastDomainRange(result.getBroadcastDomainRange().toString());
}
response.setIsolationMethods(result.getIsolationMethods());
response.setTags(result.getTags());
if(result.getState() != null){
if (result.getState() != null) {
response.setState(result.getState().toString());
}
@ -3112,20 +3109,20 @@ public class ApiResponseHelper implements ResponseGenerator {
}
@Override
public ServiceResponse createNetworkServiceResponse(Service service){
public ServiceResponse createNetworkServiceResponse(Service service) {
ServiceResponse response = new ServiceResponse();
response.setName(service.getName());
// set list of capabilities required for the service
List<CapabilityResponse> capabilityResponses = new ArrayList<CapabilityResponse>();
Capability[] capabilities = service.getCapabilities();
for(Capability cap : capabilities){
for (Capability cap : capabilities) {
CapabilityResponse capabilityResponse = new CapabilityResponse();
capabilityResponse.setName(cap.getName());
capabilityResponse.setObjectName("capability");
if (cap.getName().equals(Capability.SupportedLBIsolation.getName()) ||
cap.getName().equals(Capability.SupportedSourceNatTypes.getName()) ||
cap.getName().equals(Capability.RedundantRouter.getName()) ) {
cap.getName().equals(Capability.RedundantRouter.getName())) {
capabilityResponse.setCanChoose(true);
} else {
capabilityResponse.setCanChoose(false);
@ -3134,11 +3131,11 @@ public class ApiResponseHelper implements ResponseGenerator {
}
response.setCapabilities(capabilityResponses);
//set list of providers providing this service
// set list of providers providing this service
List<? extends Network.Provider> serviceProviders = ApiDBUtils.getProvidersForService(service);
List<ProviderResponse> serviceProvidersResponses = new ArrayList<ProviderResponse>();
for (Network.Provider serviceProvider : serviceProviders) {
//return only Virtual Router as a provider for the firewall
// return only Virtual Router as a provider for the firewall
if (service == Service.Firewall && !(serviceProvider == Provider.VirtualRouter)) {
continue;
}
@ -3162,7 +3159,7 @@ public class ApiResponseHelper implements ResponseGenerator {
}
@Override
public ProviderResponse createNetworkServiceProviderResponse(PhysicalNetworkServiceProvider result){
public ProviderResponse createNetworkServiceProviderResponse(PhysicalNetworkServiceProvider result) {
ProviderResponse response = new ProviderResponse();
response.setId(result.getUuid());
response.setName(result.getProviderName());
@ -3170,9 +3167,9 @@ public class ApiResponseHelper implements ResponseGenerator {
response.setDestinationPhysicalNetworkId(result.getDestinationPhysicalNetworkId());
response.setState(result.getState().toString());
//set enabled services
// set enabled services
List<String> services = new ArrayList<String>();
for (Service service: result.getEnabledServices()){
for (Service service : result.getEnabledServices()) {
services.add(service.getName());
}
response.setServices(services);
@ -3195,7 +3192,6 @@ public class ApiResponseHelper implements ResponseGenerator {
return response;
}
@Override
public VirtualRouterProviderResponse createVirtualRouterProviderResponse(VirtualRouterProvider result) {
VirtualRouterProviderResponse response = new VirtualRouterProviderResponse();
@ -3206,6 +3202,7 @@ public class ApiResponseHelper implements ResponseGenerator {
response.setObjectName("virtualrouterelement");
return response;
}
@Override
public LBStickinessResponse createLBStickinessPolicyResponse(
StickinessPolicy stickinessPolicy, LoadBalancer lb) {
@ -3236,7 +3233,8 @@ public class ApiResponseHelper implements ResponseGenerator {
List<? extends StickinessPolicy> stickinessPolicies, LoadBalancer lb) {
LBStickinessResponse spResponse = new LBStickinessResponse();
if (lb == null) return spResponse ;
if (lb == null)
return spResponse;
spResponse.setlbRuleId(lb.getId());
Account account = ApiDBUtils.findAccountById(lb.getAccountId());
if (account != null) {
@ -3285,4 +3283,5 @@ public class ApiResponseHelper implements ResponseGenerator {
response.setObjectName("storagenetworkiprange");
return response;
}
}

View File

@ -1,4 +1,5 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
@ -173,44 +174,44 @@ public class ApiServer implements HttpRequestHandler {
return _apiCommands;
}
public static boolean isPluggableServiceCommand(String cmdClassName){
if(s_pluggableServiceCommands != null){
if(s_pluggableServiceCommands.contains(cmdClassName)){
public static boolean isPluggableServiceCommand(String cmdClassName) {
if (s_pluggableServiceCommands != null) {
if (s_pluggableServiceCommands.contains(cmdClassName)) {
return true;
}
}
return false;
}
private String[] getPluggableServicesApiConfigs(){
private String[] getPluggableServicesApiConfigs() {
List<String> pluggableServicesApiConfigs = new ArrayList<String>();
ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name);
List<PluggableService> services = locator.getAllPluggableServices();
for(PluggableService service : services){
for (PluggableService service : services) {
pluggableServicesApiConfigs.add(service.getPropertiesFile());
}
return pluggableServicesApiConfigs.toArray(new String[0]);
}
private void processConfigFiles(String[] apiConfig, boolean pluggableServicesConfig){
try{
if(_apiCommands == null){
private void processConfigFiles(String[] apiConfig, boolean pluggableServicesConfig) {
try {
if (_apiCommands == null) {
_apiCommands = new Properties();
}
Properties preProcessedCommands = new Properties();
if (apiConfig != null) {
for (String configFile : apiConfig) {
File commandsFile = PropertiesUtil.findConfigFile(configFile);
if(commandsFile != null){
try{
if (commandsFile != null) {
try {
preProcessedCommands.load(new FileInputStream(commandsFile));
}catch (FileNotFoundException fnfex) {
//in case of a file within a jar in classpath, try to open stream using url
} catch (FileNotFoundException fnfex) {
// in case of a file within a jar in classpath, try to open stream using url
InputStream stream = PropertiesUtil.openStreamFromURL(configFile);
if(stream != null){
if (stream != null) {
preProcessedCommands.load(stream);
}else{
} else {
s_logger.error("Unable to find properites file", fnfex);
}
}
@ -221,7 +222,7 @@ public class ApiServer implements HttpRequestHandler {
String[] commandParts = preProcessedCommand.split(";");
_apiCommands.put(key, commandParts[0]);
if(pluggableServicesConfig){
if (pluggableServicesConfig) {
s_pluggableServiceCommands.add(commandParts[0]);
}
@ -263,7 +264,7 @@ public class ApiServer implements HttpRequestHandler {
BaseListCmd.configure();
processConfigFiles(apiConfig, false);
//get commands for all pluggable services
// get commands for all pluggable services
String[] pluggableServicesApiConfigs = getPluggableServicesApiConfigs();
processConfigFiles(pluggableServicesApiConfigs, true);
@ -333,7 +334,8 @@ public class ApiServer implements HttpRequestHandler {
if ("response".equalsIgnoreCase(paramValue[0])) {
responseType = paramValue[1];
} else {
// according to the servlet spec, the parameter map should be in the form (name=String, value=String[]), so
// according to the servlet spec, the parameter map should be in the form (name=String,
// value=String[]), so
// parameter values will be stored in an array
parameterMap.put(/* name */paramValue[0], /* value */new String[] { paramValue[1] });
}
@ -557,10 +559,13 @@ public class ApiServer implements HttpRequestHandler {
auditTrailSb.append(" " + HttpServletResponse.SC_OK + " ");
auditTrailSb.append(result);
/*
* if (command.equals("queryAsyncJobResult")){ //For this command we need to also log job status and job resultcode for
* if (command.equals("queryAsyncJobResult")){ //For this command we need to also log job status and job
* resultcode for
* (Pair<String,Object> pair : resultValues){ String key = pair.first(); if (key.equals("jobstatus")){
* auditTrailSb.append(" "); auditTrailSb.append(key); auditTrailSb.append("="); auditTrailSb.append(pair.second());
* }else if (key.equals("jobresultcode")){ auditTrailSb.append(" "); auditTrailSb.append(key); auditTrailSb.append("=");
* auditTrailSb.append(" "); auditTrailSb.append(key); auditTrailSb.append("=");
* auditTrailSb.append(pair.second());
* }else if (key.equals("jobresultcode")){ auditTrailSb.append(" "); auditTrailSb.append(key);
* auditTrailSb.append("=");
* auditTrailSb.append(pair.second()); } } }else { for (Pair<String,Object> pair : resultValues){ if
* (pair.first().equals("jobid")){ // Its an async job so report the jobid auditTrailSb.append(" ");
* auditTrailSb.append(pair.first()); auditTrailSb.append("="); auditTrailSb.append(pair.second()); } } }
@ -653,22 +658,22 @@ public class ApiServer implements HttpRequestHandler {
}
Date expiresTS = null;
if("3".equals(signatureVersion)){
if ("3".equals(signatureVersion)) {
// New signature authentication. Check for expire parameter and its validity
if(expires == null){
if (expires == null) {
s_logger.info("missing Expires parameter -- ignoring request...sig: " + signature + ", apiKey: " + apiKey);
return false;
}
synchronized (_dateFormat) {
try{
try {
expiresTS = _dateFormat.parse(expires);
} catch (ParseException pe){
} catch (ParseException pe) {
s_logger.info("Incorrect date format for Expires parameter", pe);
return false;
}
}
Date now = new Date(System.currentTimeMillis());
if(expiresTS.before(now)){
if (expiresTS.before(now)) {
s_logger.info("Request expired -- ignoring ...sig: " + signature + ", apiKey: " + apiKey);
return false;
}
@ -861,7 +866,8 @@ public class ApiServer implements HttpRequestHandler {
// FIXME: the following two threads are copied from
// http://svn.apache.org/repos/asf/httpcomponents/httpcore/trunk/httpcore/src/examples/org/apache/http/examples/ElementalHttpServer.java
// we have to cite a license if we are using this code directly, so we need to add the appropriate citation or modify the
// we have to cite a license if we are using this code directly, so we need to add the appropriate citation or
// modify the
// code to be very specific to our needs
static class ListenerThread extends Thread {
private HttpService _httpService = null;
@ -971,9 +977,9 @@ public class ApiServer implements HttpRequestHandler {
responseName = "errorresponse";
} else {
Object cmdObj = apiCommandParams.get("command");
//cmd name can be null when "command" parameter is missing in the request
// cmd name can be null when "command" parameter is missing in the request
if (cmdObj != null) {
String cmdName = ((String[])cmdObj) [0];
String cmdName = ((String[]) cmdObj)[0];
cmdClassName = _apiCommands.getProperty(cmdName);
if (cmdClassName != null) {
Class<?> claz = Class.forName(cmdClassName);

Some files were not shown because too many files have changed in this diff Show More