mirror of https://github.com/apache/cloudstack.git
bug 9336: securityGroups can be used by other securityGroups in the same domain only; no cross domain SG authentication
status 9336: resolved fixed Following changes were made: * deleteSecurityGroup/authorizeSecurityGroupIngress - removed account/domainId parameters as SG is uniquely identified by id now * removed account_name field from securityGroup DB table; removed allowed_security_group/allowed_sec_grp_acct from security_ingress_rule. These values were used for api response generation only for performance purposes; added caching on API level to improve performance * Added missing security checks for securityGroups/ingressRules
This commit is contained in:
parent
09b4b06b63
commit
41e5e38fef
|
|
@ -37,67 +37,53 @@ import com.cloud.api.response.SecurityGroupResponse;
|
|||
import com.cloud.async.AsyncJob;
|
||||
import com.cloud.event.EventTypes;
|
||||
import com.cloud.network.security.IngressRule;
|
||||
import com.cloud.network.security.SecurityGroup;
|
||||
import com.cloud.user.Account;
|
||||
import com.cloud.user.UserContext;
|
||||
import com.cloud.utils.StringUtils;
|
||||
|
||||
@Implementation(responseObject=IngressRuleResponse.class, description="Authorizes a particular ingress rule for this security group") @SuppressWarnings("rawtypes")
|
||||
@Implementation(responseObject = IngressRuleResponse.class, description = "Authorizes a particular ingress rule for this security group")
|
||||
@SuppressWarnings("rawtypes")
|
||||
public class AuthorizeSecurityGroupIngressCmd extends BaseAsyncCmd {
|
||||
public static final Logger s_logger = Logger.getLogger(AuthorizeSecurityGroupIngressCmd.class.getName());
|
||||
public static final Logger s_logger = Logger.getLogger(AuthorizeSecurityGroupIngressCmd.class.getName());
|
||||
|
||||
private static final String s_name = "authorizesecuritygroupingress";
|
||||
|
||||
/////////////////////////////////////////////////////
|
||||
//////////////// API parameters /////////////////////
|
||||
/////////////////////////////////////////////////////
|
||||
// ///////////////////////////////////////////////////
|
||||
// ////////////// API parameters /////////////////////
|
||||
// ///////////////////////////////////////////////////
|
||||
|
||||
@Parameter(name=ApiConstants.PROTOCOL, type=CommandType.STRING, description="TCP is default. UDP is the other supported protocol")
|
||||
@Parameter(name = ApiConstants.PROTOCOL, type = CommandType.STRING, description = "TCP is default. UDP is the other supported protocol")
|
||||
private String protocol;
|
||||
|
||||
@Parameter(name=ApiConstants.START_PORT, type=CommandType.INTEGER, description="start port for this ingress rule")
|
||||
@Parameter(name = ApiConstants.START_PORT, type = CommandType.INTEGER, description = "start port for this ingress rule")
|
||||
private Integer startPort;
|
||||
|
||||
@Parameter(name=ApiConstants.END_PORT, type=CommandType.INTEGER, description="end port for this ingress rule")
|
||||
@Parameter(name = ApiConstants.END_PORT, type = CommandType.INTEGER, description = "end port for this ingress rule")
|
||||
private Integer endPort;
|
||||
|
||||
@Parameter(name=ApiConstants.ICMP_TYPE, type=CommandType.INTEGER, description="type of the icmp message being sent")
|
||||
@Parameter(name = ApiConstants.ICMP_TYPE, type = CommandType.INTEGER, description = "type of the icmp message being sent")
|
||||
private Integer icmpType;
|
||||
|
||||
@Parameter(name=ApiConstants.ICMP_CODE, type=CommandType.INTEGER, description="error code for this icmp message")
|
||||
@Parameter(name = ApiConstants.ICMP_CODE, type = CommandType.INTEGER, description = "error code for this icmp message")
|
||||
private Integer icmpCode;
|
||||
|
||||
@Parameter(name=ApiConstants.SECURITY_GROUP_ID, type=CommandType.LONG, required=true, description="The ID of the security group")
|
||||
@Parameter(name = ApiConstants.SECURITY_GROUP_ID, type = CommandType.LONG, required = true, description = "The ID of the security group")
|
||||
private Long securityGroupId;
|
||||
|
||||
@Parameter(name=ApiConstants.CIDR_LIST, type=CommandType.LIST, collectionType=CommandType.STRING, description="the cidr list associated")
|
||||
private List cidrList;
|
||||
@Parameter(name = ApiConstants.CIDR_LIST, type = CommandType.LIST, collectionType = CommandType.STRING, description = "the cidr list associated")
|
||||
private List<String> cidrList;
|
||||
|
||||
@Parameter(name=ApiConstants.USER_SECURITY_GROUP_LIST, type=CommandType.MAP, description="user to security group mapping")
|
||||
@Parameter(name = ApiConstants.USER_SECURITY_GROUP_LIST, type = CommandType.MAP, description = "user to security group mapping")
|
||||
private Map userSecurityGroupList;
|
||||
|
||||
@Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for the security group. Must be used with domainId.")
|
||||
private String accountName;
|
||||
// ///////////////////////////////////////////////////
|
||||
// ///////////////// Accessors ///////////////////////
|
||||
// ///////////////////////////////////////////////////
|
||||
|
||||
@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;
|
||||
|
||||
|
||||
/////////////////////////////////////////////////////
|
||||
/////////////////// Accessors ///////////////////////
|
||||
/////////////////////////////////////////////////////
|
||||
|
||||
public String getAccountName() {
|
||||
return accountName;
|
||||
}
|
||||
|
||||
public List getCidrList() {
|
||||
public List<String> getCidrList() {
|
||||
return cidrList;
|
||||
}
|
||||
|
||||
public Long getDomainId() {
|
||||
return domainId;
|
||||
}
|
||||
|
||||
public Integer getEndPort() {
|
||||
return endPort;
|
||||
}
|
||||
|
|
@ -129,10 +115,9 @@ public class AuthorizeSecurityGroupIngressCmd extends BaseAsyncCmd {
|
|||
return userSecurityGroupList;
|
||||
}
|
||||
|
||||
|
||||
/////////////////////////////////////////////////////
|
||||
/////////////// API Implementation///////////////////
|
||||
/////////////////////////////////////////////////////
|
||||
// ///////////////////////////////////////////////////
|
||||
// ///////////// API Implementation///////////////////
|
||||
// ///////////////////////////////////////////////////
|
||||
|
||||
@Override
|
||||
public String getCommandName() {
|
||||
|
|
@ -140,23 +125,14 @@ public class AuthorizeSecurityGroupIngressCmd extends BaseAsyncCmd {
|
|||
}
|
||||
|
||||
public static String getResultObjectName() {
|
||||
return "securitygroup";
|
||||
return "securitygroup";
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getEntityOwnerId() {
|
||||
Account account = UserContext.current().getCaller();
|
||||
if ((account == null) || isAdmin(account.getType())) {
|
||||
if ((domainId != null) && (accountName != null)) {
|
||||
Account userAccount = _responseGenerator.findAccountByNameDomain(accountName, domainId);
|
||||
if (userAccount != null) {
|
||||
return userAccount.getId();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (account != null) {
|
||||
return account.getId();
|
||||
SecurityGroup group = _entityMgr.findById(SecurityGroup.class, getSecurityGroupId());
|
||||
if (group != null) {
|
||||
return group.getAccountId();
|
||||
}
|
||||
|
||||
return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked
|
||||
|
|
@ -175,15 +151,15 @@ public class AuthorizeSecurityGroupIngressCmd extends BaseAsyncCmd {
|
|||
Collection userGroupCollection = getUserSecurityGroupList().values();
|
||||
Iterator iter = userGroupCollection.iterator();
|
||||
|
||||
HashMap userGroup = (HashMap)iter.next();
|
||||
String group = (String)userGroup.get("group");
|
||||
String authorizedAccountName = (String)userGroup.get("account");
|
||||
HashMap userGroup = (HashMap) iter.next();
|
||||
String group = (String) userGroup.get("group");
|
||||
String authorizedAccountName = (String) userGroup.get("account");
|
||||
sb.append(group + "/" + authorizedAccountName);
|
||||
|
||||
while (iter.hasNext()) {
|
||||
userGroup = (HashMap)iter.next();
|
||||
group = (String)userGroup.get("group");
|
||||
authorizedAccountName = (String)userGroup.get("account");
|
||||
userGroup = (HashMap) iter.next();
|
||||
group = (String) userGroup.get("group");
|
||||
authorizedAccountName = (String) userGroup.get("account");
|
||||
sb.append(", " + group + "/" + authorizedAccountName);
|
||||
}
|
||||
} else if (getCidrList() != null) {
|
||||
|
|
@ -193,26 +169,26 @@ public class AuthorizeSecurityGroupIngressCmd extends BaseAsyncCmd {
|
|||
sb.append("<error: no ingress parameters>");
|
||||
}
|
||||
|
||||
return "authorizing ingress to group: " + getSecurityGroupId() + " to " + sb.toString();
|
||||
return "authorizing ingress to group: " + getSecurityGroupId() + " to " + sb.toString();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void execute(){
|
||||
public void execute() {
|
||||
List<? extends IngressRule> ingressRules = _securityGroupService.authorizeSecurityGroupIngress(this);
|
||||
if (ingressRules != null && ! ingressRules.isEmpty()) {
|
||||
SecurityGroupResponse response = _responseGenerator.createSecurityGroupResponseFromIngressRule(ingressRules);
|
||||
if (ingressRules != null && !ingressRules.isEmpty()) {
|
||||
SecurityGroupResponse response = _responseGenerator.createSecurityGroupResponseFromIngressRule(ingressRules);
|
||||
this.setResponseObject(response);
|
||||
} else {
|
||||
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to authorize security group ingress rule(s)");
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public AsyncJob.Type getInstanceType() {
|
||||
return AsyncJob.Type.SecurityGroup;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Long getInstanceId() {
|
||||
return getSecurityGroupId();
|
||||
|
|
|
|||
|
|
@ -16,89 +16,72 @@
|
|||
*
|
||||
*/
|
||||
|
||||
package com.cloud.api.commands;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
import com.cloud.api.ApiConstants;
|
||||
import com.cloud.api.BaseCmd;
|
||||
import com.cloud.api.Implementation;
|
||||
import com.cloud.api.Parameter;
|
||||
import com.cloud.api.ServerApiException;
|
||||
import com.cloud.api.response.SuccessResponse;
|
||||
import com.cloud.exception.ResourceInUseException;
|
||||
import com.cloud.network.security.SecurityGroup;
|
||||
import com.cloud.user.Account;
|
||||
|
||||
@Implementation(description="Deletes security group", responseObject=SuccessResponse.class)
|
||||
public class DeleteSecurityGroupCmd extends BaseCmd {
|
||||
public static final Logger s_logger = Logger.getLogger(DeleteSecurityGroupCmd.class.getName());
|
||||
private static final String s_name = "deletesecuritygroupresponse";
|
||||
|
||||
/////////////////////////////////////////////////////
|
||||
//////////////// API parameters /////////////////////
|
||||
/////////////////////////////////////////////////////
|
||||
|
||||
@Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="the account of the security group. Must be specified with domain ID")
|
||||
private String accountName;
|
||||
|
||||
@Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the domain ID of account owning the security group")
|
||||
private Long domainId;
|
||||
|
||||
@Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the security group")
|
||||
private Long id;
|
||||
|
||||
|
||||
/////////////////////////////////////////////////////
|
||||
/////////////////// Accessors ///////////////////////
|
||||
/////////////////////////////////////////////////////
|
||||
|
||||
public String getAccountName() {
|
||||
return accountName;
|
||||
}
|
||||
|
||||
public Long getDomainId() {
|
||||
return domainId;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/////////////////////////////////////////////////////
|
||||
/////////////// API Implementation///////////////////
|
||||
/////////////////////////////////////////////////////
|
||||
|
||||
@Override
|
||||
public String getCommandName() {
|
||||
return s_name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getEntityOwnerId() {
|
||||
SecurityGroup group = _entityMgr.findById(SecurityGroup.class, getId());
|
||||
if (group != null) {
|
||||
return group.getAccountId();
|
||||
}
|
||||
|
||||
return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(){
|
||||
try{
|
||||
boolean result = _securityGroupService.deleteSecurityGroup(this);
|
||||
if (result) {
|
||||
SuccessResponse response = new SuccessResponse(getCommandName());
|
||||
this.setResponseObject(response);
|
||||
} else {
|
||||
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete security group");
|
||||
}
|
||||
} catch (ResourceInUseException ex) {
|
||||
s_logger.warn("Exception: ", ex);
|
||||
throw new ServerApiException(BaseCmd.RESOURCE_IN_USE_ERROR, ex.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
package com.cloud.api.commands;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
import com.cloud.api.ApiConstants;
|
||||
import com.cloud.api.BaseCmd;
|
||||
import com.cloud.api.Implementation;
|
||||
import com.cloud.api.Parameter;
|
||||
import com.cloud.api.ServerApiException;
|
||||
import com.cloud.api.response.SuccessResponse;
|
||||
import com.cloud.exception.ResourceInUseException;
|
||||
import com.cloud.network.security.SecurityGroup;
|
||||
import com.cloud.user.Account;
|
||||
|
||||
@Implementation(description = "Deletes security group", responseObject = SuccessResponse.class)
|
||||
public class DeleteSecurityGroupCmd extends BaseCmd {
|
||||
public static final Logger s_logger = Logger.getLogger(DeleteSecurityGroupCmd.class.getName());
|
||||
private static final String s_name = "deletesecuritygroupresponse";
|
||||
|
||||
// ///////////////////////////////////////////////////
|
||||
// ////////////// API parameters /////////////////////
|
||||
// ///////////////////////////////////////////////////
|
||||
|
||||
@Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "The ID of the security group")
|
||||
private Long id;
|
||||
|
||||
// ///////////////////////////////////////////////////
|
||||
// ///////////////// Accessors ///////////////////////
|
||||
// ///////////////////////////////////////////////////
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
// ///////////////////////////////////////////////////
|
||||
// ///////////// API Implementation///////////////////
|
||||
// ///////////////////////////////////////////////////
|
||||
|
||||
@Override
|
||||
public String getCommandName() {
|
||||
return s_name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getEntityOwnerId() {
|
||||
SecurityGroup group = _entityMgr.findById(SecurityGroup.class, getId());
|
||||
if (group != null) {
|
||||
return group.getAccountId();
|
||||
}
|
||||
|
||||
return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute() {
|
||||
try {
|
||||
boolean result = _securityGroupService.deleteSecurityGroup(this);
|
||||
if (result) {
|
||||
SuccessResponse response = new SuccessResponse(getCommandName());
|
||||
this.setResponseObject(response);
|
||||
} else {
|
||||
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete security group");
|
||||
}
|
||||
} catch (ResourceInUseException ex) {
|
||||
s_logger.warn("Exception: ", ex);
|
||||
throw new ServerApiException(BaseCmd.RESOURCE_IN_USE_ERROR, ex.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,117 +16,94 @@
|
|||
*
|
||||
*/
|
||||
|
||||
package com.cloud.api.commands;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
import com.cloud.api.ApiConstants;
|
||||
import com.cloud.api.BaseAsyncCmd;
|
||||
import com.cloud.api.BaseCmd;
|
||||
import com.cloud.api.Implementation;
|
||||
import com.cloud.api.Parameter;
|
||||
import com.cloud.api.ServerApiException;
|
||||
import com.cloud.api.response.SuccessResponse;
|
||||
import com.cloud.async.AsyncJob;
|
||||
import com.cloud.event.EventTypes;
|
||||
import com.cloud.user.Account;
|
||||
import com.cloud.user.UserContext;
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
@Implementation(responseObject=SuccessResponse.class, description="Deletes a particular ingress rule from this security group")
|
||||
public class RevokeSecurityGroupIngressCmd extends BaseAsyncCmd {
|
||||
public static final Logger s_logger = Logger.getLogger(RevokeSecurityGroupIngressCmd.class.getName());
|
||||
|
||||
private static final String s_name = "revokesecuritygroupingress";
|
||||
|
||||
/////////////////////////////////////////////////////
|
||||
//////////////// API parameters /////////////////////
|
||||
/////////////////////////////////////////////////////
|
||||
|
||||
@Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for the security group. Must be used with domainId.")
|
||||
private String accountName;
|
||||
|
||||
@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.ID, type=CommandType.LONG, required=true, description="The ID of the ingress rule")
|
||||
private Long id;
|
||||
|
||||
/////////////////////////////////////////////////////
|
||||
/////////////////// Accessors ///////////////////////
|
||||
/////////////////////////////////////////////////////
|
||||
|
||||
public String getAccountName() {
|
||||
return accountName;
|
||||
}
|
||||
|
||||
public Long getDomainId() {
|
||||
return domainId;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
/////////////////////////////////////////////////////
|
||||
/////////////// API Implementation///////////////////
|
||||
/////////////////////////////////////////////////////
|
||||
|
||||
@Override
|
||||
public String getCommandName() {
|
||||
return s_name;
|
||||
}
|
||||
|
||||
public static String getResultObjectName() {
|
||||
return "revokesecuritygroupingress";
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getEntityOwnerId() {
|
||||
Account account = UserContext.current().getCaller();
|
||||
if ((account == null) || isAdmin(account.getType())) {
|
||||
if ((domainId != null) && (accountName != null)) {
|
||||
Account userAccount = _responseGenerator.findAccountByNameDomain(accountName, domainId);
|
||||
if (userAccount != null) {
|
||||
return userAccount.getId();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (account != null) {
|
||||
return account.getId();
|
||||
}
|
||||
|
||||
return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getEventType() {
|
||||
return EventTypes.EVENT_SECURITY_GROUP_REVOKE_INGRESS;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getEventDescription() {
|
||||
return "revoking ingress rule id: " + getId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(){
|
||||
boolean result = _securityGroupService.revokeSecurityGroupIngress(this);
|
||||
if (result) {
|
||||
SuccessResponse response = new SuccessResponse(getCommandName());
|
||||
this.setResponseObject(response);
|
||||
} else {
|
||||
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to revoke security group ingress rule");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public AsyncJob.Type getInstanceType() {
|
||||
return AsyncJob.Type.SecurityGroup;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long getInstanceId() {
|
||||
return getId();
|
||||
}
|
||||
}
|
||||
package com.cloud.api.commands;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
import com.cloud.api.ApiConstants;
|
||||
import com.cloud.api.BaseAsyncCmd;
|
||||
import com.cloud.api.BaseCmd;
|
||||
import com.cloud.api.Implementation;
|
||||
import com.cloud.api.Parameter;
|
||||
import com.cloud.api.ServerApiException;
|
||||
import com.cloud.api.response.SuccessResponse;
|
||||
import com.cloud.async.AsyncJob;
|
||||
import com.cloud.event.EventTypes;
|
||||
import com.cloud.network.security.SecurityGroup;
|
||||
import com.cloud.user.Account;
|
||||
|
||||
@Implementation(responseObject = SuccessResponse.class, description = "Deletes a particular ingress rule from this security group")
|
||||
public class RevokeSecurityGroupIngressCmd extends BaseAsyncCmd {
|
||||
public static final Logger s_logger = Logger.getLogger(RevokeSecurityGroupIngressCmd.class.getName());
|
||||
|
||||
private static final String s_name = "revokesecuritygroupingress";
|
||||
|
||||
// ///////////////////////////////////////////////////
|
||||
// ////////////// API parameters /////////////////////
|
||||
// ///////////////////////////////////////////////////
|
||||
|
||||
@Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "The ID of the ingress rule")
|
||||
private Long id;
|
||||
|
||||
// ///////////////////////////////////////////////////
|
||||
// ///////////////// Accessors ///////////////////////
|
||||
// ///////////////////////////////////////////////////
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
// ///////////////////////////////////////////////////
|
||||
// ///////////// API Implementation///////////////////
|
||||
// ///////////////////////////////////////////////////
|
||||
|
||||
@Override
|
||||
public String getCommandName() {
|
||||
return s_name;
|
||||
}
|
||||
|
||||
public static String getResultObjectName() {
|
||||
return "revokesecuritygroupingress";
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getEntityOwnerId() {
|
||||
SecurityGroup group = _entityMgr.findById(SecurityGroup.class, getId());
|
||||
if (group != null) {
|
||||
return group.getAccountId();
|
||||
}
|
||||
|
||||
return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getEventType() {
|
||||
return EventTypes.EVENT_SECURITY_GROUP_REVOKE_INGRESS;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getEventDescription() {
|
||||
return "revoking ingress rule id: " + getId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute() {
|
||||
boolean result = _securityGroupService.revokeSecurityGroupIngress(this);
|
||||
if (result) {
|
||||
SuccessResponse response = new SuccessResponse(getCommandName());
|
||||
this.setResponseObject(response);
|
||||
} else {
|
||||
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to revoke security group ingress rule");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public AsyncJob.Type getInstanceType() {
|
||||
return AsyncJob.Type.SecurityGroup;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long getInstanceId() {
|
||||
return getId();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,18 +21,23 @@ import com.cloud.async.AsyncInstanceCreateStatus;
|
|||
|
||||
/**
|
||||
* @author ahuang
|
||||
*
|
||||
*
|
||||
*/
|
||||
public interface IngressRule {
|
||||
long getId();
|
||||
|
||||
long getSecurityGroupId();
|
||||
|
||||
int getStartPort();
|
||||
|
||||
int getEndPort();
|
||||
|
||||
String getProtocol();
|
||||
|
||||
AsyncInstanceCreateStatus getCreateStatus();
|
||||
|
||||
Long getAllowedNetworkId();
|
||||
String getAllowedSecurityGroup();
|
||||
String getAllowedSecGrpAcct();
|
||||
|
||||
String getAllowedSourceIpCidr();
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,12 +17,13 @@
|
|||
*/
|
||||
package com.cloud.network.security;
|
||||
|
||||
import com.cloud.domain.PartOf;
|
||||
import com.cloud.user.OwnedBy;
|
||||
import com.cloud.acl.ControlledEntity;
|
||||
|
||||
public interface SecurityGroup extends PartOf, OwnedBy {
|
||||
public interface SecurityGroup extends ControlledEntity {
|
||||
long getId();
|
||||
|
||||
String getName();
|
||||
|
||||
String getDescription();
|
||||
String getAccountName();
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,8 +28,6 @@ public interface SecurityGroupRules {
|
|||
|
||||
Long getAccountId();
|
||||
|
||||
String getAccountName();
|
||||
|
||||
Long getRuleId();
|
||||
|
||||
int getStartPort();
|
||||
|
|
@ -40,9 +38,5 @@ public interface SecurityGroupRules {
|
|||
|
||||
Long getAllowedNetworkId();
|
||||
|
||||
String getAllowedSecurityGroup();
|
||||
|
||||
String getAllowedSecGrpAcct();
|
||||
|
||||
String getAllowedSourceIpCidr();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,8 +16,8 @@
|
|||
*
|
||||
*/
|
||||
|
||||
package com.cloud.network.security;
|
||||
|
||||
package com.cloud.network.security;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.EnumType;
|
||||
|
|
@ -29,115 +29,98 @@ import javax.persistence.Table;
|
|||
|
||||
import com.cloud.async.AsyncInstanceCreateStatus;
|
||||
import com.google.gson.annotations.Expose;
|
||||
|
||||
@Entity
|
||||
@Table(name=("security_ingress_rule"))
|
||||
public class IngressRuleVO implements IngressRule {
|
||||
@Id
|
||||
@GeneratedValue(strategy=GenerationType.IDENTITY)
|
||||
@Column(name="id")
|
||||
private long id;
|
||||
|
||||
@Column(name="security_group_id")
|
||||
private long securityGroupId;
|
||||
|
||||
@Column(name="start_port")
|
||||
private int startPort;
|
||||
|
||||
@Column(name="end_port")
|
||||
private int endPort;
|
||||
|
||||
@Column(name="protocol")
|
||||
|
||||
@Entity
|
||||
@Table(name = ("security_ingress_rule"))
|
||||
public class IngressRuleVO implements IngressRule {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "id")
|
||||
private long id;
|
||||
|
||||
@Column(name = "security_group_id")
|
||||
private long securityGroupId;
|
||||
|
||||
@Column(name = "start_port")
|
||||
private int startPort;
|
||||
|
||||
@Column(name = "end_port")
|
||||
private int endPort;
|
||||
|
||||
@Column(name = "protocol")
|
||||
private String protocol;
|
||||
|
||||
@Column(name="allowed_network_id", nullable=true)
|
||||
|
||||
@Column(name = "allowed_network_id", nullable = true)
|
||||
private Long allowedNetworkId = null;
|
||||
|
||||
@Column(name="allowed_security_group")
|
||||
private String allowedSecurityGroup;
|
||||
|
||||
@Column(name="allowed_sec_grp_acct")
|
||||
private String allowedSecGrpAcct;
|
||||
|
||||
@Column(name="allowed_ip_cidr", nullable=true)
|
||||
@Column(name = "allowed_ip_cidr", nullable = true)
|
||||
private String allowedSourceIpCidr = null;
|
||||
|
||||
@Expose
|
||||
@Column(name="create_status", updatable = true, nullable=false)
|
||||
@Enumerated(value=EnumType.STRING)
|
||||
private AsyncInstanceCreateStatus createStatus;
|
||||
|
||||
public IngressRuleVO() {}
|
||||
|
||||
public IngressRuleVO(long securityGroupId, int fromPort, int toPort, String protocol, long allowedNetworkId, String allowedSecurityGroup, String allowedSecGrpAcct) {
|
||||
this.securityGroupId = securityGroupId;
|
||||
this.startPort = fromPort;
|
||||
this.endPort = toPort;
|
||||
this.protocol = protocol;
|
||||
this.allowedNetworkId = allowedNetworkId;
|
||||
this.allowedSecurityGroup = allowedSecurityGroup;
|
||||
this.allowedSecGrpAcct = allowedSecGrpAcct;
|
||||
|
||||
@Expose
|
||||
@Column(name = "create_status", updatable = true, nullable = false)
|
||||
@Enumerated(value = EnumType.STRING)
|
||||
private AsyncInstanceCreateStatus createStatus;
|
||||
|
||||
public IngressRuleVO() {
|
||||
}
|
||||
|
||||
|
||||
public IngressRuleVO(long securityGroupId, int fromPort, int toPort, String protocol, long allowedNetworkId) {
|
||||
this.securityGroupId = securityGroupId;
|
||||
this.startPort = fromPort;
|
||||
this.endPort = toPort;
|
||||
this.protocol = protocol;
|
||||
this.allowedNetworkId = allowedNetworkId;
|
||||
}
|
||||
|
||||
public IngressRuleVO(long securityGroupId, int fromPort, int toPort, String protocol, String allowedIpCidr) {
|
||||
this.securityGroupId = securityGroupId;
|
||||
this.startPort = fromPort;
|
||||
this.endPort = toPort;
|
||||
this.protocol = protocol;
|
||||
this.allowedSourceIpCidr = allowedIpCidr;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getSecurityGroupId() {
|
||||
return securityGroupId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getStartPort() {
|
||||
return startPort;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getEndPort() {
|
||||
return endPort;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getProtocol() {
|
||||
return protocol;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AsyncInstanceCreateStatus getCreateStatus() {
|
||||
return createStatus;
|
||||
}
|
||||
|
||||
public void setCreateStatus(AsyncInstanceCreateStatus createStatus) {
|
||||
this.createStatus = createStatus;
|
||||
this.allowedSourceIpCidr = allowedIpCidr;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Override
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getSecurityGroupId() {
|
||||
return securityGroupId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getStartPort() {
|
||||
return startPort;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getEndPort() {
|
||||
return endPort;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getProtocol() {
|
||||
return protocol;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AsyncInstanceCreateStatus getCreateStatus() {
|
||||
return createStatus;
|
||||
}
|
||||
|
||||
public void setCreateStatus(AsyncInstanceCreateStatus createStatus) {
|
||||
this.createStatus = createStatus;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long getAllowedNetworkId() {
|
||||
return allowedNetworkId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAllowedSecurityGroup() {
|
||||
return allowedSecurityGroup;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAllowedSecGrpAcct() {
|
||||
return allowedSecGrpAcct;
|
||||
return allowedNetworkId;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Override
|
||||
public String getAllowedSourceIpCidr() {
|
||||
return allowedSourceIpCidr;
|
||||
}
|
||||
}
|
||||
return allowedSourceIpCidr;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,138 +16,126 @@
|
|||
*
|
||||
*/
|
||||
|
||||
package com.cloud.network.security;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.PrimaryKeyJoinColumn;
|
||||
import javax.persistence.SecondaryTable;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name=("security_group"))
|
||||
@SecondaryTable(name="security_ingress_rule", join="left",
|
||||
pkJoinColumns={@PrimaryKeyJoinColumn(name="id", referencedColumnName="security_group_id")})
|
||||
public class SecurityGroupRulesVO implements SecurityGroupRules {
|
||||
@Id
|
||||
@GeneratedValue(strategy=GenerationType.IDENTITY)
|
||||
@Column(name="id")
|
||||
private long id;
|
||||
|
||||
@Column(name="name")
|
||||
private String name;
|
||||
|
||||
@Column(name="description")
|
||||
private String description;
|
||||
|
||||
@Column(name="domain_id")
|
||||
private Long domainId;
|
||||
|
||||
@Column(name="account_id")
|
||||
private Long accountId;
|
||||
|
||||
@Column(name="account_name")
|
||||
private String accountName;
|
||||
|
||||
@Column(name="id", table="security_ingress_rule", insertable=false, updatable=false)
|
||||
private Long ruleId;
|
||||
|
||||
@Column(name="start_port", table="security_ingress_rule", insertable=false, updatable=false)
|
||||
private int startPort;
|
||||
|
||||
@Column(name="end_port", table="security_ingress_rule", insertable=false, updatable=false)
|
||||
private int endPort;
|
||||
|
||||
@Column(name="protocol", table="security_ingress_rule", insertable=false, updatable=false)
|
||||
private String protocol;
|
||||
|
||||
@Column(name="allowed_network_id", table="security_ingress_rule", insertable=false, updatable=false, nullable=true)
|
||||
private Long allowedNetworkId = null;
|
||||
|
||||
@Column(name="allowed_security_group", table="security_ingress_rule", insertable=false, updatable=false, nullable=true)
|
||||
private String allowedSecurityGroup = null;
|
||||
|
||||
@Column(name="allowed_sec_grp_acct", table="security_ingress_rule", insertable=false, updatable=false, nullable=true)
|
||||
private String allowedSecGrpAcct = null;
|
||||
|
||||
@Column(name="allowed_ip_cidr", table="security_ingress_rule", insertable=false, updatable=false, nullable=true)
|
||||
private String allowedSourceIpCidr = null;
|
||||
|
||||
public SecurityGroupRulesVO() { }
|
||||
|
||||
public SecurityGroupRulesVO(long id, String name, String description, Long domainId, Long accountId, String accountName, Long ruleId, int startPort, int endPort, String protocol, Long allowedNetworkId, String allowedSecurityGroup, String allowedSecGrpAcct, String allowedSourceIpCidr) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
this.domainId = domainId;
|
||||
this.accountId = accountId;
|
||||
this.accountName = accountName;
|
||||
this.ruleId = ruleId;
|
||||
this.startPort = startPort;
|
||||
this.endPort = endPort;
|
||||
this.protocol = protocol;
|
||||
this.allowedNetworkId = allowedNetworkId;
|
||||
this.allowedSecurityGroup = allowedSecurityGroup;
|
||||
this.allowedSecGrpAcct = allowedSecGrpAcct;
|
||||
this.allowedSourceIpCidr = allowedSourceIpCidr;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public Long getDomainId() {
|
||||
return domainId;
|
||||
}
|
||||
|
||||
public Long getAccountId() {
|
||||
return accountId;
|
||||
}
|
||||
|
||||
public String getAccountName() {
|
||||
return accountName;
|
||||
}
|
||||
|
||||
public Long getRuleId() {
|
||||
return ruleId;
|
||||
}
|
||||
|
||||
public int getStartPort() {
|
||||
return startPort;
|
||||
}
|
||||
|
||||
public int getEndPort() {
|
||||
return endPort;
|
||||
}
|
||||
|
||||
public String getProtocol() {
|
||||
return protocol;
|
||||
}
|
||||
|
||||
public Long getAllowedNetworkId() {
|
||||
return allowedNetworkId;
|
||||
}
|
||||
|
||||
public String getAllowedSecurityGroup() {
|
||||
return allowedSecurityGroup;
|
||||
}
|
||||
|
||||
public String getAllowedSecGrpAcct() {
|
||||
return allowedSecGrpAcct;
|
||||
}
|
||||
|
||||
public String getAllowedSourceIpCidr() {
|
||||
return allowedSourceIpCidr;
|
||||
}
|
||||
}
|
||||
package com.cloud.network.security;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.PrimaryKeyJoinColumn;
|
||||
import javax.persistence.SecondaryTable;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = ("security_group"))
|
||||
@SecondaryTable(name = "security_ingress_rule", join = "left", pkJoinColumns = { @PrimaryKeyJoinColumn(name = "id", referencedColumnName = "security_group_id") })
|
||||
public class SecurityGroupRulesVO implements SecurityGroupRules {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "id")
|
||||
private long id;
|
||||
|
||||
@Column(name = "name")
|
||||
private String name;
|
||||
|
||||
@Column(name = "description")
|
||||
private String description;
|
||||
|
||||
@Column(name = "domain_id")
|
||||
private Long domainId;
|
||||
|
||||
@Column(name = "account_id")
|
||||
private Long accountId;
|
||||
|
||||
@Column(name = "id", table = "security_ingress_rule", insertable = false, updatable = false)
|
||||
private Long ruleId;
|
||||
|
||||
@Column(name = "start_port", table = "security_ingress_rule", insertable = false, updatable = false)
|
||||
private int startPort;
|
||||
|
||||
@Column(name = "end_port", table = "security_ingress_rule", insertable = false, updatable = false)
|
||||
private int endPort;
|
||||
|
||||
@Column(name = "protocol", table = "security_ingress_rule", insertable = false, updatable = false)
|
||||
private String protocol;
|
||||
|
||||
@Column(name = "allowed_network_id", table = "security_ingress_rule", insertable = false, updatable = false, nullable = true)
|
||||
private Long allowedNetworkId = null;
|
||||
|
||||
@Column(name = "allowed_ip_cidr", table = "security_ingress_rule", insertable = false, updatable = false, nullable = true)
|
||||
private String allowedSourceIpCidr = null;
|
||||
|
||||
public SecurityGroupRulesVO() {
|
||||
}
|
||||
|
||||
public SecurityGroupRulesVO(long id, String name, String description, Long domainId, Long accountId, Long ruleId, int startPort, int endPort, String protocol, Long allowedNetworkId,
|
||||
String allowedSourceIpCidr) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
this.domainId = domainId;
|
||||
this.accountId = accountId;
|
||||
this.ruleId = ruleId;
|
||||
this.startPort = startPort;
|
||||
this.endPort = endPort;
|
||||
this.protocol = protocol;
|
||||
this.allowedNetworkId = allowedNetworkId;
|
||||
this.allowedSourceIpCidr = allowedSourceIpCidr;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long getDomainId() {
|
||||
return domainId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long getAccountId() {
|
||||
return accountId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long getRuleId() {
|
||||
return ruleId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getStartPort() {
|
||||
return startPort;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getEndPort() {
|
||||
return endPort;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getProtocol() {
|
||||
return protocol;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long getAllowedNetworkId() {
|
||||
return allowedNetworkId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAllowedSourceIpCidr() {
|
||||
return allowedSourceIpCidr;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,70 +16,67 @@
|
|||
*
|
||||
*/
|
||||
|
||||
package com.cloud.network.security;
|
||||
|
||||
package com.cloud.network.security;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name=("security_group"))
|
||||
public class SecurityGroupVO implements SecurityGroup {
|
||||
@Id
|
||||
@GeneratedValue(strategy=GenerationType.IDENTITY)
|
||||
@Column(name="id")
|
||||
private long id;
|
||||
|
||||
@Column(name="name")
|
||||
private String name;
|
||||
|
||||
@Column(name="description")
|
||||
private String description;
|
||||
|
||||
@Column(name="domain_id")
|
||||
private long domainId;
|
||||
|
||||
@Column(name="account_id")
|
||||
private long accountId;
|
||||
|
||||
@Column(name="account_name")
|
||||
private String accountName = null;
|
||||
|
||||
public SecurityGroupVO() {}
|
||||
|
||||
public SecurityGroupVO(String name, String description, long domainId, long accountId, String accountName) {
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
this.domainId = domainId;
|
||||
|
||||
@Entity
|
||||
@Table(name = ("security_group"))
|
||||
public class SecurityGroupVO implements SecurityGroup {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "id")
|
||||
private long id;
|
||||
|
||||
@Column(name = "name")
|
||||
private String name;
|
||||
|
||||
@Column(name = "description")
|
||||
private String description;
|
||||
|
||||
@Column(name = "domain_id")
|
||||
private long domainId;
|
||||
|
||||
@Column(name = "account_id")
|
||||
private long accountId;
|
||||
|
||||
public SecurityGroupVO() {
|
||||
}
|
||||
|
||||
public SecurityGroupVO(String name, String description, long domainId, long accountId) {
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
this.domainId = domainId;
|
||||
this.accountId = accountId;
|
||||
this.accountName = accountName;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public long getDomainId() {
|
||||
return domainId;
|
||||
}
|
||||
|
||||
public long getAccountId() {
|
||||
return accountId;
|
||||
}
|
||||
|
||||
public String getAccountName() {
|
||||
return accountName;
|
||||
}
|
||||
}
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getDomainId() {
|
||||
return domainId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getAccountId() {
|
||||
return accountId;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -120,7 +120,7 @@ public class ApiDBUtils {
|
|||
private static AccountManager _accountMgr;
|
||||
private static AgentManager _agentMgr;
|
||||
public static AsyncJobManager _asyncMgr;
|
||||
private static SecurityGroupManager _networkGroupMgr;
|
||||
private static SecurityGroupManager _securityGroupMgr;
|
||||
private static SnapshotManager _snapMgr;
|
||||
private static StorageManager _storageMgr;
|
||||
private static UserVmManager _userVmMgr;
|
||||
|
|
@ -138,7 +138,7 @@ public class ApiDBUtils {
|
|||
private static HostDao _hostDao;
|
||||
private static IPAddressDao _ipAddressDao;
|
||||
private static LoadBalancerDao _loadBalancerDao;
|
||||
private static SecurityGroupDao _networkGroupDao;
|
||||
private static SecurityGroupDao _securityGroupDao;
|
||||
private static NetworkRuleConfigDao _networkRuleConfigDao;
|
||||
private static HostPodDao _podDao;
|
||||
private static ServiceOfferingDao _serviceOfferingDao;
|
||||
|
|
@ -158,13 +158,13 @@ public class ApiDBUtils {
|
|||
private static ConfigurationService _configMgr;
|
||||
|
||||
static {
|
||||
_ms = (ManagementServer)ComponentLocator.getComponent(ManagementServer.Name);
|
||||
_ms = (ManagementServer) ComponentLocator.getComponent(ManagementServer.Name);
|
||||
|
||||
ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name);
|
||||
_accountMgr = locator.getManager(AccountManager.class);
|
||||
_agentMgr = locator.getManager(AgentManager.class);
|
||||
_asyncMgr = locator.getManager(AsyncJobManager.class);
|
||||
_networkGroupMgr = locator.getManager(SecurityGroupManager.class);
|
||||
_securityGroupMgr = locator.getManager(SecurityGroupManager.class);
|
||||
_snapMgr = locator.getManager(SnapshotManager.class);
|
||||
_storageMgr = locator.getManager(StorageManager.class);
|
||||
_userVmMgr = locator.getManager(UserVmManager.class);
|
||||
|
|
@ -175,14 +175,14 @@ public class ApiDBUtils {
|
|||
_accountVlanMapDao = locator.getDao(AccountVlanMapDao.class);
|
||||
_clusterDao = locator.getDao(ClusterDao.class);
|
||||
_diskOfferingDao = locator.getDao(DiskOfferingDao.class);
|
||||
_domainDao = locator.getDao(DomainDao.class);
|
||||
_domainRouterDao = locator.getDao(DomainRouterDao.class);
|
||||
_domainDao = locator.getDao(DomainDao.class);
|
||||
_domainRouterDao = locator.getDao(DomainRouterDao.class);
|
||||
_guestOSDao = locator.getDao(GuestOSDao.class);
|
||||
_guestOSCategoryDao = locator.getDao(GuestOSCategoryDao.class);
|
||||
_hostDao = locator.getDao(HostDao.class);
|
||||
_ipAddressDao = locator.getDao(IPAddressDao.class);
|
||||
_loadBalancerDao = locator.getDao(LoadBalancerDao.class);
|
||||
_networkRuleConfigDao = locator.getDao(NetworkRuleConfigDao.class);
|
||||
_networkRuleConfigDao = locator.getDao(NetworkRuleConfigDao.class);
|
||||
_podDao = locator.getDao(HostPodDao.class);
|
||||
_serviceOfferingDao = locator.getDao(ServiceOfferingDao.class);
|
||||
_snapshotDao = locator.getDao(SnapshotDao.class);
|
||||
|
|
@ -196,24 +196,24 @@ public class ApiDBUtils {
|
|||
_vlanDao = locator.getDao(VlanDao.class);
|
||||
_volumeDao = locator.getDao(VolumeDao.class);
|
||||
_zoneDao = locator.getDao(DataCenterDao.class);
|
||||
_networkGroupDao = locator.getDao(SecurityGroupDao.class);
|
||||
_securityGroupDao = locator.getDao(SecurityGroupDao.class);
|
||||
_networkOfferingDao = locator.getDao(NetworkOfferingDao.class);
|
||||
_networkDao = locator.getDao(NetworkDao.class);
|
||||
|
||||
// Note: stats collector should already have been initialized by this time, otherwise a null instance is returned
|
||||
// Note: stats collector should already have been initialized by this time, otherwise a null instance is returned
|
||||
_statsCollector = StatsCollector.getInstance();
|
||||
}
|
||||
|
||||
/////////////////////////////////////////////////////////////
|
||||
// ManagementServer methods //
|
||||
/////////////////////////////////////////////////////////////
|
||||
|
||||
// ///////////////////////////////////////////////////////////
|
||||
// ManagementServer methods //
|
||||
// ///////////////////////////////////////////////////////////
|
||||
|
||||
public static VMInstanceVO findVMInstanceById(long vmId) {
|
||||
return _ms.findVMInstanceById(vmId);
|
||||
}
|
||||
|
||||
public static long getMemoryUsagebyHost(Long hostId) {
|
||||
// TODO: This method is for the API only, but it has configuration values (ramSize for system vms)
|
||||
// TODO: This method is for the API only, but it has configuration values (ramSize for system vms)
|
||||
// so if this Utils class can have some kind of config rather than a static initializer (maybe from
|
||||
// management server instantiation?) then maybe the management server method can be moved entirely
|
||||
// into this utils class.
|
||||
|
|
@ -236,9 +236,9 @@ public class ApiDBUtils {
|
|||
return _ms.searchForStoragePools(c);
|
||||
}
|
||||
|
||||
/////////////////////////////////////////////////////////////
|
||||
// Manager methods //
|
||||
/////////////////////////////////////////////////////////////
|
||||
// ///////////////////////////////////////////////////////////
|
||||
// Manager methods //
|
||||
// ///////////////////////////////////////////////////////////
|
||||
|
||||
public static long findCorrectResourceLimit(ResourceType type, long accountId) {
|
||||
AccountVO account = _accountDao.findById(accountId);
|
||||
|
|
@ -256,20 +256,20 @@ public class ApiDBUtils {
|
|||
|
||||
public static long getResourceCount(ResourceType type, long accountId) {
|
||||
AccountVO account = _accountDao.findById(accountId);
|
||||
|
||||
|
||||
if (account == null) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
return _accountMgr.getResourceCount(account, type);
|
||||
}
|
||||
|
||||
public static String getNetworkGroupsNamesForVm(long vmId) {
|
||||
return _networkGroupMgr.getSecurityGroupsNamesForVm(vmId);
|
||||
public static String getSecurityGroupsNamesForVm(long vmId) {
|
||||
return _securityGroupMgr.getSecurityGroupsNamesForVm(vmId);
|
||||
}
|
||||
|
||||
|
||||
public static List<SecurityGroupVO> getSecurityGroupsForVm(long vmId) {
|
||||
return _networkGroupMgr.getSecurityGroupsForVm(vmId);
|
||||
return _securityGroupMgr.getSecurityGroupsForVm(vmId);
|
||||
}
|
||||
|
||||
public static String getSnapshotIntervalTypes(long snapshotId) {
|
||||
|
|
@ -280,7 +280,7 @@ public class ApiDBUtils {
|
|||
public static String getStoragePoolTags(long poolId) {
|
||||
return _storageMgr.getStoragePoolTags(poolId);
|
||||
}
|
||||
|
||||
|
||||
public static boolean isLocalStorageActiveOnHost(Host host) {
|
||||
return _storageMgr.isLocalStorageActiveOnHost(host);
|
||||
}
|
||||
|
|
@ -289,9 +289,9 @@ public class ApiDBUtils {
|
|||
return _userVmMgr.getGroupForVm(vmId);
|
||||
}
|
||||
|
||||
/////////////////////////////////////////////////////////////
|
||||
// Misc methods //
|
||||
/////////////////////////////////////////////////////////////
|
||||
// ///////////////////////////////////////////////////////////
|
||||
// Misc methods //
|
||||
// ///////////////////////////////////////////////////////////
|
||||
|
||||
public static HostStats getHostStatistics(long hostId) {
|
||||
return _statsCollector.getHostStats(hostId);
|
||||
|
|
@ -304,19 +304,19 @@ public class ApiDBUtils {
|
|||
public static VmStats getVmStatistics(long hostId) {
|
||||
return _statsCollector.getVmStats(hostId);
|
||||
}
|
||||
|
||||
public static StorageStats getSecondaryStorageStatistics(long id){
|
||||
return _statsCollector.getStorageStats(id);
|
||||
|
||||
public static StorageStats getSecondaryStorageStatistics(long id) {
|
||||
return _statsCollector.getStorageStats(id);
|
||||
}
|
||||
|
||||
/////////////////////////////////////////////////////////////
|
||||
// Dao methods //
|
||||
/////////////////////////////////////////////////////////////
|
||||
// ///////////////////////////////////////////////////////////
|
||||
// Dao methods //
|
||||
// ///////////////////////////////////////////////////////////
|
||||
|
||||
public static Account findAccountById(Long accountId) {
|
||||
return _accountDao.findByIdIncludingRemoved(accountId);
|
||||
}
|
||||
|
||||
|
||||
public static Account findAccountByIdIncludingRemoved(Long accountId) {
|
||||
return _accountDao.findByIdIncludingRemoved(accountId);
|
||||
}
|
||||
|
|
@ -336,7 +336,7 @@ public class ApiDBUtils {
|
|||
public static DomainVO findDomainById(Long domainId) {
|
||||
return _domainDao.findByIdIncludingRemoved(domainId);
|
||||
}
|
||||
|
||||
|
||||
public static DomainVO findDomainByIdIncludingRemoved(Long domainId) {
|
||||
return _domainDao.findByIdIncludingRemoved(domainId);
|
||||
}
|
||||
|
|
@ -359,18 +359,17 @@ public class ApiDBUtils {
|
|||
|
||||
public static GuestOSCategoryVO getHostGuestOSCategory(long hostId) {
|
||||
Long guestOSCategoryID = _agentMgr.getGuestOSCategoryId(hostId);
|
||||
|
||||
|
||||
if (guestOSCategoryID != null) {
|
||||
return _guestOSCategoryDao.findById(guestOSCategoryID);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static String getHostTags(long hostId) {
|
||||
return _agentMgr.getHostTags(hostId);
|
||||
return _agentMgr.getHostTags(hostId);
|
||||
}
|
||||
|
||||
|
||||
public static LoadBalancerVO findLoadBalancerById(Long loadBalancerId) {
|
||||
return _loadBalancerDao.findById(loadBalancerId);
|
||||
|
|
@ -379,9 +378,9 @@ public class ApiDBUtils {
|
|||
public static NetworkRuleConfigVO findNetworkRuleById(Long ruleId) {
|
||||
return _networkRuleConfigDao.findById(ruleId);
|
||||
}
|
||||
|
||||
public static SecurityGroup findNetworkGroupById(Long groupId) {
|
||||
return _networkGroupDao.findById(groupId);
|
||||
|
||||
public static SecurityGroup findSecurityGroupById(Long groupId) {
|
||||
return _securityGroupDao.findById(groupId);
|
||||
}
|
||||
|
||||
public static HostPodVO findPodById(Long podId) {
|
||||
|
|
@ -405,8 +404,7 @@ public class ApiDBUtils {
|
|||
SnapshotVO snapshot = _snapshotDao.findById(snapshotId);
|
||||
if (snapshot != null && snapshot.getRemoved() == null && snapshot.getStatus() == Snapshot.Status.BackedUp) {
|
||||
return snapshot;
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
@ -420,23 +418,23 @@ public class ApiDBUtils {
|
|||
}
|
||||
|
||||
public static VMTemplateHostVO findTemplateHostRef(long templateId, long zoneId) {
|
||||
VMTemplateVO vmTemplate = findTemplateById(templateId);
|
||||
if (vmTemplate.getHypervisorType() == HypervisorType.BareMetal) {
|
||||
return _templateHostDao.findByHostTemplate(zoneId, templateId);
|
||||
} else {
|
||||
HostVO secondaryStorageHost = _storageMgr.getSecondaryStorageHost(zoneId);
|
||||
if (secondaryStorageHost == null) {
|
||||
return null;
|
||||
} else {
|
||||
return _templateHostDao.findByHostTemplate(secondaryStorageHost.getId(), templateId);
|
||||
}
|
||||
}
|
||||
VMTemplateVO vmTemplate = findTemplateById(templateId);
|
||||
if (vmTemplate.getHypervisorType() == HypervisorType.BareMetal) {
|
||||
return _templateHostDao.findByHostTemplate(zoneId, templateId);
|
||||
} else {
|
||||
HostVO secondaryStorageHost = _storageMgr.getSecondaryStorageHost(zoneId);
|
||||
if (secondaryStorageHost == null) {
|
||||
return null;
|
||||
} else {
|
||||
return _templateHostDao.findByHostTemplate(secondaryStorageHost.getId(), templateId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static UploadVO findUploadById(Long id){
|
||||
|
||||
public static UploadVO findUploadById(Long id) {
|
||||
return _uploadDao.findById(id);
|
||||
}
|
||||
|
||||
|
||||
public static User findUserById(Long userId) {
|
||||
return _userDao.findById(userId);
|
||||
}
|
||||
|
|
@ -452,7 +450,7 @@ public class ApiDBUtils {
|
|||
public static VolumeVO findVolumeById(Long volumeId) {
|
||||
return _volumeDao.findByIdIncludingRemoved(volumeId);
|
||||
}
|
||||
|
||||
|
||||
public static List<UserVO> listUsersByAccount(long accountId) {
|
||||
return _userDao.listByAccount(accountId);
|
||||
}
|
||||
|
|
@ -476,17 +474,17 @@ public class ApiDBUtils {
|
|||
|
||||
public static List<VMTemplateHostVO> listTemplateHostBy(long templateId, Long zoneId) {
|
||||
if (zoneId != null) {
|
||||
VMTemplateVO vmTemplate = findTemplateById(templateId);
|
||||
if (vmTemplate.getHypervisorType() == HypervisorType.BareMetal) {
|
||||
return _templateHostDao.listByHostTemplate(zoneId, templateId);
|
||||
} else {
|
||||
HostVO secondaryStorageHost = _storageMgr.getSecondaryStorageHost(zoneId);
|
||||
if (secondaryStorageHost == null) {
|
||||
return new ArrayList<VMTemplateHostVO>();
|
||||
} else {
|
||||
return _templateHostDao.listByHostTemplate(secondaryStorageHost.getId(), templateId);
|
||||
}
|
||||
}
|
||||
VMTemplateVO vmTemplate = findTemplateById(templateId);
|
||||
if (vmTemplate.getHypervisorType() == HypervisorType.BareMetal) {
|
||||
return _templateHostDao.listByHostTemplate(zoneId, templateId);
|
||||
} else {
|
||||
HostVO secondaryStorageHost = _storageMgr.getSecondaryStorageHost(zoneId);
|
||||
if (secondaryStorageHost == null) {
|
||||
return new ArrayList<VMTemplateHostVO>();
|
||||
} else {
|
||||
return _templateHostDao.listByHostTemplate(secondaryStorageHost.getId(), templateId);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return _templateHostDao.listByOnlyTemplateId(templateId);
|
||||
}
|
||||
|
|
@ -513,31 +511,31 @@ public class ApiDBUtils {
|
|||
|
||||
return _storageMgr.volumeOnSharedStoragePool(volume);
|
||||
}
|
||||
|
||||
|
||||
public static List<NicProfile> getNics(VirtualMachine vm) {
|
||||
return _networkMgr.getNicProfiles(vm);
|
||||
}
|
||||
|
||||
|
||||
public static NetworkProfile getNetworkProfile(long networkId) {
|
||||
return _networkMgr.convertNetworkToNetworkProfile(networkId);
|
||||
}
|
||||
|
||||
|
||||
public static NetworkOfferingVO findNetworkOfferingById(long networkOfferingId) {
|
||||
return _networkOfferingDao.findByIdIncludingRemoved(networkOfferingId);
|
||||
}
|
||||
|
||||
|
||||
public static List<? extends Vlan> listVlanByNetworkId(long networkId) {
|
||||
return _vlanDao.listVlansByNetworkId(networkId);
|
||||
}
|
||||
|
||||
|
||||
public static NetworkVO findNetworkById(long id) {
|
||||
return _networkDao.findById(id);
|
||||
}
|
||||
|
||||
|
||||
public static Map<Service, Map<Capability, String>> getNetworkCapabilities(long networkId) {
|
||||
return _networkMgr.getNetworkCapabilities(networkId);
|
||||
}
|
||||
|
||||
|
||||
public static long getPublicNetworkIdByZone(long zoneId) {
|
||||
return _networkMgr.getSystemNetworkByZoneAndTrafficType(zoneId, TrafficType.Public).getId();
|
||||
}
|
||||
|
|
@ -550,15 +548,15 @@ public class ApiDBUtils {
|
|||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static Integer getNetworkRate(long networkOfferingId) {
|
||||
return _configMgr.getNetworkOfferingNetworkRate(networkOfferingId);
|
||||
return _configMgr.getNetworkOfferingNetworkRate(networkOfferingId);
|
||||
}
|
||||
|
||||
|
||||
public static Account getVlanAccount(long vlanId) {
|
||||
return _configMgr.getVlanAccount(vlanId);
|
||||
return _configMgr.getVlanAccount(vlanId);
|
||||
}
|
||||
|
||||
|
||||
public static boolean isSecurityGroupEnabledInZone(long zoneId) {
|
||||
DataCenterVO dc = _zoneDao.findById(zoneId);
|
||||
if (dc == null) {
|
||||
|
|
@ -567,9 +565,9 @@ public class ApiDBUtils {
|
|||
return dc.isSecurityGroupEnabled();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static Long getDedicatedNetworkDomain(long networkId) {
|
||||
return _networkMgr.getDedicatedNetworkDomain(networkId);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -48,6 +48,7 @@ import com.cloud.api.response.FirewallRuleResponse;
|
|||
import com.cloud.api.response.HostResponse;
|
||||
import com.cloud.api.response.IPAddressResponse;
|
||||
import com.cloud.api.response.IngressRuleResponse;
|
||||
import com.cloud.api.response.IngressRuleResultObject;
|
||||
import com.cloud.api.response.InstanceGroupResponse;
|
||||
import com.cloud.api.response.IpForwardingRuleResponse;
|
||||
import com.cloud.api.response.ListResponse;
|
||||
|
|
@ -59,6 +60,7 @@ import com.cloud.api.response.PodResponse;
|
|||
import com.cloud.api.response.RemoteAccessVpnResponse;
|
||||
import com.cloud.api.response.ResourceLimitResponse;
|
||||
import com.cloud.api.response.SecurityGroupResponse;
|
||||
import com.cloud.api.response.SecurityGroupResultObject;
|
||||
import com.cloud.api.response.ServiceOfferingResponse;
|
||||
import com.cloud.api.response.ServiceResponse;
|
||||
import com.cloud.api.response.SnapshotPolicyResponse;
|
||||
|
|
@ -75,8 +77,6 @@ import com.cloud.api.response.VpnUsersResponse;
|
|||
import com.cloud.api.response.ZoneResponse;
|
||||
import com.cloud.async.AsyncJob;
|
||||
import com.cloud.async.AsyncJobResult;
|
||||
import com.cloud.async.executor.IngressRuleResultObject;
|
||||
import com.cloud.async.executor.SecurityGroupResultObject;
|
||||
import com.cloud.capacity.Capacity;
|
||||
import com.cloud.capacity.CapacityVO;
|
||||
import com.cloud.configuration.Configuration;
|
||||
|
|
@ -1685,9 +1685,11 @@ public class ApiResponseHelper implements ResponseGenerator {
|
|||
@Override
|
||||
public SecurityGroupResponse createSecurityGroupResponse(SecurityGroup group) {
|
||||
SecurityGroupResponse response = new SecurityGroupResponse();
|
||||
response.setAccountName(group.getAccountName());
|
||||
response.setDescription(group.getDescription());
|
||||
Account account = ApiDBUtils.findAccountById(group.getAccountId());
|
||||
|
||||
response.setAccountName(account.getAccountName());
|
||||
response.setDomainId(group.getDomainId());
|
||||
response.setDescription(group.getDescription());
|
||||
response.setDomainName(ApiDBUtils.findDomainById(group.getDomainId()).getName());
|
||||
response.setId(group.getId());
|
||||
response.setName(group.getName());
|
||||
|
|
@ -2273,14 +2275,25 @@ public class ApiResponseHelper implements ResponseGenerator {
|
|||
@Override
|
||||
public SecurityGroupResponse createSecurityGroupResponseFromIngressRule(List<? extends IngressRule> ingressRules) {
|
||||
SecurityGroupResponse response = new SecurityGroupResponse();
|
||||
Map<Long, Account> securiytGroupAccounts = new HashMap<Long, Account>();
|
||||
Map<Long, SecurityGroup> allowedSecurityGroups = new HashMap<Long, SecurityGroup>();
|
||||
Map<Long, Account> allowedSecuriytGroupAccounts = new HashMap<Long, Account>();
|
||||
|
||||
if ((ingressRules != null) && !ingressRules.isEmpty()) {
|
||||
SecurityGroup securityGroup = ApiDBUtils.findNetworkGroupById(ingressRules.get(0).getSecurityGroupId());
|
||||
SecurityGroup securityGroup = ApiDBUtils.findSecurityGroupById(ingressRules.get(0).getSecurityGroupId());
|
||||
response.setId(securityGroup.getId());
|
||||
response.setName(securityGroup.getName());
|
||||
response.setDescription(securityGroup.getDescription());
|
||||
response.setAccountName(securityGroup.getAccountName());
|
||||
response.setDomainId(securityGroup.getDomainId());
|
||||
|
||||
Account account = securiytGroupAccounts.get(securityGroup.getAccountId());
|
||||
|
||||
if (account == null) {
|
||||
account = ApiDBUtils.findAccountById(securityGroup.getAccountId());
|
||||
securiytGroupAccounts.put(securityGroup.getAccountId(), account);
|
||||
}
|
||||
|
||||
response.setAccountName(account.getAccountName());
|
||||
response.setDomainId(account.getDomainId());
|
||||
response.setDomainName(ApiDBUtils.findDomainById(securityGroup.getDomainId()).getName());
|
||||
|
||||
List<IngressRuleResponse> responses = new ArrayList<IngressRuleResponse>();
|
||||
|
|
@ -2297,9 +2310,23 @@ public class ApiResponseHelper implements ResponseGenerator {
|
|||
ingressData.setEndPort(ingressRule.getEndPort());
|
||||
}
|
||||
|
||||
if (ingressRule.getAllowedSecurityGroup() != null) {
|
||||
ingressData.setSecurityGroupName(ingressRule.getAllowedSecurityGroup());
|
||||
ingressData.setAccountName(ingressRule.getAllowedSecGrpAcct());
|
||||
Long allowedSecurityGroupId = ingressRule.getAllowedNetworkId();
|
||||
if (allowedSecurityGroupId != null) {
|
||||
SecurityGroup allowedSecurityGroup = allowedSecurityGroups.get(allowedSecurityGroupId);
|
||||
if (allowedSecurityGroup == null) {
|
||||
allowedSecurityGroup = ApiDBUtils.findSecurityGroupById(allowedSecurityGroupId);
|
||||
allowedSecurityGroups.put(allowedSecurityGroupId, allowedSecurityGroup);
|
||||
}
|
||||
|
||||
ingressData.setSecurityGroupName(allowedSecurityGroup.getName());
|
||||
|
||||
Account allowedAccount = allowedSecuriytGroupAccounts.get(allowedSecurityGroup.getAccountId());
|
||||
if (allowedAccount == null) {
|
||||
allowedAccount = ApiDBUtils.findAccountById(allowedSecurityGroup.getAccountId());
|
||||
allowedSecuriytGroupAccounts.put(allowedAccount.getId(), allowedAccount);
|
||||
}
|
||||
|
||||
ingressData.setAccountName(allowedAccount.getAccountName());
|
||||
} else {
|
||||
ingressData.setCidr(ingressRule.getAllowedSourceIpCidr());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,409 +14,408 @@
|
|||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*
|
||||
*/
|
||||
|
||||
package com.cloud.api;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLDecoder;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
import com.cloud.cluster.StackMaid;
|
||||
import com.cloud.exception.CloudAuthenticationException;
|
||||
import com.cloud.server.ManagementServer;
|
||||
import com.cloud.user.Account;
|
||||
import com.cloud.user.AccountService;
|
||||
import com.cloud.user.UserContext;
|
||||
import com.cloud.utils.component.ComponentLocator;
|
||||
import com.cloud.utils.exception.CloudRuntimeException;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public class ApiServlet extends HttpServlet {
|
||||
public static final Logger s_logger = Logger.getLogger(ApiServlet.class.getName());
|
||||
private static final Logger s_accessLogger = Logger.getLogger("apiserver." + ApiServer.class.getName());
|
||||
|
||||
private ApiServer _apiServer = null;
|
||||
private AccountService _accountMgr = null;
|
||||
|
||||
public ApiServlet() {
|
||||
super();
|
||||
_apiServer = ApiServer.getInstance();
|
||||
if (_apiServer == null) {
|
||||
throw new CloudRuntimeException("ApiServer not initialized");
|
||||
}
|
||||
ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name);
|
||||
_accountMgr = locator.getManager(AccountService.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
|
||||
try {
|
||||
processRequest(req, resp);
|
||||
} finally {
|
||||
StackMaid.current().exitCleanup();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
|
||||
try {
|
||||
processRequest(req, resp);
|
||||
} finally {
|
||||
StackMaid.current().exitCleanup();
|
||||
}
|
||||
}
|
||||
|
||||
private void utf8Fixup(HttpServletRequest req, Map<String, Object[]> params) {
|
||||
if(req.getQueryString() == null)
|
||||
return;
|
||||
|
||||
String[] paramsInQueryString = req.getQueryString().split("&");
|
||||
if(paramsInQueryString != null) {
|
||||
for (String param : paramsInQueryString) {
|
||||
String[] paramTokens = param.split("=");
|
||||
if(paramTokens != null && paramTokens.length == 2) {
|
||||
String name = param.split("=")[0];
|
||||
String value = param.split("=")[1];
|
||||
|
||||
try { name = URLDecoder.decode(name, "UTF-8"); } catch (UnsupportedEncodingException e) {}
|
||||
try { value = URLDecoder.decode(value, "UTF-8"); } catch (UnsupportedEncodingException e) {}
|
||||
params.put(name, new String[] {value});
|
||||
} else {
|
||||
s_logger.debug("Invalid paramemter in URL found. param: " + param);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void processRequest(HttpServletRequest req, HttpServletResponse resp) {
|
||||
StringBuffer auditTrailSb = new StringBuffer();
|
||||
auditTrailSb.append(" " +req.getRemoteAddr());
|
||||
auditTrailSb.append(" -- " + req.getMethod() + " " );
|
||||
// get the response format since we'll need it in a couple of places
|
||||
String responseType = BaseCmd.RESPONSE_TYPE_XML;
|
||||
Map<String, Object[]> params = new HashMap<String, Object[]>();
|
||||
params.putAll(req.getParameterMap());
|
||||
|
||||
//
|
||||
// For HTTP GET requests, it seems that HttpServletRequest.getParameterMap() actually tries
|
||||
// to unwrap URL encoded content from ISO-9959-1.
|
||||
//
|
||||
// After failed in using setCharacterEncoding() to control it, end up with following hacking : for all GET requests,
|
||||
// we will override it with our-own way of UTF-8 based URL decoding.
|
||||
//
|
||||
utf8Fixup(req, params);
|
||||
|
||||
try {
|
||||
HttpSession session = req.getSession(false);
|
||||
Object[] responseTypeParam = params.get("response");
|
||||
if (responseTypeParam != null) {
|
||||
responseType = (String)responseTypeParam[0];
|
||||
}
|
||||
|
||||
Object[] commandObj = params.get("command");
|
||||
if (commandObj != null) {
|
||||
String command = (String)commandObj[0];
|
||||
if ("logout".equalsIgnoreCase(command)) {
|
||||
// if this is just a logout, invalidate the session and return
|
||||
if (session != null) {
|
||||
Long userId = (Long)session.getAttribute("userid");
|
||||
Account account = (Account)session.getAttribute("accountobj");
|
||||
Long accountId = null;
|
||||
if (account != null) {
|
||||
accountId = account.getId();
|
||||
}
|
||||
auditTrailSb.insert(0, "(userId="+userId+
|
||||
" accountId="+ accountId +
|
||||
" sessionId="+session.getId() +")" );
|
||||
if (userId != null) {
|
||||
_apiServer.logoutUser(userId);
|
||||
}
|
||||
try {
|
||||
session.invalidate();
|
||||
}catch (IllegalStateException ise) {}
|
||||
}
|
||||
auditTrailSb.append("command=logout");
|
||||
auditTrailSb.append(" " + HttpServletResponse.SC_OK);
|
||||
writeResponse(resp, getLogoutSuccessResponse(responseType), HttpServletResponse.SC_OK, responseType);
|
||||
return;
|
||||
} else if ("login".equalsIgnoreCase(command)) {
|
||||
auditTrailSb.append("command=login");
|
||||
// if this is a login, authenticate the user and return
|
||||
if (session != null) {
|
||||
try {
|
||||
session.invalidate();
|
||||
}catch (IllegalStateException ise) {}
|
||||
}
|
||||
session = req.getSession(true);
|
||||
String[] username = (String[])params.get("username");
|
||||
String[] password = (String[])params.get("password");
|
||||
String[] domainIdArr = (String[])params.get("domainid");
|
||||
|
||||
if (domainIdArr == null) {
|
||||
domainIdArr = (String[])params.get("domainId");
|
||||
}
|
||||
String[] domainName = (String[])params.get("domain");
|
||||
Long domainId = null;
|
||||
if ((domainIdArr != null) && (domainIdArr.length > 0)) {
|
||||
try{
|
||||
domainId = new Long(Long.parseLong(domainIdArr[0]));
|
||||
auditTrailSb.append(" domainid=" +domainId);// building the params for POST call
|
||||
}
|
||||
catch(NumberFormatException e)
|
||||
{
|
||||
s_logger.warn("Invalid domain id entered by user");
|
||||
auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + "Invalid domain id entered, please enter a valid one");
|
||||
String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid domain id entered, please enter a valid one", params, responseType);
|
||||
writeResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType);
|
||||
}
|
||||
}
|
||||
String domain = null;
|
||||
if (domainName != null) {
|
||||
domain = domainName[0];
|
||||
auditTrailSb.append(" domain=" +domain);
|
||||
if (domain != null) {
|
||||
// ensure domain starts with '/' and ends with '/'
|
||||
if (!domain.endsWith("/")) {
|
||||
domain += '/';
|
||||
}
|
||||
if (!domain.startsWith("/")) {
|
||||
domain = "/" + domain;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (username != null) {
|
||||
String pwd = ((password == null) ? null : password[0]);
|
||||
try {
|
||||
_apiServer.loginUser(session, username[0], pwd, domainId, domain, params);
|
||||
auditTrailSb.insert(0,"(userId="+session.getAttribute("userid")+
|
||||
" accountId="+ ((Account)session.getAttribute("accountobj")).getId()+
|
||||
" sessionId="+session.getId()+ ")" );
|
||||
String loginResponse = getLoginSuccessResponse(session, responseType);
|
||||
writeResponse(resp, loginResponse, HttpServletResponse.SC_OK, responseType);
|
||||
return;
|
||||
} catch (CloudAuthenticationException ex) {
|
||||
// TODO: fall through to API key, or just fail here w/ auth error? (HTTP 401)
|
||||
try {
|
||||
session.invalidate();
|
||||
}catch (IllegalStateException ise) {}
|
||||
|
||||
auditTrailSb.append(" " + BaseCmd.ACCOUNT_ERROR + " " + ex.getMessage() != null ? ex.getMessage() : "failed to authenticate user, check if username/password are correct");
|
||||
String serializedResponse = _apiServer.getSerializedApiError(BaseCmd.ACCOUNT_ERROR, ex.getMessage() != null ? ex.getMessage() : "failed to authenticate user, check if username/password are correct", params, responseType);
|
||||
writeResponse(resp, serializedResponse, BaseCmd.ACCOUNT_ERROR, responseType);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
auditTrailSb.append(req.getQueryString());
|
||||
boolean isNew = ((session == null) ? true : session.isNew());
|
||||
|
||||
// Initialize an empty context and we will update it after we have verified the request below,
|
||||
// we no longer rely on web-session here, verifyRequest will populate user/account information
|
||||
// if a API key exists
|
||||
UserContext.registerContext(_accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount(), null, false);
|
||||
Long userId = null;
|
||||
|
||||
if (!isNew) {
|
||||
userId = (Long)session.getAttribute("userid");
|
||||
String account = (String)session.getAttribute("account");
|
||||
Long domainId = (Long)session.getAttribute("domainid");
|
||||
Object accountObj = session.getAttribute("accountobj");
|
||||
String sessionKey = (String)session.getAttribute("sessionkey");
|
||||
String[] sessionKeyParam = (String[])params.get("sessionkey");
|
||||
if ((sessionKeyParam == null) || (sessionKey == null) || !sessionKey.equals(sessionKeyParam[0])) {
|
||||
try {
|
||||
session.invalidate();
|
||||
}catch (IllegalStateException ise) {}
|
||||
auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + "unable to verify user credentials");
|
||||
String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "unable to verify user credentials", params, responseType);
|
||||
writeResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType);
|
||||
return;
|
||||
}
|
||||
|
||||
// Do a sanity check here to make sure the user hasn't already been deleted
|
||||
if ((userId != null) && (account != null) && (accountObj != null) && _apiServer.verifyUser(userId)) {
|
||||
String[] command = (String[])params.get("command");
|
||||
if (command == null) {
|
||||
s_logger.info("missing command, ignoring request...");
|
||||
auditTrailSb.append(" " + HttpServletResponse.SC_BAD_REQUEST + " " + "no command specified");
|
||||
String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_BAD_REQUEST, "no command specified", params, responseType);
|
||||
writeResponse(resp, serializedResponse, HttpServletResponse.SC_BAD_REQUEST, responseType);
|
||||
return;
|
||||
}
|
||||
UserContext.updateContext(userId, (Account)accountObj, session.getId());
|
||||
} else {
|
||||
// Invalidate the session to ensure we won't allow a request across management server restarts if the userId was serialized to the
|
||||
// stored session
|
||||
try {
|
||||
session.invalidate();
|
||||
}catch (IllegalStateException ise) {}
|
||||
|
||||
auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + "unable to verify user credentials");
|
||||
String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "unable to verify user credentials", params, responseType);
|
||||
writeResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (_apiServer.verifyRequest(params, userId)) {
|
||||
/*
|
||||
if (accountObj != null) {
|
||||
Account userAccount = (Account)accountObj;
|
||||
if (userAccount.getType() == Account.ACCOUNT_TYPE_NORMAL) {
|
||||
params.put(BaseCmd.Properties.USER_ID.getName(), new String[] { userId });
|
||||
params.put(BaseCmd.Properties.ACCOUNT.getName(), new String[] { account });
|
||||
params.put(BaseCmd.Properties.DOMAIN_ID.getName(), new String[] { domainId });
|
||||
params.put(BaseCmd.Properties.ACCOUNT_OBJ.getName(), new Object[] { accountObj });
|
||||
} else {
|
||||
params.put(BaseCmd.Properties.USER_ID.getName(), new String[] { userId });
|
||||
params.put(BaseCmd.Properties.ACCOUNT_OBJ.getName(), new Object[] { accountObj });
|
||||
}
|
||||
}
|
||||
|
||||
// update user context info here so that we can take information if the request is authenticated
|
||||
// via api key mechanism
|
||||
updateUserContext(params, session != null ? session.getId() : null);
|
||||
*/
|
||||
|
||||
auditTrailSb.insert(0, "(userId="+UserContext.current().getCallerUserId()+ " accountId="+UserContext.current().getCaller().getId()+ " sessionId="+(session != null ? session.getId() : null)+ ")" );
|
||||
|
||||
try {
|
||||
String response = _apiServer.handleRequest(params, false, responseType, auditTrailSb);
|
||||
writeResponse(resp, response != null ? response : "", HttpServletResponse.SC_OK, responseType);
|
||||
} catch (ServerApiException se) {
|
||||
String serializedResponseText = _apiServer.getSerializedApiError(se.getErrorCode(), se.getDescription(), params, responseType);
|
||||
resp.setHeader("X-Description", se.getDescription());
|
||||
writeResponse(resp, serializedResponseText, se.getErrorCode(), responseType);
|
||||
auditTrailSb.append(" " +se.getErrorCode() + " " + se.getDescription());
|
||||
}
|
||||
} else {
|
||||
if (session != null) {
|
||||
try {
|
||||
session.invalidate();
|
||||
} catch (IllegalStateException ise) {}
|
||||
}
|
||||
|
||||
auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + "unable to verify user credentials and/or request signature");
|
||||
String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "unable to verify user credentials and/or request signature", params, responseType);
|
||||
writeResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType);
|
||||
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
if (ex instanceof ServerApiException && ((ServerApiException) ex).getErrorCode() == BaseCmd.UNSUPPORTED_ACTION_ERROR) {
|
||||
ServerApiException se = (ServerApiException)ex;
|
||||
String serializedResponseText = _apiServer.getSerializedApiError(se.getErrorCode(), se.getDescription(), params, responseType);
|
||||
resp.setHeader("X-Description", se.getDescription());
|
||||
writeResponse(resp, serializedResponseText, se.getErrorCode(), responseType);
|
||||
auditTrailSb.append(" " +se.getErrorCode() + " " + se.getDescription());
|
||||
} else {
|
||||
s_logger.error("unknown exception writing api response", ex);
|
||||
auditTrailSb.append(" unknown exception writing api response");
|
||||
}
|
||||
} finally {
|
||||
s_accessLogger.info(auditTrailSb.toString());
|
||||
// cleanup user context to prevent from being peeked in other request context
|
||||
UserContext.unregisterContext();
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
private void updateUserContext(Map<String, Object[]> requestParameters, String sessionId) {
|
||||
String userIdStr = (String)(requestParameters.get(BaseCmd.Properties.USER_ID.getName())[0]);
|
||||
Account accountObj = (Account)(requestParameters.get(BaseCmd.Properties.ACCOUNT_OBJ.getName())[0]);
|
||||
|
||||
Long userId = null;
|
||||
Long accountId = null;
|
||||
if(userIdStr != null)
|
||||
userId = Long.parseLong(userIdStr);
|
||||
|
||||
if(accountObj != null)
|
||||
accountId = accountObj.getId();
|
||||
UserContext.updateContext(userId, accountId, sessionId);
|
||||
}
|
||||
*/
|
||||
|
||||
// FIXME: rather than isError, we might was to pass in the status code to give more flexibility
|
||||
private void writeResponse(HttpServletResponse resp, String response, int responseCode, String responseType) {
|
||||
try {
|
||||
if (BaseCmd.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
|
||||
resp.setContentType("text/javascript; charset=UTF-8");
|
||||
} else {
|
||||
resp.setContentType("text/xml; charset=UTF-8");
|
||||
}
|
||||
|
||||
resp.setStatus(responseCode);
|
||||
resp.getWriter().print(response);
|
||||
} catch (IOException ioex) {
|
||||
if (s_logger.isTraceEnabled()) {
|
||||
s_logger.trace("exception writing response: " + ioex);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
if (!(ex instanceof IllegalStateException)) {
|
||||
s_logger.error("unknown exception writing api response", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
private String getLoginSuccessResponse(HttpSession session, String responseType) {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
int inactiveInterval = session.getMaxInactiveInterval();
|
||||
|
||||
if (BaseCmd.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
|
||||
sb.append("{ \"loginresponse\" : { ");
|
||||
Enumeration attrNames = session.getAttributeNames();
|
||||
if (attrNames != null) {
|
||||
sb.append("\"timeout\" : \"" + inactiveInterval + "\"");
|
||||
while (attrNames.hasMoreElements()) {
|
||||
String attrName = (String)attrNames.nextElement();
|
||||
Object attrObj = session.getAttribute(attrName);
|
||||
if ((attrObj instanceof String) || (attrObj instanceof Long)) {
|
||||
sb.append(", \"" + attrName + "\" : \"" + attrObj.toString() + "\"");
|
||||
}
|
||||
}
|
||||
}
|
||||
sb.append(" } }");
|
||||
} else {
|
||||
sb.append("<loginresponse>");
|
||||
sb.append("<timeout>" + inactiveInterval + "</timeout>");
|
||||
Enumeration attrNames = session.getAttributeNames();
|
||||
if (attrNames != null) {
|
||||
while (attrNames.hasMoreElements()) {
|
||||
String attrName = (String)attrNames.nextElement();
|
||||
Object attrObj = session.getAttribute(attrName);
|
||||
if (attrObj instanceof String || attrObj instanceof Long || attrObj instanceof Short) {
|
||||
sb.append("<" + attrName + ">" + attrObj.toString() + "</" + attrName + ">");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sb.append("</loginresponse>");
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private String getLogoutSuccessResponse(String responseType) {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
if (BaseCmd.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
|
||||
sb.append("{ \"logoutresponse\" : { \"description\" : \"success\" } }");
|
||||
} else {
|
||||
sb.append("<logoutresponse><description>success</description></logoutresponse>");
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
}
|
||||
*/
|
||||
|
||||
package com.cloud.api;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLDecoder;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
import com.cloud.cluster.StackMaid;
|
||||
import com.cloud.exception.CloudAuthenticationException;
|
||||
import com.cloud.server.ManagementServer;
|
||||
import com.cloud.user.Account;
|
||||
import com.cloud.user.AccountService;
|
||||
import com.cloud.user.UserContext;
|
||||
import com.cloud.utils.component.ComponentLocator;
|
||||
import com.cloud.utils.exception.CloudRuntimeException;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public class ApiServlet extends HttpServlet {
|
||||
public static final Logger s_logger = Logger.getLogger(ApiServlet.class.getName());
|
||||
private static final Logger s_accessLogger = Logger.getLogger("apiserver." + ApiServer.class.getName());
|
||||
|
||||
private ApiServer _apiServer = null;
|
||||
private AccountService _accountMgr = null;
|
||||
|
||||
public ApiServlet() {
|
||||
super();
|
||||
_apiServer = ApiServer.getInstance();
|
||||
if (_apiServer == null) {
|
||||
throw new CloudRuntimeException("ApiServer not initialized");
|
||||
}
|
||||
ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name);
|
||||
_accountMgr = locator.getManager(AccountService.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
|
||||
try {
|
||||
processRequest(req, resp);
|
||||
} finally {
|
||||
StackMaid.current().exitCleanup();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
|
||||
try {
|
||||
processRequest(req, resp);
|
||||
} finally {
|
||||
StackMaid.current().exitCleanup();
|
||||
}
|
||||
}
|
||||
|
||||
private void utf8Fixup(HttpServletRequest req, Map<String, Object[]> params) {
|
||||
if (req.getQueryString() == null)
|
||||
return;
|
||||
|
||||
String[] paramsInQueryString = req.getQueryString().split("&");
|
||||
if (paramsInQueryString != null) {
|
||||
for (String param : paramsInQueryString) {
|
||||
String[] paramTokens = param.split("=");
|
||||
if (paramTokens != null && paramTokens.length == 2) {
|
||||
String name = param.split("=")[0];
|
||||
String value = param.split("=")[1];
|
||||
|
||||
try {
|
||||
name = URLDecoder.decode(name, "UTF-8");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
}
|
||||
try {
|
||||
value = URLDecoder.decode(value, "UTF-8");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
}
|
||||
params.put(name, new String[] { value });
|
||||
} else {
|
||||
s_logger.debug("Invalid paramemter in URL found. param: " + param);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void processRequest(HttpServletRequest req, HttpServletResponse resp) {
|
||||
StringBuffer auditTrailSb = new StringBuffer();
|
||||
auditTrailSb.append(" " + req.getRemoteAddr());
|
||||
auditTrailSb.append(" -- " + req.getMethod() + " ");
|
||||
// get the response format since we'll need it in a couple of places
|
||||
String responseType = BaseCmd.RESPONSE_TYPE_XML;
|
||||
Map<String, Object[]> params = new HashMap<String, Object[]>();
|
||||
params.putAll(req.getParameterMap());
|
||||
|
||||
//
|
||||
// For HTTP GET requests, it seems that HttpServletRequest.getParameterMap() actually tries
|
||||
// to unwrap URL encoded content from ISO-9959-1.
|
||||
//
|
||||
// After failed in using setCharacterEncoding() to control it, end up with following hacking : for all GET requests,
|
||||
// we will override it with our-own way of UTF-8 based URL decoding.
|
||||
//
|
||||
utf8Fixup(req, params);
|
||||
|
||||
try {
|
||||
HttpSession session = req.getSession(false);
|
||||
Object[] responseTypeParam = params.get("response");
|
||||
if (responseTypeParam != null) {
|
||||
responseType = (String) responseTypeParam[0];
|
||||
}
|
||||
|
||||
Object[] commandObj = params.get("command");
|
||||
if (commandObj != null) {
|
||||
String command = (String) commandObj[0];
|
||||
if ("logout".equalsIgnoreCase(command)) {
|
||||
// if this is just a logout, invalidate the session and return
|
||||
if (session != null) {
|
||||
Long userId = (Long) session.getAttribute("userid");
|
||||
Account account = (Account) session.getAttribute("accountobj");
|
||||
Long accountId = null;
|
||||
if (account != null) {
|
||||
accountId = account.getId();
|
||||
}
|
||||
auditTrailSb.insert(0, "(userId=" + userId + " accountId=" + accountId + " sessionId=" + session.getId() + ")");
|
||||
if (userId != null) {
|
||||
_apiServer.logoutUser(userId);
|
||||
}
|
||||
try {
|
||||
session.invalidate();
|
||||
} catch (IllegalStateException ise) {
|
||||
}
|
||||
}
|
||||
auditTrailSb.append("command=logout");
|
||||
auditTrailSb.append(" " + HttpServletResponse.SC_OK);
|
||||
writeResponse(resp, getLogoutSuccessResponse(responseType), HttpServletResponse.SC_OK, responseType);
|
||||
return;
|
||||
} else if ("login".equalsIgnoreCase(command)) {
|
||||
auditTrailSb.append("command=login");
|
||||
// if this is a login, authenticate the user and return
|
||||
if (session != null) {
|
||||
try {
|
||||
session.invalidate();
|
||||
} catch (IllegalStateException ise) {
|
||||
}
|
||||
}
|
||||
session = req.getSession(true);
|
||||
String[] username = (String[]) params.get("username");
|
||||
String[] password = (String[]) params.get("password");
|
||||
String[] domainIdArr = (String[]) params.get("domainid");
|
||||
|
||||
if (domainIdArr == null) {
|
||||
domainIdArr = (String[]) params.get("domainId");
|
||||
}
|
||||
String[] domainName = (String[]) params.get("domain");
|
||||
Long domainId = null;
|
||||
if ((domainIdArr != null) && (domainIdArr.length > 0)) {
|
||||
try {
|
||||
domainId = new Long(Long.parseLong(domainIdArr[0]));
|
||||
auditTrailSb.append(" domainid=" + domainId);// building the params for POST call
|
||||
} catch (NumberFormatException e) {
|
||||
s_logger.warn("Invalid domain id entered by user");
|
||||
auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + "Invalid domain id entered, please enter a valid one");
|
||||
String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid domain id entered, please enter a valid one", params,
|
||||
responseType);
|
||||
writeResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType);
|
||||
}
|
||||
}
|
||||
String domain = null;
|
||||
if (domainName != null) {
|
||||
domain = domainName[0];
|
||||
auditTrailSb.append(" domain=" + domain);
|
||||
if (domain != null) {
|
||||
// ensure domain starts with '/' and ends with '/'
|
||||
if (!domain.endsWith("/")) {
|
||||
domain += '/';
|
||||
}
|
||||
if (!domain.startsWith("/")) {
|
||||
domain = "/" + domain;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (username != null) {
|
||||
String pwd = ((password == null) ? null : password[0]);
|
||||
try {
|
||||
_apiServer.loginUser(session, username[0], pwd, domainId, domain, params);
|
||||
auditTrailSb.insert(0,
|
||||
"(userId=" + session.getAttribute("userid") + " accountId=" + ((Account) session.getAttribute("accountobj")).getId() + " sessionId=" + session.getId() + ")");
|
||||
String loginResponse = getLoginSuccessResponse(session, responseType);
|
||||
writeResponse(resp, loginResponse, HttpServletResponse.SC_OK, responseType);
|
||||
return;
|
||||
} catch (CloudAuthenticationException ex) {
|
||||
// TODO: fall through to API key, or just fail here w/ auth error? (HTTP 401)
|
||||
try {
|
||||
session.invalidate();
|
||||
} catch (IllegalStateException ise) {
|
||||
}
|
||||
|
||||
auditTrailSb.append(" " + BaseCmd.ACCOUNT_ERROR + " " + ex.getMessage() != null ? ex.getMessage() : "failed to authenticate user, check if username/password are correct");
|
||||
String serializedResponse = _apiServer.getSerializedApiError(BaseCmd.ACCOUNT_ERROR, ex.getMessage() != null ? ex.getMessage()
|
||||
: "failed to authenticate user, check if username/password are correct", params, responseType);
|
||||
writeResponse(resp, serializedResponse, BaseCmd.ACCOUNT_ERROR, responseType);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
auditTrailSb.append(req.getQueryString());
|
||||
boolean isNew = ((session == null) ? true : session.isNew());
|
||||
|
||||
// Initialize an empty context and we will update it after we have verified the request below,
|
||||
// we no longer rely on web-session here, verifyRequest will populate user/account information
|
||||
// if a API key exists
|
||||
UserContext.registerContext(_accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount(), null, false);
|
||||
Long userId = null;
|
||||
|
||||
if (!isNew) {
|
||||
userId = (Long) session.getAttribute("userid");
|
||||
String account = (String) session.getAttribute("account");
|
||||
Object accountObj = session.getAttribute("accountobj");
|
||||
String sessionKey = (String) session.getAttribute("sessionkey");
|
||||
String[] sessionKeyParam = (String[]) params.get("sessionkey");
|
||||
if ((sessionKeyParam == null) || (sessionKey == null) || !sessionKey.equals(sessionKeyParam[0])) {
|
||||
try {
|
||||
session.invalidate();
|
||||
} catch (IllegalStateException ise) {
|
||||
}
|
||||
auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + "unable to verify user credentials");
|
||||
String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "unable to verify user credentials", params, responseType);
|
||||
writeResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType);
|
||||
return;
|
||||
}
|
||||
|
||||
// Do a sanity check here to make sure the user hasn't already been deleted
|
||||
if ((userId != null) && (account != null) && (accountObj != null) && _apiServer.verifyUser(userId)) {
|
||||
String[] command = (String[]) params.get("command");
|
||||
if (command == null) {
|
||||
s_logger.info("missing command, ignoring request...");
|
||||
auditTrailSb.append(" " + HttpServletResponse.SC_BAD_REQUEST + " " + "no command specified");
|
||||
String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_BAD_REQUEST, "no command specified", params, responseType);
|
||||
writeResponse(resp, serializedResponse, HttpServletResponse.SC_BAD_REQUEST, responseType);
|
||||
return;
|
||||
}
|
||||
UserContext.updateContext(userId, (Account) accountObj, session.getId());
|
||||
} else {
|
||||
// Invalidate the session to ensure we won't allow a request across management server restarts if the userId
|
||||
// was serialized to the
|
||||
// stored session
|
||||
try {
|
||||
session.invalidate();
|
||||
} catch (IllegalStateException ise) {
|
||||
}
|
||||
|
||||
auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + "unable to verify user credentials");
|
||||
String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "unable to verify user credentials", params, responseType);
|
||||
writeResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (_apiServer.verifyRequest(params, userId)) {
|
||||
/*
|
||||
* if (accountObj != null) { Account userAccount = (Account)accountObj; if (userAccount.getType() ==
|
||||
* Account.ACCOUNT_TYPE_NORMAL) { params.put(BaseCmd.Properties.USER_ID.getName(), new String[] { userId });
|
||||
* params.put(BaseCmd.Properties.ACCOUNT.getName(), new String[] { account });
|
||||
* params.put(BaseCmd.Properties.DOMAIN_ID.getName(), new String[] { domainId });
|
||||
* params.put(BaseCmd.Properties.ACCOUNT_OBJ.getName(), new Object[] { accountObj }); } else {
|
||||
* params.put(BaseCmd.Properties.USER_ID.getName(), new String[] { userId });
|
||||
* params.put(BaseCmd.Properties.ACCOUNT_OBJ.getName(), new Object[] { accountObj }); } }
|
||||
*
|
||||
* // update user context info here so that we can take information if the request is authenticated // via api
|
||||
* key mechanism updateUserContext(params, session != null ? session.getId() : null);
|
||||
*/
|
||||
|
||||
auditTrailSb.insert(0,
|
||||
"(userId=" + UserContext.current().getCallerUserId() + " accountId=" + UserContext.current().getCaller().getId() + " sessionId=" + (session != null ? session.getId() : null)
|
||||
+ ")");
|
||||
|
||||
try {
|
||||
String response = _apiServer.handleRequest(params, false, responseType, auditTrailSb);
|
||||
writeResponse(resp, response != null ? response : "", HttpServletResponse.SC_OK, responseType);
|
||||
} catch (ServerApiException se) {
|
||||
String serializedResponseText = _apiServer.getSerializedApiError(se.getErrorCode(), se.getDescription(), params, responseType);
|
||||
resp.setHeader("X-Description", se.getDescription());
|
||||
writeResponse(resp, serializedResponseText, se.getErrorCode(), responseType);
|
||||
auditTrailSb.append(" " + se.getErrorCode() + " " + se.getDescription());
|
||||
}
|
||||
} else {
|
||||
if (session != null) {
|
||||
try {
|
||||
session.invalidate();
|
||||
} catch (IllegalStateException ise) {
|
||||
}
|
||||
}
|
||||
|
||||
auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + "unable to verify user credentials and/or request signature");
|
||||
String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "unable to verify user credentials and/or request signature", params, responseType);
|
||||
writeResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType);
|
||||
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
if (ex instanceof ServerApiException && ((ServerApiException) ex).getErrorCode() == BaseCmd.UNSUPPORTED_ACTION_ERROR) {
|
||||
ServerApiException se = (ServerApiException) ex;
|
||||
String serializedResponseText = _apiServer.getSerializedApiError(se.getErrorCode(), se.getDescription(), params, responseType);
|
||||
resp.setHeader("X-Description", se.getDescription());
|
||||
writeResponse(resp, serializedResponseText, se.getErrorCode(), responseType);
|
||||
auditTrailSb.append(" " + se.getErrorCode() + " " + se.getDescription());
|
||||
} else {
|
||||
s_logger.error("unknown exception writing api response", ex);
|
||||
auditTrailSb.append(" unknown exception writing api response");
|
||||
}
|
||||
} finally {
|
||||
s_accessLogger.info(auditTrailSb.toString());
|
||||
// cleanup user context to prevent from being peeked in other request context
|
||||
UserContext.unregisterContext();
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* private void updateUserContext(Map<String, Object[]> requestParameters, String sessionId) { String userIdStr =
|
||||
* (String)(requestParameters.get(BaseCmd.Properties.USER_ID.getName())[0]); Account accountObj =
|
||||
* (Account)(requestParameters.get(BaseCmd.Properties.ACCOUNT_OBJ.getName())[0]);
|
||||
*
|
||||
* Long userId = null; Long accountId = null; if(userIdStr != null) userId = Long.parseLong(userIdStr);
|
||||
*
|
||||
* if(accountObj != null) accountId = accountObj.getId(); UserContext.updateContext(userId, accountId, sessionId); }
|
||||
*/
|
||||
|
||||
// FIXME: rather than isError, we might was to pass in the status code to give more flexibility
|
||||
private void writeResponse(HttpServletResponse resp, String response, int responseCode, String responseType) {
|
||||
try {
|
||||
if (BaseCmd.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
|
||||
resp.setContentType("text/javascript; charset=UTF-8");
|
||||
} else {
|
||||
resp.setContentType("text/xml; charset=UTF-8");
|
||||
}
|
||||
|
||||
resp.setStatus(responseCode);
|
||||
resp.getWriter().print(response);
|
||||
} catch (IOException ioex) {
|
||||
if (s_logger.isTraceEnabled()) {
|
||||
s_logger.trace("exception writing response: " + ioex);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
if (!(ex instanceof IllegalStateException)) {
|
||||
s_logger.error("unknown exception writing api response", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
private String getLoginSuccessResponse(HttpSession session, String responseType) {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
int inactiveInterval = session.getMaxInactiveInterval();
|
||||
|
||||
if (BaseCmd.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
|
||||
sb.append("{ \"loginresponse\" : { ");
|
||||
Enumeration attrNames = session.getAttributeNames();
|
||||
if (attrNames != null) {
|
||||
sb.append("\"timeout\" : \"" + inactiveInterval + "\"");
|
||||
while (attrNames.hasMoreElements()) {
|
||||
String attrName = (String) attrNames.nextElement();
|
||||
Object attrObj = session.getAttribute(attrName);
|
||||
if ((attrObj instanceof String) || (attrObj instanceof Long)) {
|
||||
sb.append(", \"" + attrName + "\" : \"" + attrObj.toString() + "\"");
|
||||
}
|
||||
}
|
||||
}
|
||||
sb.append(" } }");
|
||||
} else {
|
||||
sb.append("<loginresponse>");
|
||||
sb.append("<timeout>" + inactiveInterval + "</timeout>");
|
||||
Enumeration attrNames = session.getAttributeNames();
|
||||
if (attrNames != null) {
|
||||
while (attrNames.hasMoreElements()) {
|
||||
String attrName = (String) attrNames.nextElement();
|
||||
Object attrObj = session.getAttribute(attrName);
|
||||
if (attrObj instanceof String || attrObj instanceof Long || attrObj instanceof Short) {
|
||||
sb.append("<" + attrName + ">" + attrObj.toString() + "</" + attrName + ">");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sb.append("</loginresponse>");
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private String getLogoutSuccessResponse(String responseType) {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
if (BaseCmd.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
|
||||
sb.append("{ \"logoutresponse\" : { \"description\" : \"success\" } }");
|
||||
} else {
|
||||
sb.append("<logoutresponse><description>success</description></logoutresponse>");
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@
|
|||
*
|
||||
*/
|
||||
|
||||
package com.cloud.async.executor;
|
||||
package com.cloud.api.response;
|
||||
|
||||
import com.cloud.serializer.Param;
|
||||
|
||||
|
|
@ -16,163 +16,192 @@
|
|||
*
|
||||
*/
|
||||
|
||||
package com.cloud.async.executor;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.cloud.network.security.SecurityGroupRules;
|
||||
import com.cloud.serializer.Param;
|
||||
|
||||
public class SecurityGroupResultObject {
|
||||
@Param(name="id")
|
||||
private Long id;
|
||||
|
||||
@Param(name="name")
|
||||
private String name;
|
||||
|
||||
@Param(name="description")
|
||||
private String description;
|
||||
|
||||
@Param(name="domainid")
|
||||
private Long domainId;
|
||||
|
||||
@Param(name="accountid")
|
||||
private Long accountId;
|
||||
|
||||
@Param(name="accountname")
|
||||
private String accountName = null;
|
||||
|
||||
@Param(name="ingressrules")
|
||||
private List<IngressRuleResultObject> ingressRules = null;
|
||||
|
||||
public SecurityGroupResultObject() {}
|
||||
|
||||
public SecurityGroupResultObject(Long id, String name, String description, Long domainId, Long accountId, String accountName, List<IngressRuleResultObject> ingressRules) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
this.domainId = domainId;
|
||||
this.accountId = accountId;
|
||||
this.accountName = accountName;
|
||||
this.ingressRules = ingressRules;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public Long getDomainId() {
|
||||
return domainId;
|
||||
}
|
||||
|
||||
public void setDomainId(Long domainId) {
|
||||
this.domainId = domainId;
|
||||
}
|
||||
|
||||
public Long getAccountId() {
|
||||
return accountId;
|
||||
}
|
||||
|
||||
public void setAccountId(Long accountId) {
|
||||
this.accountId = accountId;
|
||||
}
|
||||
|
||||
public String getAccountName() {
|
||||
return accountName;
|
||||
}
|
||||
|
||||
public void setAccountName(String accountName) {
|
||||
this.accountName = accountName;
|
||||
}
|
||||
|
||||
public List<IngressRuleResultObject> getIngressRules() {
|
||||
return ingressRules;
|
||||
}
|
||||
|
||||
public void setIngressRules(List<IngressRuleResultObject> ingressRules) {
|
||||
this.ingressRules = ingressRules;
|
||||
}
|
||||
|
||||
public static List<SecurityGroupResultObject> transposeNetworkGroups(List<? extends SecurityGroupRules> groups) {
|
||||
List<SecurityGroupResultObject> resultObjects = new ArrayList<SecurityGroupResultObject>();
|
||||
|
||||
if ((groups != null) && !groups.isEmpty()) {
|
||||
List<IngressRuleResultObject> ingressDataList = new ArrayList<IngressRuleResultObject>();
|
||||
SecurityGroupResultObject currentGroup = null;
|
||||
|
||||
List<Long> processedGroups = new ArrayList<Long>();
|
||||
for (SecurityGroupRules netGroupRule : groups) {
|
||||
Long groupId = netGroupRule.getId();
|
||||
if (!processedGroups.contains(groupId)) {
|
||||
processedGroups.add(groupId);
|
||||
|
||||
if (currentGroup != null) {
|
||||
if (!ingressDataList.isEmpty()) {
|
||||
currentGroup.setIngressRules(ingressDataList);
|
||||
ingressDataList = new ArrayList<IngressRuleResultObject>();
|
||||
}
|
||||
resultObjects.add(currentGroup);
|
||||
}
|
||||
|
||||
// start a new group
|
||||
SecurityGroupResultObject groupResult = new SecurityGroupResultObject();
|
||||
groupResult.setId(netGroupRule.getId());
|
||||
groupResult.setName(netGroupRule.getName());
|
||||
groupResult.setDescription(netGroupRule.getDescription());
|
||||
groupResult.setDomainId(netGroupRule.getDomainId());
|
||||
groupResult.setAccountId(netGroupRule.getAccountId());
|
||||
groupResult.setAccountName(netGroupRule.getAccountName());
|
||||
|
||||
currentGroup = groupResult;
|
||||
}
|
||||
|
||||
if (netGroupRule.getRuleId() != null) {
|
||||
// there's at least one ingress rule for this network group, add the ingress rule data
|
||||
IngressRuleResultObject ingressData = new IngressRuleResultObject();
|
||||
ingressData.setEndPort(netGroupRule.getEndPort());
|
||||
ingressData.setStartPort(netGroupRule.getStartPort());
|
||||
ingressData.setId(netGroupRule.getRuleId());
|
||||
ingressData.setProtocol(netGroupRule.getProtocol());
|
||||
|
||||
if (netGroupRule.getAllowedSecurityGroup() != null) {
|
||||
ingressData.setAllowedSecurityGroup(netGroupRule.getAllowedSecurityGroup());
|
||||
ingressData.setAllowedSecGroupAcct(netGroupRule.getAllowedSecGrpAcct());
|
||||
} else if (netGroupRule.getAllowedSourceIpCidr() != null) {
|
||||
ingressData.setAllowedSourceIpCidr(netGroupRule.getAllowedSourceIpCidr());
|
||||
}
|
||||
ingressDataList.add(ingressData);
|
||||
}
|
||||
}
|
||||
|
||||
// all rules have been processed, add the final data into the list
|
||||
if (currentGroup != null) {
|
||||
if (!ingressDataList.isEmpty()) {
|
||||
currentGroup.setIngressRules(ingressDataList);
|
||||
}
|
||||
resultObjects.add(currentGroup);
|
||||
}
|
||||
}
|
||||
return resultObjects;
|
||||
}
|
||||
}
|
||||
package com.cloud.api.response;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.cloud.api.ApiDBUtils;
|
||||
import com.cloud.network.security.SecurityGroup;
|
||||
import com.cloud.network.security.SecurityGroupRules;
|
||||
import com.cloud.serializer.Param;
|
||||
import com.cloud.user.Account;
|
||||
|
||||
public class SecurityGroupResultObject {
|
||||
@Param(name = "id")
|
||||
private Long id;
|
||||
|
||||
@Param(name = "name")
|
||||
private String name;
|
||||
|
||||
@Param(name = "description")
|
||||
private String description;
|
||||
|
||||
@Param(name = "domainid")
|
||||
private Long domainId;
|
||||
|
||||
@Param(name = "accountid")
|
||||
private Long accountId;
|
||||
|
||||
@Param(name = "accountname")
|
||||
private String accountName = null;
|
||||
|
||||
@Param(name = "ingressrules")
|
||||
private List<IngressRuleResultObject> ingressRules = null;
|
||||
|
||||
public SecurityGroupResultObject() {
|
||||
}
|
||||
|
||||
public SecurityGroupResultObject(Long id, String name, String description, Long domainId, Long accountId, String accountName, List<IngressRuleResultObject> ingressRules) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
this.domainId = domainId;
|
||||
this.accountId = accountId;
|
||||
this.accountName = accountName;
|
||||
this.ingressRules = ingressRules;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public Long getDomainId() {
|
||||
return domainId;
|
||||
}
|
||||
|
||||
public void setDomainId(Long domainId) {
|
||||
this.domainId = domainId;
|
||||
}
|
||||
|
||||
public Long getAccountId() {
|
||||
return accountId;
|
||||
}
|
||||
|
||||
public void setAccountId(Long accountId) {
|
||||
this.accountId = accountId;
|
||||
}
|
||||
|
||||
public String getAccountName() {
|
||||
return accountName;
|
||||
}
|
||||
|
||||
public void setAccountName(String accountName) {
|
||||
this.accountName = accountName;
|
||||
}
|
||||
|
||||
public List<IngressRuleResultObject> getIngressRules() {
|
||||
return ingressRules;
|
||||
}
|
||||
|
||||
public void setIngressRules(List<IngressRuleResultObject> ingressRules) {
|
||||
this.ingressRules = ingressRules;
|
||||
}
|
||||
|
||||
public static List<SecurityGroupResultObject> transposeNetworkGroups(List<? extends SecurityGroupRules> groups) {
|
||||
List<SecurityGroupResultObject> resultObjects = new ArrayList<SecurityGroupResultObject>();
|
||||
Map<Long, SecurityGroup> allowedSecurityGroups = new HashMap<Long, SecurityGroup>();
|
||||
Map<Long, Account> accounts = new HashMap<Long, Account>();
|
||||
|
||||
if ((groups != null) && !groups.isEmpty()) {
|
||||
List<IngressRuleResultObject> ingressDataList = new ArrayList<IngressRuleResultObject>();
|
||||
SecurityGroupResultObject currentGroup = null;
|
||||
|
||||
List<Long> processedGroups = new ArrayList<Long>();
|
||||
for (SecurityGroupRules netGroupRule : groups) {
|
||||
Long groupId = netGroupRule.getId();
|
||||
if (!processedGroups.contains(groupId)) {
|
||||
processedGroups.add(groupId);
|
||||
|
||||
if (currentGroup != null) {
|
||||
if (!ingressDataList.isEmpty()) {
|
||||
currentGroup.setIngressRules(ingressDataList);
|
||||
ingressDataList = new ArrayList<IngressRuleResultObject>();
|
||||
}
|
||||
resultObjects.add(currentGroup);
|
||||
}
|
||||
|
||||
// start a new group
|
||||
SecurityGroupResultObject groupResult = new SecurityGroupResultObject();
|
||||
groupResult.setId(netGroupRule.getId());
|
||||
groupResult.setName(netGroupRule.getName());
|
||||
groupResult.setDescription(netGroupRule.getDescription());
|
||||
groupResult.setDomainId(netGroupRule.getDomainId());
|
||||
|
||||
Account account = accounts.get(netGroupRule.getAccountId());
|
||||
if (account == null) {
|
||||
account = ApiDBUtils.findAccountById(netGroupRule.getAccountId());
|
||||
accounts.put(account.getId(), account);
|
||||
}
|
||||
|
||||
groupResult.setAccountId(account.getId());
|
||||
groupResult.setAccountName(account.getAccountName());
|
||||
|
||||
currentGroup = groupResult;
|
||||
}
|
||||
|
||||
if (netGroupRule.getRuleId() != null) {
|
||||
// there's at least one ingress rule for this network group, add the ingress rule data
|
||||
IngressRuleResultObject ingressData = new IngressRuleResultObject();
|
||||
ingressData.setEndPort(netGroupRule.getEndPort());
|
||||
ingressData.setStartPort(netGroupRule.getStartPort());
|
||||
ingressData.setId(netGroupRule.getRuleId());
|
||||
ingressData.setProtocol(netGroupRule.getProtocol());
|
||||
|
||||
Long allowedSecurityGroupId = netGroupRule.getAllowedNetworkId();
|
||||
if (allowedSecurityGroupId != null) {
|
||||
SecurityGroup allowedSecurityGroup = allowedSecurityGroups.get(allowedSecurityGroupId);
|
||||
if (allowedSecurityGroup == null) {
|
||||
allowedSecurityGroup = ApiDBUtils.findSecurityGroupById(allowedSecurityGroupId);
|
||||
allowedSecurityGroups.put(allowedSecurityGroupId, allowedSecurityGroup);
|
||||
}
|
||||
|
||||
ingressData.setAllowedSecurityGroup(allowedSecurityGroup.getName());
|
||||
|
||||
Account allowedAccount = accounts.get(allowedSecurityGroup.getAccountId());
|
||||
if (allowedAccount == null) {
|
||||
allowedAccount = ApiDBUtils.findAccountById(allowedSecurityGroup.getAccountId());
|
||||
accounts.put(allowedAccount.getId(), allowedAccount);
|
||||
}
|
||||
|
||||
ingressData.setAllowedSecGroupAcct(allowedAccount.getAccountName());
|
||||
} else if (netGroupRule.getAllowedSourceIpCidr() != null) {
|
||||
ingressData.setAllowedSourceIpCidr(netGroupRule.getAllowedSourceIpCidr());
|
||||
}
|
||||
ingressDataList.add(ingressData);
|
||||
}
|
||||
}
|
||||
|
||||
// all rules have been processed, add the final data into the list
|
||||
if (currentGroup != null) {
|
||||
if (!ingressDataList.isEmpty()) {
|
||||
currentGroup.setIngressRules(ingressDataList);
|
||||
}
|
||||
resultObjects.add(currentGroup);
|
||||
}
|
||||
}
|
||||
return resultObjects;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -1301,7 +1301,6 @@ CREATE TABLE `cloud`.`security_group` (
|
|||
`description` varchar(4096) NULL,
|
||||
`domain_id` bigint unsigned NOT NULL,
|
||||
`account_id` bigint unsigned NOT NULL,
|
||||
`account_name` varchar(100) NOT NULL,
|
||||
PRIMARY KEY (`id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
||||
|
||||
|
|
@ -1312,8 +1311,6 @@ CREATE TABLE `cloud`.`security_ingress_rule` (
|
|||
`end_port` varchar(10) default NULL,
|
||||
`protocol` varchar(16) NOT NULL default 'TCP',
|
||||
`allowed_network_id` bigint unsigned,
|
||||
`allowed_security_group` varchar(255) COMMENT 'data duplicated from security_group table to avoid lots of joins when listing rules (the name of the group should be displayed rather than just id)',
|
||||
`allowed_sec_grp_acct` varchar(100) COMMENT 'data duplicated from security_group table to avoid lots of joins when listing rules (the name of the group owner should be displayed)',
|
||||
`allowed_ip_cidr` varchar(44),
|
||||
`create_status` varchar(32) COMMENT 'rule creation status',
|
||||
PRIMARY KEY (`id`)
|
||||
|
|
|
|||
|
|
@ -23,4 +23,10 @@ ALTER TABLE `cloud`.`secondary_storage_vm` ADD COLUMN `role` varchar(64) NOT NUL
|
|||
INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) VALUES ('Network', 'DEFAULT', 'management-server', 'vm.network.throttling.rate', 200, 'Default data transfer rate in megabits per second allowed in user vm\'s default network.');
|
||||
|
||||
ALTER TABLE `cloud`.`host_pod_ref` ADD COLUMN `removed` datetime COMMENT 'date removed if not null';
|
||||
ALTER TABLE `cloud`.`host_pod_ref` MODIFY `name` varchar(255);
|
||||
ALTER TABLE `cloud`.`host_pod_ref` MODIFY `name` varchar(255);
|
||||
|
||||
ALTER TABLE `cloud`.`security_group` DROP COLUMN `account_name`;
|
||||
|
||||
ALTER TABLE `cloud`.`security_ingress_rule` DROP COLUMN `allowed_security_group`;
|
||||
ALTER TABLE `cloud`.`security_ingress_rule` DROP COLUMN `allowed_sec_grp_acct`;
|
||||
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
Loading…
Reference in New Issue