diff --git a/api/src/com/cloud/api/commands/AuthorizeSecurityGroupIngressCmd.java b/api/src/com/cloud/api/commands/AuthorizeSecurityGroupIngressCmd.java index ae5bc963fb3..1dda17d260b 100644 --- a/api/src/com/cloud/api/commands/AuthorizeSecurityGroupIngressCmd.java +++ b/api/src/com/cloud/api/commands/AuthorizeSecurityGroupIngressCmd.java @@ -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 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 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(""); } - 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 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(); diff --git a/api/src/com/cloud/api/commands/DeleteSecurityGroupCmd.java b/api/src/com/cloud/api/commands/DeleteSecurityGroupCmd.java index e108bffe7ae..ff03a4a5300 100644 --- a/api/src/com/cloud/api/commands/DeleteSecurityGroupCmd.java +++ b/api/src/com/cloud/api/commands/DeleteSecurityGroupCmd.java @@ -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()); + } + } +} diff --git a/api/src/com/cloud/api/commands/RevokeSecurityGroupIngressCmd.java b/api/src/com/cloud/api/commands/RevokeSecurityGroupIngressCmd.java index 4034ccf46b8..0f429f2085b 100644 --- a/api/src/com/cloud/api/commands/RevokeSecurityGroupIngressCmd.java +++ b/api/src/com/cloud/api/commands/RevokeSecurityGroupIngressCmd.java @@ -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(); + } +} diff --git a/api/src/com/cloud/network/security/IngressRule.java b/api/src/com/cloud/network/security/IngressRule.java index baf1bc4b8f5..6eaeabbcbb1 100644 --- a/api/src/com/cloud/network/security/IngressRule.java +++ b/api/src/com/cloud/network/security/IngressRule.java @@ -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(); } diff --git a/api/src/com/cloud/network/security/SecurityGroup.java b/api/src/com/cloud/network/security/SecurityGroup.java index f93bb8af63e..e451f8334fd 100644 --- a/api/src/com/cloud/network/security/SecurityGroup.java +++ b/api/src/com/cloud/network/security/SecurityGroup.java @@ -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(); + } diff --git a/api/src/com/cloud/network/security/SecurityGroupRules.java b/api/src/com/cloud/network/security/SecurityGroupRules.java index c8a279e6ffa..92ad02db00f 100644 --- a/api/src/com/cloud/network/security/SecurityGroupRules.java +++ b/api/src/com/cloud/network/security/SecurityGroupRules.java @@ -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(); } diff --git a/core/src/com/cloud/network/security/IngressRuleVO.java b/core/src/com/cloud/network/security/IngressRuleVO.java index ec29a788741..aeb1170e101 100644 --- a/core/src/com/cloud/network/security/IngressRuleVO.java +++ b/core/src/com/cloud/network/security/IngressRuleVO.java @@ -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; + } +} diff --git a/core/src/com/cloud/network/security/SecurityGroupRulesVO.java b/core/src/com/cloud/network/security/SecurityGroupRulesVO.java index 09446dd6e4e..7485711ff94 100644 --- a/core/src/com/cloud/network/security/SecurityGroupRulesVO.java +++ b/core/src/com/cloud/network/security/SecurityGroupRulesVO.java @@ -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; + } +} diff --git a/core/src/com/cloud/network/security/SecurityGroupVO.java b/core/src/com/cloud/network/security/SecurityGroupVO.java index d5a0b7e8299..9a3cf09b9b0 100644 --- a/core/src/com/cloud/network/security/SecurityGroupVO.java +++ b/core/src/com/cloud/network/security/SecurityGroupVO.java @@ -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; + } +} diff --git a/server/src/com/cloud/api/ApiDBUtils.java b/server/src/com/cloud/api/ApiDBUtils.java index 47ed232fedf..45a13becf5a 100755 --- a/server/src/com/cloud/api/ApiDBUtils.java +++ b/server/src/com/cloud/api/ApiDBUtils.java @@ -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 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 listUsersByAccount(long accountId) { return _userDao.listByAccount(accountId); } @@ -476,17 +474,17 @@ public class ApiDBUtils { public static List 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(); - } 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(); + } 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 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 listVlanByNetworkId(long networkId) { return _vlanDao.listVlansByNetworkId(networkId); } - + public static NetworkVO findNetworkById(long id) { return _networkDao.findById(id); } - + public static Map> 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); } - + } diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index 1a60d0918b1..1f037d74838 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -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 ingressRules) { SecurityGroupResponse response = new SecurityGroupResponse(); + Map securiytGroupAccounts = new HashMap(); + Map allowedSecurityGroups = new HashMap(); + Map allowedSecuriytGroupAccounts = new HashMap(); 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 responses = new ArrayList(); @@ -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()); } diff --git a/server/src/com/cloud/api/ApiServlet.java b/server/src/com/cloud/api/ApiServlet.java index e68fb9f8a81..ec705e3a2fb 100755 --- a/server/src/com/cloud/api/ApiServlet.java +++ b/server/src/com/cloud/api/ApiServlet.java @@ -14,409 +14,408 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . * - */ - -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 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 params = new HashMap(); - 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 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(""); - sb.append("" + inactiveInterval + ""); - 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() + ""); - } - } - } - - sb.append(""); - } - 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("success"); - } - 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 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 params = new HashMap(); + 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 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(""); + sb.append("" + inactiveInterval + ""); + 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() + ""); + } + } + } + + sb.append(""); + } + 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("success"); + } + return sb.toString(); + } + +} diff --git a/server/src/com/cloud/async/executor/IngressRuleResultObject.java b/server/src/com/cloud/api/response/IngressRuleResultObject.java similarity index 95% rename from server/src/com/cloud/async/executor/IngressRuleResultObject.java rename to server/src/com/cloud/api/response/IngressRuleResultObject.java index 028a31ebd85..12d2c054b8d 100644 --- a/server/src/com/cloud/async/executor/IngressRuleResultObject.java +++ b/server/src/com/cloud/api/response/IngressRuleResultObject.java @@ -16,7 +16,7 @@ * */ -package com.cloud.async.executor; +package com.cloud.api.response; import com.cloud.serializer.Param; diff --git a/server/src/com/cloud/async/executor/SecurityGroupResultObject.java b/server/src/com/cloud/api/response/SecurityGroupResultObject.java similarity index 71% rename from server/src/com/cloud/async/executor/SecurityGroupResultObject.java rename to server/src/com/cloud/api/response/SecurityGroupResultObject.java index e7835cbb86f..15050e492c1 100644 --- a/server/src/com/cloud/async/executor/SecurityGroupResultObject.java +++ b/server/src/com/cloud/api/response/SecurityGroupResultObject.java @@ -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 ingressRules = null; - - public SecurityGroupResultObject() {} - - public SecurityGroupResultObject(Long id, String name, String description, Long domainId, Long accountId, String accountName, List 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 getIngressRules() { - return ingressRules; - } - - public void setIngressRules(List ingressRules) { - this.ingressRules = ingressRules; - } - - public static List transposeNetworkGroups(List groups) { - List resultObjects = new ArrayList(); - - if ((groups != null) && !groups.isEmpty()) { - List ingressDataList = new ArrayList(); - SecurityGroupResultObject currentGroup = null; - - List processedGroups = new ArrayList(); - 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(); - } - 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 ingressRules = null; + + public SecurityGroupResultObject() { + } + + public SecurityGroupResultObject(Long id, String name, String description, Long domainId, Long accountId, String accountName, List 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 getIngressRules() { + return ingressRules; + } + + public void setIngressRules(List ingressRules) { + this.ingressRules = ingressRules; + } + + public static List transposeNetworkGroups(List groups) { + List resultObjects = new ArrayList(); + Map allowedSecurityGroups = new HashMap(); + Map accounts = new HashMap(); + + if ((groups != null) && !groups.isEmpty()) { + List ingressDataList = new ArrayList(); + SecurityGroupResultObject currentGroup = null; + + List processedGroups = new ArrayList(); + 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(); + } + 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; + } +} diff --git a/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java b/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java index 84113071afe..741e0d52375 100755 --- a/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java +++ b/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java @@ -50,6 +50,7 @@ import com.cloud.api.commands.DeleteSecurityGroupCmd; import com.cloud.api.commands.ListSecurityGroupsCmd; import com.cloud.api.commands.RevokeSecurityGroupIngressCmd; import com.cloud.configuration.dao.ConfigurationDao; +import com.cloud.domain.Domain; import com.cloud.domain.DomainVO; import com.cloud.domain.dao.DomainDao; import com.cloud.event.ActionEvent; @@ -70,6 +71,7 @@ import com.cloud.network.security.dao.SecurityGroupWorkDao; import com.cloud.network.security.dao.VmRulesetLogDao; import com.cloud.server.ManagementServer; import com.cloud.user.Account; +import com.cloud.user.AccountManager; import com.cloud.user.AccountVO; import com.cloud.user.UserContext; import com.cloud.user.dao.AccountDao; @@ -100,403 +102,429 @@ import com.cloud.vm.VirtualMachineManager; import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.VMInstanceDao; -@Local(value={SecurityGroupManager.class, SecurityGroupService.class}) +@Local(value = { SecurityGroupManager.class, SecurityGroupService.class }) public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityGroupService, Manager, StateListener { public static final Logger s_logger = Logger.getLogger(SecurityGroupManagerImpl.class); - @Inject SecurityGroupDao _securityGroupDao; - @Inject IngressRuleDao _ingressRuleDao; - @Inject SecurityGroupVMMapDao _securityGroupVMMapDao; - @Inject SecurityGroupRulesDao _securityGroupRulesDao; - @Inject UserVmDao _userVMDao; - @Inject AccountDao _accountDao; - @Inject ConfigurationDao _configDao; - @Inject SecurityGroupWorkDao _workDao; - @Inject VmRulesetLogDao _rulesetLogDao; - @Inject DomainDao _domainDao; - @Inject AgentManager _agentMgr; - @Inject VirtualMachineManager _itMgr; - @Inject UserVmManager _userVmMgr; - @Inject VMInstanceDao _vmDao; - @Inject NetworkManager _networkMgr; - ScheduledExecutorService _executorPool; + @Inject + SecurityGroupDao _securityGroupDao; + @Inject + IngressRuleDao _ingressRuleDao; + @Inject + SecurityGroupVMMapDao _securityGroupVMMapDao; + @Inject + SecurityGroupRulesDao _securityGroupRulesDao; + @Inject + UserVmDao _userVMDao; + @Inject + AccountDao _accountDao; + @Inject + ConfigurationDao _configDao; + @Inject + SecurityGroupWorkDao _workDao; + @Inject + VmRulesetLogDao _rulesetLogDao; + @Inject + DomainDao _domainDao; + @Inject + AgentManager _agentMgr; + @Inject + VirtualMachineManager _itMgr; + @Inject + UserVmManager _userVmMgr; + @Inject + VMInstanceDao _vmDao; + @Inject + NetworkManager _networkMgr; + @Inject + AccountManager _accountMgr; + + ScheduledExecutorService _executorPool; ScheduledExecutorService _cleanupExecutor; - private long _serverId; + private long _serverId; - private final long _timeBetweenCleanups = 30; //seconds + private final long _timeBetweenCleanups = 30; // seconds - SecurityGroupListener _answerListener; - - - private final class SecurityGroupVOComparator implements - Comparator { - @Override - public int compare(SecurityGroupVO o1, SecurityGroupVO o2) { - return o1.getId() == o2.getId() ? 0 : o1.getId() < o2.getId() ? -1 : 1; - } - } + SecurityGroupListener _answerListener; - public class WorkerThread implements Runnable { - @Override - public void run() { - work(); - } - - WorkerThread() { - - } - } - - public class CleanupThread implements Runnable { - @Override - public void run() { - cleanupFinishedWork(); - cleanupUnfinishedWork(); - } - + private final class SecurityGroupVOComparator implements Comparator { + @Override + public int compare(SecurityGroupVO o1, SecurityGroupVO o2) { + return o1.getId() == o2.getId() ? 0 : o1.getId() < o2.getId() ? -1 : 1; + } + } + public class WorkerThread implements Runnable { + @Override + public void run() { + work(); + } - CleanupThread() { - - } - } - - + WorkerThread() { + } + } - - public static class PortAndProto implements Comparable{ - String proto; - int startPort; - int endPort; - public PortAndProto(String proto, int startPort, int endPort) { - this.proto = proto; - this.startPort = startPort; - this.endPort = endPort; - } - public String getProto() { - return proto; - } - public int getStartPort() { - return startPort; - } - public int getEndPort() { - return endPort; - } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + endPort; - result = prime * result + ((proto == null) ? 0 : proto.hashCode()); - result = prime * result + startPort; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { + public class CleanupThread implements Runnable { + @Override + public void run() { + cleanupFinishedWork(); + cleanupUnfinishedWork(); + } + + CleanupThread() { + + } + } + + public static class PortAndProto implements Comparable { + String proto; + int startPort; + int endPort; + + public PortAndProto(String proto, int startPort, int endPort) { + this.proto = proto; + this.startPort = startPort; + this.endPort = endPort; + } + + public String getProto() { + return proto; + } + + public int getStartPort() { + return startPort; + } + + public int getEndPort() { + return endPort; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + endPort; + result = prime * result + ((proto == null) ? 0 : proto.hashCode()); + result = prime * result + startPort; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { return true; } - if (obj == null) { + if (obj == null) { return false; } - if (getClass() != obj.getClass()) { + if (getClass() != obj.getClass()) { return false; } - PortAndProto other = (PortAndProto) obj; - if (endPort != other.endPort) { + PortAndProto other = (PortAndProto) obj; + if (endPort != other.endPort) { return false; } - if (proto == null) { - if (other.proto != null) { + if (proto == null) { + if (other.proto != null) { return false; } - } else if (!proto.equals(other.proto)) { + } else if (!proto.equals(other.proto)) { return false; } - if (startPort != other.startPort) { + if (startPort != other.startPort) { return false; } - return true; - } - - @Override - public int compareTo(PortAndProto obj) { - if (this == obj) { + return true; + } + + @Override + public int compareTo(PortAndProto obj) { + if (this == obj) { return 0; } - if (obj == null) { + if (obj == null) { return 1; } - if (proto == null) { - if (obj.proto != null) { + if (proto == null) { + if (obj.proto != null) { return -1; } else { return 0; } - } - if (!obj.proto.equalsIgnoreCase(proto)) { - return proto.compareTo(obj.proto); - } - if (startPort < obj.startPort) { + } + if (!obj.proto.equalsIgnoreCase(proto)) { + return proto.compareTo(obj.proto); + } + if (startPort < obj.startPort) { return -1; } else if (startPort > obj.startPort) { return 1; } - - if (endPort < obj.endPort) { + + if (endPort < obj.endPort) { return -1; } else if (endPort > obj.endPort) { return 1; } - - return 0; - } - - } - - - public static class CidrComparator implements Comparator { + return 0; + } - @Override - public int compare(String cidr1, String cidr2) { - return cidr1.compareTo(cidr2); //FIXME - } - - } + } - protected Map> generateRulesForVM(Long userVmId){ + public static class CidrComparator implements Comparator { - Map> allowed = new TreeMap>(); + @Override + public int compare(String cidr1, String cidr2) { + return cidr1.compareTo(cidr2); // FIXME + } - List groupsForVm = _securityGroupVMMapDao.listByInstanceId(userVmId); - for (SecurityGroupVMMapVO mapVO: groupsForVm) { - List rules = _ingressRuleDao.listBySecurityGroupId(mapVO.getSecurityGroupId()); - for (IngressRuleVO rule: rules){ - PortAndProto portAndProto = new PortAndProto(rule.getProtocol(), rule.getStartPort(), rule.getEndPort()); - Set cidrs = allowed.get(portAndProto ); - if (cidrs == null) { - cidrs = new TreeSet(new CidrComparator()); - } - if (rule.getAllowedNetworkId() != null){ - List allowedInstances = _securityGroupVMMapDao.listBySecurityGroup(rule.getAllowedNetworkId(), State.Running); - for (SecurityGroupVMMapVO ngmapVO: allowedInstances){ - Nic defaultNic = _networkMgr.getDefaultNic(ngmapVO.getInstanceId()); - if (defaultNic != null) { - String cidr = defaultNic.getIp4Address(); - cidr = cidr + "/32"; - cidrs.add(cidr); - } - } - }else if (rule.getAllowedSourceIpCidr() != null) { - cidrs.add(rule.getAllowedSourceIpCidr()); - } - if (cidrs.size() > 0) { + } + + protected Map> generateRulesForVM(Long userVmId) { + + Map> allowed = new TreeMap>(); + + List groupsForVm = _securityGroupVMMapDao.listByInstanceId(userVmId); + for (SecurityGroupVMMapVO mapVO : groupsForVm) { + List rules = _ingressRuleDao.listBySecurityGroupId(mapVO.getSecurityGroupId()); + for (IngressRuleVO rule : rules) { + PortAndProto portAndProto = new PortAndProto(rule.getProtocol(), rule.getStartPort(), rule.getEndPort()); + Set cidrs = allowed.get(portAndProto); + if (cidrs == null) { + cidrs = new TreeSet(new CidrComparator()); + } + if (rule.getAllowedNetworkId() != null) { + List allowedInstances = _securityGroupVMMapDao.listBySecurityGroup(rule.getAllowedNetworkId(), State.Running); + for (SecurityGroupVMMapVO ngmapVO : allowedInstances) { + Nic defaultNic = _networkMgr.getDefaultNic(ngmapVO.getInstanceId()); + if (defaultNic != null) { + String cidr = defaultNic.getIp4Address(); + cidr = cidr + "/32"; + cidrs.add(cidr); + } + } + } else if (rule.getAllowedSourceIpCidr() != null) { + cidrs.add(rule.getAllowedSourceIpCidr()); + } + if (cidrs.size() > 0) { allowed.put(portAndProto, cidrs); } - } - } + } + } + return allowed; + } - return allowed; - } - - private String generateRulesetSignature(Map> allowed) { - String ruleset = allowed.toString(); - return DigestUtils.md5Hex(ruleset); - } + private String generateRulesetSignature(Map> allowed) { + String ruleset = allowed.toString(); + return DigestUtils.md5Hex(ruleset); + } - protected void handleVmStarted(VMInstanceVO vm) { - if (vm.getType() != VirtualMachine.Type.User || !isVmSecurityGroupEnabled(vm.getId())) - return; - Set affectedVms = getAffectedVmsForVmStart(vm); - scheduleRulesetUpdateToHosts(affectedVms, true, null); - } - - @DB - public void scheduleRulesetUpdateToHosts(Set affectedVms, boolean updateSeqno, Long delayMs) { - if (delayMs == null) { + protected void handleVmStarted(VMInstanceVO vm) { + if (vm.getType() != VirtualMachine.Type.User || !isVmSecurityGroupEnabled(vm.getId())) + return; + Set affectedVms = getAffectedVmsForVmStart(vm); + scheduleRulesetUpdateToHosts(affectedVms, true, null); + } + + @DB + public void scheduleRulesetUpdateToHosts(Set affectedVms, boolean updateSeqno, Long delayMs) { + if (delayMs == null) { delayMs = new Long(100l); } - - for (Long vmId: affectedVms) { - - VmRulesetLogVO log = null; - SecurityGroupWorkVO work = null; - UserVm vm = null; - Transaction txn = null; - try { - txn = Transaction.currentTxn(); - txn.start(); - - vm = _userVMDao.acquireInLockTable(vmId); - if (vm == null) { - s_logger.warn("Failed to acquire lock on vm id " + vmId); - continue; - } - log = _rulesetLogDao.findByVmId(vmId); - if (log == null) { - log = new VmRulesetLogVO(vmId); - log = _rulesetLogDao.persist(log); - } - - if (log != null && updateSeqno){ - log.incrLogsequence(); - _rulesetLogDao.update(log.getId(), log); - } - work = _workDao.findByVmIdStep(vmId, Step.Scheduled); - if (work == null) { - work = new SecurityGroupWorkVO(vmId, null, null, SecurityGroupWorkVO.Step.Scheduled, null); - work = _workDao.persist(work); - } - - work.setLogsequenceNumber(log.getLogsequence()); - _workDao.update(work.getId(), work); - - } finally { - if (vm != null) { - _userVMDao.releaseFromLockTable(vmId); - } - - if (txn != null) - txn.commit(); - } - _executorPool.schedule(new WorkerThread(), delayMs, TimeUnit.MILLISECONDS); + for (Long vmId : affectedVms) { - } - } - - protected Set getAffectedVmsForVmStart(VMInstanceVO vm) { - Set affectedVms = new HashSet(); - affectedVms.add(vm.getId()); - List groupsForVm = _securityGroupVMMapDao.listByInstanceId(vm.getId()); - //For each group, find the ingress rules that allow the group - for (SecurityGroupVMMapVO mapVO: groupsForVm) {//FIXME: use custom sql in the dao - List allowingRules = _ingressRuleDao.listByAllowedSecurityGroupId(mapVO.getSecurityGroupId()); - //For each ingress rule that allows a group that the vm belongs to, find the group it belongs to - affectedVms.addAll(getAffectedVmsForIngressRules(allowingRules)); - } - return affectedVms; - } - - protected Set getAffectedVmsForVmStop(VMInstanceVO vm) { - Set affectedVms = new HashSet(); - List groupsForVm = _securityGroupVMMapDao.listByInstanceId(vm.getId()); - //For each group, find the ingress rules that allow the group - for (SecurityGroupVMMapVO mapVO: groupsForVm) {//FIXME: use custom sql in the dao - List allowingRules = _ingressRuleDao.listByAllowedSecurityGroupId(mapVO.getSecurityGroupId()); - //For each ingress rule that allows a group that the vm belongs to, find the group it belongs to - affectedVms.addAll(getAffectedVmsForIngressRules(allowingRules)); - } - return affectedVms; - } - - - protected Set getAffectedVmsForIngressRules(List allowingRules) { - Set distinctGroups = new HashSet (); - Set affectedVms = new HashSet(); + VmRulesetLogVO log = null; + SecurityGroupWorkVO work = null; + UserVm vm = null; + Transaction txn = null; + try { + txn = Transaction.currentTxn(); + txn.start(); - for (IngressRuleVO allowingRule: allowingRules){ - distinctGroups.add(allowingRule.getSecurityGroupId()); - } - for (Long groupId: distinctGroups){ - //allVmUpdates.putAll(generateRulesetForGroupMembers(groupId)); - affectedVms.addAll(_securityGroupVMMapDao.listVmIdsBySecurityGroup(groupId)); - } - return affectedVms; - } + vm = _userVMDao.acquireInLockTable(vmId); + if (vm == null) { + s_logger.warn("Failed to acquire lock on vm id " + vmId); + continue; + } + log = _rulesetLogDao.findByVmId(vmId); + if (log == null) { + log = new VmRulesetLogVO(vmId); + log = _rulesetLogDao.persist(log); + } - - - protected SecurityIngressRulesCmd generateRulesetCmd(String vmName, String guestIp, String guestMac, Long vmId, String signature, long seqnum, Map> rules) { - List result = new ArrayList(); - for (PortAndProto pAp : rules.keySet()) { - Set cidrs = rules.get(pAp); - if (cidrs.size() > 0) { - IpPortAndProto ipPortAndProto = new SecurityIngressRulesCmd.IpPortAndProto(pAp.getProto(), pAp.getStartPort(), pAp.getEndPort(), cidrs.toArray(new String[cidrs.size()])); - result.add(ipPortAndProto); - } - } - return new SecurityIngressRulesCmd(guestIp, guestMac, vmName, vmId, signature, seqnum, result.toArray(new IpPortAndProto[result.size()])); - } - - protected void handleVmStopped(VMInstanceVO vm) { - if (vm.getType() != VirtualMachine.Type.User || !isVmSecurityGroupEnabled(vm.getId())) + if (log != null && updateSeqno) { + log.incrLogsequence(); + _rulesetLogDao.update(log.getId(), log); + } + work = _workDao.findByVmIdStep(vmId, Step.Scheduled); + if (work == null) { + work = new SecurityGroupWorkVO(vmId, null, null, SecurityGroupWorkVO.Step.Scheduled, null); + work = _workDao.persist(work); + } + + work.setLogsequenceNumber(log.getLogsequence()); + _workDao.update(work.getId(), work); + + } finally { + if (vm != null) { + _userVMDao.releaseFromLockTable(vmId); + } + + if (txn != null) + txn.commit(); + } + + _executorPool.schedule(new WorkerThread(), delayMs, TimeUnit.MILLISECONDS); + + } + } + + protected Set getAffectedVmsForVmStart(VMInstanceVO vm) { + Set affectedVms = new HashSet(); + affectedVms.add(vm.getId()); + List groupsForVm = _securityGroupVMMapDao.listByInstanceId(vm.getId()); + // For each group, find the ingress rules that allow the group + for (SecurityGroupVMMapVO mapVO : groupsForVm) {// FIXME: use custom sql in the dao + List allowingRules = _ingressRuleDao.listByAllowedSecurityGroupId(mapVO.getSecurityGroupId()); + // For each ingress rule that allows a group that the vm belongs to, find the group it belongs to + affectedVms.addAll(getAffectedVmsForIngressRules(allowingRules)); + } + return affectedVms; + } + + protected Set getAffectedVmsForVmStop(VMInstanceVO vm) { + Set affectedVms = new HashSet(); + List groupsForVm = _securityGroupVMMapDao.listByInstanceId(vm.getId()); + // For each group, find the ingress rules that allow the group + for (SecurityGroupVMMapVO mapVO : groupsForVm) {// FIXME: use custom sql in the dao + List allowingRules = _ingressRuleDao.listByAllowedSecurityGroupId(mapVO.getSecurityGroupId()); + // For each ingress rule that allows a group that the vm belongs to, find the group it belongs to + affectedVms.addAll(getAffectedVmsForIngressRules(allowingRules)); + } + return affectedVms; + } + + protected Set getAffectedVmsForIngressRules(List allowingRules) { + Set distinctGroups = new HashSet(); + Set affectedVms = new HashSet(); + + for (IngressRuleVO allowingRule : allowingRules) { + distinctGroups.add(allowingRule.getSecurityGroupId()); + } + for (Long groupId : distinctGroups) { + // allVmUpdates.putAll(generateRulesetForGroupMembers(groupId)); + affectedVms.addAll(_securityGroupVMMapDao.listVmIdsBySecurityGroup(groupId)); + } + return affectedVms; + } + + protected SecurityIngressRulesCmd generateRulesetCmd(String vmName, String guestIp, String guestMac, Long vmId, String signature, long seqnum, Map> rules) { + List result = new ArrayList(); + for (PortAndProto pAp : rules.keySet()) { + Set cidrs = rules.get(pAp); + if (cidrs.size() > 0) { + IpPortAndProto ipPortAndProto = new SecurityIngressRulesCmd.IpPortAndProto(pAp.getProto(), pAp.getStartPort(), pAp.getEndPort(), cidrs.toArray(new String[cidrs.size()])); + result.add(ipPortAndProto); + } + } + return new SecurityIngressRulesCmd(guestIp, guestMac, vmName, vmId, signature, seqnum, result.toArray(new IpPortAndProto[result.size()])); + } + + protected void handleVmStopped(VMInstanceVO vm) { + if (vm.getType() != VirtualMachine.Type.User || !isVmSecurityGroupEnabled(vm.getId())) return; - Set affectedVms = getAffectedVmsForVmStop(vm); - scheduleRulesetUpdateToHosts(affectedVms, true, null); - } - - protected void handleVmMigrated(VMInstanceVO vm) { - if (!isVmSecurityGroupEnabled(vm.getId())) - return; - if (vm.getType() != VirtualMachine.Type.User) { - Commands cmds = null; - NetworkRulesSystemVmCommand nrc = new NetworkRulesSystemVmCommand(vm.getInstanceName(), vm.getType()); - cmds = new Commands(nrc); - try { - _agentMgr.send(vm.getHostId(), cmds); - } catch (AgentUnavailableException e) { - s_logger.debug(e.toString()); - } catch (OperationTimedoutException e) { - s_logger.debug(e.toString()); - } + Set affectedVms = getAffectedVmsForVmStop(vm); + scheduleRulesetUpdateToHosts(affectedVms, true, null); + } - } else { - Set affectedVms = new HashSet(); - affectedVms.add(vm.getId()); - scheduleRulesetUpdateToHosts(affectedVms, true, null); - } - } - - @Override @DB @SuppressWarnings("rawtypes") - public List authorizeSecurityGroupIngress(AuthorizeSecurityGroupIngressCmd cmd){ - Long groupId = cmd.getSecurityGroupId(); - String protocol = cmd.getProtocol(); - Integer startPort = cmd.getStartPort(); - Integer endPort = cmd.getEndPort(); - Integer icmpType = cmd.getIcmpType(); - Integer icmpCode = cmd.getIcmpCode(); - List cidrList = cmd.getCidrList(); - Map groupList = cmd.getUserSecurityGroupList(); - Account account = UserContext.current().getCaller(); - String accountName = cmd.getAccountName(); - Long domainId = cmd.getDomainId(); - Integer startPortOrType = null; + protected void handleVmMigrated(VMInstanceVO vm) { + if (!isVmSecurityGroupEnabled(vm.getId())) + return; + if (vm.getType() != VirtualMachine.Type.User) { + Commands cmds = null; + NetworkRulesSystemVmCommand nrc = new NetworkRulesSystemVmCommand(vm.getInstanceName(), vm.getType()); + cmds = new Commands(nrc); + try { + _agentMgr.send(vm.getHostId(), cmds); + } catch (AgentUnavailableException e) { + s_logger.debug(e.toString()); + } catch (OperationTimedoutException e) { + s_logger.debug(e.toString()); + } + + } else { + Set affectedVms = new HashSet(); + affectedVms.add(vm.getId()); + scheduleRulesetUpdateToHosts(affectedVms, true, null); + } + } + + @Override + @DB + @SuppressWarnings("rawtypes") + public List authorizeSecurityGroupIngress(AuthorizeSecurityGroupIngressCmd cmd) { + Long securityGroupId = cmd.getSecurityGroupId(); + String protocol = cmd.getProtocol(); + Integer startPort = cmd.getStartPort(); + Integer endPort = cmd.getEndPort(); + Integer icmpType = cmd.getIcmpType(); + Integer icmpCode = cmd.getIcmpCode(); + List cidrList = cmd.getCidrList(); + Map groupList = cmd.getUserSecurityGroupList(); + Integer startPortOrType = null; Integer endPortOrCode = null; - Long accountId = null; - - //Verify input parameters + + // Validate parameters + SecurityGroup securityGroup = _securityGroupDao.findById(securityGroupId); + if (securityGroup == null) { + throw new InvalidParameterValueException("Unable to find security group by id " + securityGroupId); + } + + if (cidrList == null && groupList == null) { + throw new InvalidParameterValueException("At least one cidr or at least one security group needs to be specified"); + } + + Account caller = UserContext.current().getCaller(); + Account owner = _accountMgr.getAccount(securityGroup.getAccountId()); + + if (owner == null) { + throw new InvalidParameterValueException("Unable to find security group owner by id=" + securityGroup.getAccountId()); + } + + // Verify permissions + _accountMgr.checkAccess(caller, securityGroup); + Long domainId = owner.getDomainId(); + if (protocol == null) { - protocol = "all"; + protocol = NetUtils.ALL_PROTO; } if (!NetUtils.isValidSecurityGroupProto(protocol)) { - s_logger.debug("Invalid protocol specified " + protocol); - throw new InvalidParameterValueException("Invalid protocol " + protocol); + throw new InvalidParameterValueException("Invalid protocol " + protocol); } - if ("icmp".equalsIgnoreCase(protocol) ) { + if ("icmp".equalsIgnoreCase(protocol)) { if ((icmpType == null) || (icmpCode == null)) { throw new InvalidParameterValueException("Invalid ICMP type/code specified, icmpType = " + icmpType + ", icmpCode = " + icmpCode); } - if (icmpType == -1 && icmpCode != -1) { - throw new InvalidParameterValueException("Invalid icmp type range" ); - } - if (icmpCode > 255) { - throw new InvalidParameterValueException("Invalid icmp code " ); - } - startPortOrType = icmpType; - endPortOrCode= icmpCode; - } else if (protocol.equals("all")) { - if ((startPort != null) || (endPort != null)) { + if (icmpType == -1 && icmpCode != -1) { + throw new InvalidParameterValueException("Invalid icmp type range"); + } + if (icmpCode > 255) { + throw new InvalidParameterValueException("Invalid icmp code "); + } + startPortOrType = icmpType; + endPortOrCode = icmpCode; + } else if (protocol.equals(NetUtils.ALL_PROTO)) { + if ((startPort != null) || (endPort != null)) { throw new InvalidParameterValueException("Cannot specify startPort or endPort without specifying protocol"); } - startPortOrType = 0; - endPortOrCode = 0; + startPortOrType = 0; + endPortOrCode = 0; } else { if ((startPort == null) || (endPort == null)) { throw new InvalidParameterValueException("Invalid port range specified, startPort = " + startPort + ", endPort = " + endPort); @@ -505,648 +533,457 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG endPort = 65535; } if (startPort > endPort) { - s_logger.debug("Invalid port range specified: " + startPort + ":" + endPort); - throw new InvalidParameterValueException("Invalid port range " ); + throw new InvalidParameterValueException("Invalid port range " + startPort + ":" + endPort); } if (startPort > 65535 || endPort > 65535 || startPort < -1 || endPort < -1) { - s_logger.debug("Invalid port numbers specified: " + startPort + ":" + endPort); - throw new InvalidParameterValueException("Invalid port numbers " ); + throw new InvalidParameterValueException("Invalid port numbers " + startPort + ":" + endPort); + } + + if (startPort < 0 || endPort < 0) { + throw new InvalidParameterValueException("Invalid port range " + startPort + ":" + endPort); } - - if (startPort < 0 || endPort < 0) { - throw new InvalidParameterValueException("Invalid port range " ); - } startPortOrType = startPort; - endPortOrCode= endPort; + endPortOrCode = endPort; } - + protocol = protocol.toLowerCase(); - if ((account == null) || isAdmin(account.getType())) { - if ((accountName != null) && (domainId != null)) { - // if it's an admin account, do a quick permission check - if ((account != null) && !_domainDao.isChildDomain(account.getDomainId(), domainId)) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Unable to find rules for security group id = " + groupId + ", permission denied."); - } - throw new PermissionDeniedException("Unable to find rules for security group id = " + groupId + ", permission denied."); - } - - Account groupOwner = _accountDao.findActiveAccount(accountName, domainId); - if (groupOwner == null) { - throw new PermissionDeniedException("Unable to find account " + accountName + " in domain " + domainId); - } - accountId = groupOwner.getId(); - } else { - if (account != null) { - accountId = account.getId(); - domainId = account.getDomainId(); - } - } - } else { - if (account != null) { - accountId = account.getId(); - domainId = account.getDomainId(); - } - } - - if (accountId == null) { - throw new InvalidParameterValueException("Unable to find account for security group " + groupId + "; failed to authorize ingress."); - } - - - if (cidrList == null && groupList == null) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("At least one cidr or at least one security group needs to be specified"); - } - throw new InvalidParameterValueException("At least one cidr or at least one security group needs to be specified"); - } - - List authorizedGroups = new ArrayList (); + List authorizedGroups = new ArrayList(); if (groupList != null) { Collection userGroupCollection = groupList.values(); Iterator iter = userGroupCollection.iterator(); while (iter.hasNext()) { - HashMap userGroup = (HashMap)iter.next(); - String group = (String)userGroup.get("group"); - String authorizedAccountName = (String)userGroup.get("account"); - if ((group == null) || (authorizedAccountName == null)) { - throw new InvalidParameterValueException("Invalid user group specified, fields 'group' and 'account' cannot be null, please specify groups in the form: userGroupList[0].group=XXX&userGroupList[0].account=YYY"); - } + HashMap userGroup = (HashMap) iter.next(); + String group = (String) userGroup.get("group"); + String authorizedAccountName = (String) userGroup.get("account"); - Account authorizedAccount = _accountDao.findActiveAccount(authorizedAccountName, domainId); - if (authorizedAccount == null) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Nonexistent account: " + authorizedAccountName + ", domainid: " + domainId + " when trying to authorize ingress for " + groupId + ":" + protocol + ":" + startPortOrType + ":" + endPortOrCode); - } - throw new InvalidParameterValueException("Nonexistent account: " + authorizedAccountName + " when trying to authorize ingress for " + groupId + ":" + protocol + ":" + startPortOrType + ":" + endPortOrCode); - } + if ((group == null) || (authorizedAccountName == null)) { + throw new InvalidParameterValueException( + "Invalid user group specified, fields 'group' and 'account' cannot be null, please specify groups in the form: userGroupList[0].group=XXX&userGroupList[0].account=YYY"); + } - SecurityGroupVO groupVO = _securityGroupDao.findByAccountAndName(authorizedAccount.getId(), group); - if (groupVO == null) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Nonexistent group " + group + " for account " + authorizedAccountName + "/" + domainId); - } - throw new InvalidParameterValueException("Invalid group (" + group + ") given, unable to authorize ingress."); - } - authorizedGroups.add(groupVO); - } + Account authorizedAccount = _accountDao.findActiveAccount(authorizedAccountName, domainId); + if (authorizedAccount == null) { + throw new InvalidParameterValueException("Nonexistent account: " + authorizedAccountName + " when trying to authorize ingress for " + securityGroupId + ":" + protocol + ":" + + startPortOrType + ":" + endPortOrCode); + } + + SecurityGroupVO groupVO = _securityGroupDao.findByAccountAndName(authorizedAccount.getId(), group); + if (groupVO == null) { + throw new InvalidParameterValueException("Nonexistent group " + group + " for account " + authorizedAccountName + "/" + domainId + " is given, unable to authorize ingress."); + } + + // Check permissions + _accountMgr.checkAccess(caller, groupVO); + + authorizedGroups.add(groupVO); + } } - + final Transaction txn = Transaction.currentTxn(); - final Set authorizedGroups2 = new TreeSet(new SecurityGroupVOComparator()); + final Set authorizedGroups2 = new TreeSet(new SecurityGroupVOComparator()); - authorizedGroups2.addAll(authorizedGroups); //Ensure we don't re-lock the same row - txn.start(); - SecurityGroupVO securityGroup = _securityGroupDao.findById(groupId); - if (securityGroup == null) { - s_logger.warn("Security group not found: id= " + groupId); - return null; - } - //Prevents other threads/management servers from creating duplicate ingress rules - SecurityGroupVO securityGroupLock = _securityGroupDao.acquireInLockTable(securityGroup.getId()); - if (securityGroupLock == null) { - s_logger.warn("Could not acquire lock on network security group: name= " + securityGroup.getName()); - return null; - } - List newRules = new ArrayList(); - try { - //Don't delete the group from under us. - securityGroup = _securityGroupDao.lockRow(securityGroup.getId(), false); - if (securityGroup == null) { - s_logger.warn("Could not acquire lock on network group " + securityGroup.getName()); - return null; - } + authorizedGroups2.addAll(authorizedGroups); // Ensure we don't re-lock the same row + txn.start(); - for (final SecurityGroupVO ngVO: authorizedGroups2) { - final Long ngId = ngVO.getId(); - //Don't delete the referenced group from under us - if (ngVO.getId() != securityGroup.getId()) { - final SecurityGroupVO tmpGrp = _securityGroupDao.lockRow(ngId, false); - if (tmpGrp == null) { - s_logger.warn("Failed to acquire lock on security group: " + ngId); - txn.rollback(); - return null; - } - } - IngressRuleVO ingressRule = _ingressRuleDao.findByProtoPortsAndAllowedGroupId(securityGroup.getId(), protocol, startPortOrType, endPortOrCode, ngVO.getId()); - if (ingressRule != null) { - continue; //rule already exists. - } - ingressRule = new IngressRuleVO(securityGroup.getId(), startPortOrType, endPortOrCode, protocol, ngVO.getId(), ngVO.getName(), ngVO.getAccountName()); - ingressRule = _ingressRuleDao.persist(ingressRule); - newRules.add(ingressRule); - } - if(cidrList != null) { - for (String cidr: cidrList) { - IngressRuleVO ingressRule = _ingressRuleDao.findByProtoPortsAndCidr(securityGroup.getId(),protocol, startPortOrType, endPortOrCode, cidr); - if (ingressRule != null) { - continue; - } - ingressRule = new IngressRuleVO(securityGroup.getId(), startPortOrType, endPortOrCode, protocol, cidr); - ingressRule = _ingressRuleDao.persist(ingressRule); - newRules.add(ingressRule); - } - } - if (s_logger.isDebugEnabled()) { - s_logger.debug("Added " + newRules.size() + " rules to security group " + securityGroup.getName()); - } - txn.commit(); - final Set affectedVms = new HashSet(); - affectedVms.addAll(_securityGroupVMMapDao.listVmIdsBySecurityGroup(securityGroup.getId())); - scheduleRulesetUpdateToHosts(affectedVms, true, null); - return newRules; - } catch (Exception e){ - s_logger.warn("Exception caught when adding ingress rules ", e); - throw new CloudRuntimeException("Exception caught when adding ingress rules", e); - } finally { - if (securityGroupLock != null) { - _securityGroupDao.releaseFromLockTable(securityGroupLock.getId()); - } - } - } - - @Override - @DB - public boolean revokeSecurityGroupIngress(RevokeSecurityGroupIngressCmd cmd) { - //input validation - Account account = UserContext.current().getCaller(); - Long domainId = cmd.getDomainId(); - String accountName = cmd.getAccountName(); - Long id = cmd.getId(); - Long accountId = null; - SecurityGroupVO groupHandle = null; - if ((account == null) || isAdmin(account.getType())) { - if ((accountName != null) && (domainId != null)) { - // if it's an admin account, do a quick permission check - if ((account != null) && !_domainDao.isChildDomain(account.getDomainId(), domainId)) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Unable to revoke ingress rule id = " + id + ", permission denied."); + // Prevents other threads/management servers from creating duplicate ingress rules + securityGroup = _securityGroupDao.acquireInLockTable(securityGroupId); + if (securityGroup == null) { + s_logger.warn("Could not acquire lock on network security group: id= " + securityGroupId); + return null; + } + List newRules = new ArrayList(); + try { + for (final SecurityGroupVO ngVO : authorizedGroups2) { + final Long ngId = ngVO.getId(); + // Don't delete the referenced group from under us + if (ngVO.getId() != securityGroup.getId()) { + final SecurityGroupVO tmpGrp = _securityGroupDao.lockRow(ngId, false); + if (tmpGrp == null) { + s_logger.warn("Failed to acquire lock on security group: " + ngId); + txn.rollback(); + return null; } - throw new PermissionDeniedException("Unable to revoke ingress rule id = " + id + ", permission denied."); } - Account groupOwner = _accountDao.findActiveAccount(accountName, domainId); - if (groupOwner == null) { - throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId); + IngressRuleVO ingressRule = _ingressRuleDao.findByProtoPortsAndAllowedGroupId(securityGroup.getId(), protocol, startPortOrType, endPortOrCode, ngVO.getId()); + if (ingressRule != null) { + continue; // rule already exists. } - accountId = groupOwner.getId(); - } else { - if (account != null) { - accountId = account.getId(); - domainId = account.getDomainId(); + ingressRule = new IngressRuleVO(securityGroup.getId(), startPortOrType, endPortOrCode, protocol, ngVO.getId()); + ingressRule = _ingressRuleDao.persist(ingressRule); + newRules.add(ingressRule); + } + if (cidrList != null) { + for (String cidr : cidrList) { + IngressRuleVO ingressRule = _ingressRuleDao.findByProtoPortsAndCidr(securityGroup.getId(), protocol, startPortOrType, endPortOrCode, cidr); + if (ingressRule != null) { + continue; + } + ingressRule = new IngressRuleVO(securityGroup.getId(), startPortOrType, endPortOrCode, protocol, cidr); + ingressRule = _ingressRuleDao.persist(ingressRule); + newRules.add(ingressRule); } } - } else { - if (account != null) { - accountId = account.getId(); - domainId = account.getDomainId(); + if (s_logger.isDebugEnabled()) { + s_logger.debug("Added " + newRules.size() + " rules to security group " + securityGroup.getName()); + } + txn.commit(); + final Set affectedVms = new HashSet(); + affectedVms.addAll(_securityGroupVMMapDao.listVmIdsBySecurityGroup(securityGroup.getId())); + scheduleRulesetUpdateToHosts(affectedVms, true, null); + return newRules; + } catch (Exception e) { + s_logger.warn("Exception caught when adding ingress rules ", e); + throw new CloudRuntimeException("Exception caught when adding ingress rules", e); + } finally { + if (securityGroup != null) { + _securityGroupDao.releaseFromLockTable(securityGroup.getId()); } } + } - if (accountId == null) { - throw new InvalidParameterValueException("Unable to find account for ingress rule id:" + id + "; failed to revoke ingress."); - } + @Override + @DB + public boolean revokeSecurityGroupIngress(RevokeSecurityGroupIngressCmd cmd) { + // input validation + Account caller = UserContext.current().getCaller(); + Long id = cmd.getId(); IngressRuleVO rule = _ingressRuleDao.findById(id); if (rule == null) { s_logger.debug("Unable to find ingress rule with id " + id); throw new InvalidParameterValueException("Unable to find ingress rule with id " + id); } - + + // Check permissions + SecurityGroup securityGroup = _securityGroupDao.findById(rule.getSecurityGroupId()); + _accountMgr.checkAccess(caller, securityGroup); + + SecurityGroupVO groupHandle = null; final Transaction txn = Transaction.currentTxn(); - try { - txn.start(); - //acquire lock on parent group (preserving this logic) - groupHandle = _securityGroupDao.acquireInLockTable(rule.getSecurityGroupId()); - if (groupHandle == null) { - s_logger.warn("Could not acquire lock on security group id: " + rule.getSecurityGroupId()); - return false; - } - - _ingressRuleDao.remove(id); - s_logger.debug("revokeSecurityGroupIngress succeeded for ingress rule id: " +id); - - final Set affectedVms = new HashSet(); - affectedVms.addAll(_securityGroupVMMapDao.listVmIdsBySecurityGroup(groupHandle.getId())); - scheduleRulesetUpdateToHosts(affectedVms, true, null); - - return true; - } catch (Exception e) { - s_logger.warn("Exception caught when deleting ingress rules ", e); - throw new CloudRuntimeException("Exception caught when deleting ingress rules", e); - } finally { - if (groupHandle != null) { - _securityGroupDao.releaseFromLockTable(groupHandle.getId()); - } - txn.commit(); - } - - } - - private static boolean isAdmin(short accountType) { - return ((accountType == Account.ACCOUNT_TYPE_ADMIN) || - (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) || - (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || - (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN)); - } - - @Override - @ActionEvent(eventType = EventTypes.EVENT_SECURITY_GROUP_CREATE, eventDescription = "creating security group") - public SecurityGroupVO createSecurityGroup(CreateSecurityGroupCmd cmd) throws PermissionDeniedException, InvalidParameterValueException { - - String accountName = cmd.getAccountName(); - Long domainId = cmd.getDomainId(); - Long accountId = null; - - Account account = UserContext.current().getCaller(); - if (account != null) { - if (isAdmin(account.getType())) { - if ((domainId != null) && (accountName != null)) { - if (!_domainDao.isChildDomain(account.getDomainId(), domainId)) { - throw new PermissionDeniedException("Unable to create security group in domain " + domainId + ", permission denied."); - } - - Account userAccount = _accountDao.findActiveAccount(accountName, domainId); - if (userAccount == null) { - throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId + ", failed to create security group " + cmd.getSecurityGroupName()); - } - - accountId = userAccount.getId(); - } else { - // the admin must be creating a security group for himself/herself - if (account != null) { - accountId = account.getId(); - domainId = account.getDomainId(); - accountName = account.getAccountName(); - } - } - } else { - accountId = account.getId(); - domainId = account.getDomainId(); - accountName = account.getAccountName(); + try { + txn.start(); + // acquire lock on parent group (preserving this logic) + groupHandle = _securityGroupDao.acquireInLockTable(rule.getSecurityGroupId()); + if (groupHandle == null) { + s_logger.warn("Could not acquire lock on security group id: " + rule.getSecurityGroupId()); + return false; } - } - // if no account exists in the context, it's a system level command, look up the account - if (accountId == null) { - if ((accountName != null) && (domainId != null)) { - Account userAccount = _accountDao.findActiveAccount(accountName, domainId); - if (userAccount != null) { - accountId = userAccount.getId(); - } else { - throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId + ", failed to create security group " + cmd.getSecurityGroupName()); - } - } else { - throw new InvalidParameterValueException("Missing account information (account: " + accountName + ", domain: " + domainId + "), failed to create security group " + cmd.getSecurityGroupName()); + _ingressRuleDao.remove(id); + s_logger.debug("revokeSecurityGroupIngress succeeded for ingress rule id: " + id); + + final Set affectedVms = new HashSet(); + affectedVms.addAll(_securityGroupVMMapDao.listVmIdsBySecurityGroup(groupHandle.getId())); + scheduleRulesetUpdateToHosts(affectedVms, true, null); + + return true; + } catch (Exception e) { + s_logger.warn("Exception caught when deleting ingress rules ", e); + throw new CloudRuntimeException("Exception caught when deleting ingress rules", e); + } finally { + if (groupHandle != null) { + _securityGroupDao.releaseFromLockTable(groupHandle.getId()); } + txn.commit(); } - if (_securityGroupDao.isNameInUse(accountId, domainId, cmd.getSecurityGroupName())) { - throw new InvalidParameterValueException("Unable to create security group, a group with name " + cmd.getSecurityGroupName() + " already exisits."); - } - - return createSecurityGroup(cmd.getSecurityGroupName(), cmd.getDescription(), domainId, accountId, accountName); - } - - @DB - @Override - public SecurityGroupVO createSecurityGroup(String name, String description, Long domainId, Long accountId, String accountName) { - final Transaction txn = Transaction.currentTxn(); - AccountVO account = null; - txn.start(); - try { - account = _accountDao.acquireInLockTable(accountId); //to ensure duplicate group names are not created. - if (account == null) { - s_logger.warn("Failed to acquire lock on account"); - return null; - } - SecurityGroupVO group = _securityGroupDao.findByAccountAndName(accountId, name); - if (group == null){ - group = new SecurityGroupVO(name, description, domainId, accountId, accountName); - group = _securityGroupDao.persist(group); - } - - s_logger.debug("Created security group " + group + " for account id=" + accountId); - return group; - } finally { - if (account != null) { - _accountDao.releaseFromLockTable(accountId); - } - txn.commit(); - } - } - - @Override - public boolean configure(String name, Map params) - throws ConfigurationException { - /*register state listener, no matter security group is enabled or not*/ - VirtualMachine.State.getStateMachine().registerListener(this); - - _answerListener = new SecurityGroupListener(this, _agentMgr, _workDao); - _agentMgr.registerForHostEvents(_answerListener, true, true, true); - - _serverId = ((ManagementServer)ComponentLocator.getComponent(ManagementServer.Name)).getId(); + + @Override + @ActionEvent(eventType = EventTypes.EVENT_SECURITY_GROUP_CREATE, eventDescription = "creating security group") + public SecurityGroupVO createSecurityGroup(CreateSecurityGroupCmd cmd) throws PermissionDeniedException, InvalidParameterValueException { + String name = cmd.getSecurityGroupName(); + Account caller = UserContext.current().getCaller(); + Account owner = _accountMgr.finalizeOwner(caller, cmd.getAccountName(), cmd.getDomainId()); + + if (_securityGroupDao.isNameInUse(owner.getId(), owner.getDomainId(), cmd.getSecurityGroupName())) { + throw new InvalidParameterValueException("Unable to create security group, a group with name " + name + " already exisits."); + } + + return createSecurityGroup(cmd.getSecurityGroupName(), cmd.getDescription(), owner.getDomainId(), owner.getAccountId(), owner.getAccountName()); + } + + @DB + @Override + public SecurityGroupVO createSecurityGroup(String name, String description, Long domainId, Long accountId, String accountName) { + final Transaction txn = Transaction.currentTxn(); + AccountVO account = null; + txn.start(); + try { + account = _accountDao.acquireInLockTable(accountId); // to ensure duplicate group names are not created. + if (account == null) { + s_logger.warn("Failed to acquire lock on account"); + return null; + } + SecurityGroupVO group = _securityGroupDao.findByAccountAndName(accountId, name); + if (group == null) { + group = new SecurityGroupVO(name, description, domainId, accountId); + group = _securityGroupDao.persist(group); + } + + s_logger.debug("Created security group " + group + " for account id=" + accountId); + return group; + } finally { + if (account != null) { + _accountDao.releaseFromLockTable(accountId); + } + txn.commit(); + } + + } + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + /* register state listener, no matter security group is enabled or not */ + VirtualMachine.State.getStateMachine().registerListener(this); + + _answerListener = new SecurityGroupListener(this, _agentMgr, _workDao); + _agentMgr.registerForHostEvents(_answerListener, true, true, true); + + _serverId = ((ManagementServer) ComponentLocator.getComponent(ManagementServer.Name)).getId(); _executorPool = Executors.newScheduledThreadPool(10, new NamedThreadFactory("NWGRP")); _cleanupExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("NWGRP-Cleanup")); - - return true; - } + return true; + } - @Override - public String getName() { - return this.getClass().getName(); - } + @Override + public String getName() { + return this.getClass().getName(); + } + @Override + public boolean start() { + _cleanupExecutor.scheduleAtFixedRate(new CleanupThread(), _timeBetweenCleanups, _timeBetweenCleanups, TimeUnit.SECONDS); + return true; + } - @Override - public boolean start() { - _cleanupExecutor.scheduleAtFixedRate(new CleanupThread(), _timeBetweenCleanups, _timeBetweenCleanups, TimeUnit.SECONDS); - return true; - } - - - @Override - public boolean stop() { - return true; - } - - @Override - public SecurityGroupVO createDefaultSecurityGroup(Long accountId) { - SecurityGroupVO groupVO = _securityGroupDao.findByAccountAndName(accountId, SecurityGroupManager.DEFAULT_GROUP_NAME); - if (groupVO == null ) { - Account accVO = _accountDao.findById(accountId); - if (accVO != null) { - return createSecurityGroup(SecurityGroupManager.DEFAULT_GROUP_NAME, SecurityGroupManager.DEFAULT_GROUP_DESCRIPTION, accVO.getDomainId(), accVO.getId(), accVO.getAccountName()); - } - } - return groupVO; - } - - @DB - public void work() { - if (s_logger.isTraceEnabled()) { - s_logger.trace("Checking the database"); - } - final SecurityGroupWorkVO work = _workDao.take(_serverId); - if (work == null) { - return; - } - Long userVmId = work.getInstanceId(); - UserVm vm = null; - Long seqnum = null; - s_logger.info("Working on " + work.toString()); - final Transaction txn = Transaction.currentTxn(); - txn.start(); - try { - vm = _userVMDao.acquireInLockTable(work.getInstanceId()); - if (vm == null) { - s_logger.warn("Unable to acquire lock on vm id=" + userVmId); - return ; - } - Long agentId = null; - VmRulesetLogVO log = _rulesetLogDao.findByVmId(userVmId); - if (log == null) { - s_logger.warn("Cannot find log record for vm id=" + userVmId); - return; - } - seqnum = log.getLogsequence(); - - if (vm != null && vm.getState() == State.Running) { - Map> rules = generateRulesForVM(userVmId); - agentId = vm.getHostId(); - if (agentId != null ) { - _rulesetLogDao.findByVmId(work.getInstanceId()); - SecurityIngressRulesCmd cmd = generateRulesetCmd(vm.getInstanceName(), vm.getPrivateIpAddress(), vm.getPrivateMacAddress(), vm.getId(), generateRulesetSignature(rules), seqnum, rules); - Commands cmds = new Commands(cmd); - try { - _agentMgr.send(agentId, cmds, _answerListener); - } catch (AgentUnavailableException e) { - s_logger.debug("Unable to send updates for vm: " + userVmId + "(agentid=" + agentId + ")"); - _workDao.updateStep(work.getInstanceId(), seqnum, Step.Done); - } - } - } - } finally { - if (vm != null) { - _userVMDao.releaseFromLockTable(userVmId); - _workDao.updateStep(work.getId(), Step.Done); - } - txn.commit(); - } - - - } - - @Override - @DB - public boolean addInstanceToGroups(final Long userVmId, final List groups) { - if (!isVmSecurityGroupEnabled(userVmId)) { - return true; - } - if (groups != null && !groups.isEmpty()) { - - final Transaction txn = Transaction.currentTxn(); - txn.start(); - UserVm userVm = _userVMDao.acquireInLockTable(userVmId); //ensures that duplicate entries are not created. - List sgs = new ArrayList(); - for (Long sgId : groups) { - sgs.add(_securityGroupDao.findById(sgId)); - } - final Set uniqueGroups = new TreeSet(new SecurityGroupVOComparator()); - uniqueGroups.addAll(sgs); - if (userVm == null) { - s_logger.warn("Failed to acquire lock on user vm id=" + userVmId); - } - try { - for (SecurityGroupVO securityGroup:uniqueGroups) { - //don't let the group be deleted from under us. - SecurityGroupVO ngrpLock = _securityGroupDao.lockRow(securityGroup.getId(), false); - if (ngrpLock == null) { - s_logger.warn("Failed to acquire lock on network group id=" + securityGroup.getId() + " name=" + securityGroup.getName()); - txn.rollback(); - return false; - } - if (_securityGroupVMMapDao.findByVmIdGroupId(userVmId, securityGroup.getId()) == null) { - SecurityGroupVMMapVO groupVmMapVO = new SecurityGroupVMMapVO(securityGroup.getId(), userVmId); - _securityGroupVMMapDao.persist(groupVmMapVO); - } - } - txn.commit(); - return true; - } finally { - if (userVm != null) { - _userVMDao.releaseFromLockTable(userVmId); - } - } - + @Override + public boolean stop() { + return true; + } + @Override + public SecurityGroupVO createDefaultSecurityGroup(Long accountId) { + SecurityGroupVO groupVO = _securityGroupDao.findByAccountAndName(accountId, SecurityGroupManager.DEFAULT_GROUP_NAME); + if (groupVO == null) { + Account accVO = _accountDao.findById(accountId); + if (accVO != null) { + return createSecurityGroup(SecurityGroupManager.DEFAULT_GROUP_NAME, SecurityGroupManager.DEFAULT_GROUP_DESCRIPTION, accVO.getDomainId(), accVO.getId(), accVO.getAccountName()); + } } - return false; - - } + return groupVO; + } - @Override - @DB - public void removeInstanceFromGroups(Long userVmId) { - if (!isVmSecurityGroupEnabled(userVmId)) { - return; - } - final Transaction txn = Transaction.currentTxn(); - txn.start(); - UserVm userVm = _userVMDao.acquireInLockTable(userVmId); //ensures that duplicate entries are not created in addInstance - if (userVm == null) { - s_logger.warn("Failed to acquire lock on user vm id=" + userVmId); - } - int n = _securityGroupVMMapDao.deleteVM(userVmId); - s_logger.info("Disassociated " + n + " network groups " + " from uservm " + userVmId); - _userVMDao.releaseFromLockTable(userVmId); - txn.commit(); - } + @DB + public void work() { + if (s_logger.isTraceEnabled()) { + s_logger.trace("Checking the database"); + } + final SecurityGroupWorkVO work = _workDao.take(_serverId); + if (work == null) { + return; + } + Long userVmId = work.getInstanceId(); + UserVm vm = null; + Long seqnum = null; + s_logger.info("Working on " + work.toString()); + final Transaction txn = Transaction.currentTxn(); + txn.start(); + try { + vm = _userVMDao.acquireInLockTable(work.getInstanceId()); + if (vm == null) { + s_logger.warn("Unable to acquire lock on vm id=" + userVmId); + return; + } + Long agentId = null; + VmRulesetLogVO log = _rulesetLogDao.findByVmId(userVmId); + if (log == null) { + s_logger.warn("Cannot find log record for vm id=" + userVmId); + return; + } + seqnum = log.getLogsequence(); - @DB - @Override - @ActionEvent(eventType = EventTypes.EVENT_SECURITY_GROUP_DELETE, eventDescription = "deleting security group") - public boolean deleteSecurityGroup(DeleteSecurityGroupCmd cmd) throws ResourceInUseException{ - Long id = cmd.getId(); - String accountName = cmd.getAccountName(); - Long domainId = cmd.getDomainId(); - Account account = UserContext.current().getCaller(); - - //Verify input parameters - Long accountId = null; - if ((account == null) || isAdmin(account.getType())) { - if ((accountName != null) && (domainId != null)) { - // if it's an admin account, do a quick permission check - if ((account != null) && !_domainDao.isChildDomain(account.getDomainId(), domainId)) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Unable to find rules network group: " + id + ", permission denied."); + if (vm != null && vm.getState() == State.Running) { + Map> rules = generateRulesForVM(userVmId); + agentId = vm.getHostId(); + if (agentId != null) { + _rulesetLogDao.findByVmId(work.getInstanceId()); + SecurityIngressRulesCmd cmd = generateRulesetCmd(vm.getInstanceName(), vm.getPrivateIpAddress(), vm.getPrivateMacAddress(), vm.getId(), generateRulesetSignature(rules), seqnum, + rules); + Commands cmds = new Commands(cmd); + try { + _agentMgr.send(agentId, cmds, _answerListener); + } catch (AgentUnavailableException e) { + s_logger.debug("Unable to send updates for vm: " + userVmId + "(agentid=" + agentId + ")"); + _workDao.updateStep(work.getInstanceId(), seqnum, Step.Done); } - throw new PermissionDeniedException("Unable to network group: " + id + ", permission denied."); - } - - Account groupOwner = _accountDao.findActiveAccount(accountName, domainId); - if (groupOwner == null) { - throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId); - } - accountId = groupOwner.getId(); - } else { - if (account != null) { - accountId = account.getId(); - domainId = account.getDomainId(); } } - } else { - if (account != null) { - accountId = account.getId(); - domainId = account.getDomainId(); + } finally { + if (vm != null) { + _userVMDao.releaseFromLockTable(userVmId); + _workDao.updateStep(work.getId(), Step.Done); } + txn.commit(); } - if (accountId == null) { - throw new InvalidParameterValueException("Unable to find account for network group: " + id + "; failed to delete group."); + } + + @Override + @DB + public boolean addInstanceToGroups(final Long userVmId, final List groups) { + if (!isVmSecurityGroupEnabled(userVmId)) { + return true; + } + if (groups != null && !groups.isEmpty()) { + + final Transaction txn = Transaction.currentTxn(); + txn.start(); + UserVm userVm = _userVMDao.acquireInLockTable(userVmId); // ensures that duplicate entries are not created. + List sgs = new ArrayList(); + for (Long sgId : groups) { + sgs.add(_securityGroupDao.findById(sgId)); + } + final Set uniqueGroups = new TreeSet(new SecurityGroupVOComparator()); + uniqueGroups.addAll(sgs); + if (userVm == null) { + s_logger.warn("Failed to acquire lock on user vm id=" + userVmId); + } + try { + for (SecurityGroupVO securityGroup : uniqueGroups) { + // don't let the group be deleted from under us. + SecurityGroupVO ngrpLock = _securityGroupDao.lockRow(securityGroup.getId(), false); + if (ngrpLock == null) { + s_logger.warn("Failed to acquire lock on network group id=" + securityGroup.getId() + " name=" + securityGroup.getName()); + txn.rollback(); + return false; + } + if (_securityGroupVMMapDao.findByVmIdGroupId(userVmId, securityGroup.getId()) == null) { + SecurityGroupVMMapVO groupVmMapVO = new SecurityGroupVMMapVO(securityGroup.getId(), userVmId); + _securityGroupVMMapDao.persist(groupVmMapVO); + } + } + txn.commit(); + return true; + } finally { + if (userVm != null) { + _userVMDao.releaseFromLockTable(userVmId); + } + } + + } + return false; + + } + + @Override + @DB + public void removeInstanceFromGroups(Long userVmId) { + if (!isVmSecurityGroupEnabled(userVmId)) { + return; + } + final Transaction txn = Transaction.currentTxn(); + txn.start(); + UserVm userVm = _userVMDao.acquireInLockTable(userVmId); // ensures that duplicate entries are not created in + // addInstance + if (userVm == null) { + s_logger.warn("Failed to acquire lock on user vm id=" + userVmId); + } + int n = _securityGroupVMMapDao.deleteVM(userVmId); + s_logger.info("Disassociated " + n + " network groups " + " from uservm " + userVmId); + _userVMDao.releaseFromLockTable(userVmId); + txn.commit(); + } + + @DB + @Override + @ActionEvent(eventType = EventTypes.EVENT_SECURITY_GROUP_DELETE, eventDescription = "deleting security group") + public boolean deleteSecurityGroup(DeleteSecurityGroupCmd cmd) throws ResourceInUseException { + Long groupId = cmd.getId(); + Account caller = UserContext.current().getCaller(); + + SecurityGroupVO group = _securityGroupDao.findById(groupId); + if (group == null) { + throw new InvalidParameterValueException("Unable to find network group: " + groupId + "; failed to delete group."); } - SecurityGroupVO sg = _securityGroupDao.findById(id); - if (sg == null) { - throw new InvalidParameterValueException("Unable to find network group: " + id + "; failed to delete group."); + // check permissions + _accountMgr.checkAccess(caller, group); + + final Transaction txn = Transaction.currentTxn(); + txn.start(); + + group = _securityGroupDao.lockRow(groupId, true); + if (group == null) { + s_logger.info("Not deleting group -- cannot find id " + groupId); + return false; + } + + if (group.getName().equalsIgnoreCase(SecurityGroupManager.DEFAULT_GROUP_NAME)) { + txn.rollback(); + throw new InvalidParameterValueException("The network group default is reserved"); + } + + List allowingRules = _ingressRuleDao.listByAllowedSecurityGroupId(groupId); + if (allowingRules.size() != 0) { + txn.rollback(); + throw new ResourceInUseException("Cannot delete group when there are ingress rules that allow this group"); + } + + List rulesInGroup = _ingressRuleDao.listBySecurityGroupId(groupId); + if (rulesInGroup.size() != 0) { + txn.rollback(); + throw new ResourceInUseException("Cannot delete group when there are ingress rules in this group"); } - - Long groupId = sg.getId(); - - final Transaction txn = Transaction.currentTxn(); - txn.start(); - - final SecurityGroupVO group = _securityGroupDao.lockRow(groupId, true); - if (group == null) { - s_logger.info("Not deleting group -- cannot find id " + groupId); - return false; - } - - if (group.getName().equalsIgnoreCase(SecurityGroupManager.DEFAULT_GROUP_NAME)) { - txn.rollback(); - throw new PermissionDeniedException("The network group default is reserved"); - } - - List allowingRules = _ingressRuleDao.listByAllowedSecurityGroupId(groupId); - if (allowingRules.size() != 0) { - txn.rollback(); - throw new ResourceInUseException("Cannot delete group when there are ingress rules that allow this group"); - } - - List rulesInGroup = _ingressRuleDao.listBySecurityGroupId(groupId); - if (rulesInGroup.size() != 0) { - txn.rollback(); - throw new ResourceInUseException("Cannot delete group when there are ingress rules in this group"); - } _securityGroupDao.expunge(groupId); txn.commit(); - - s_logger.debug("Deleted security group " + group + " for account id=" + accountId); - + + s_logger.debug("Deleted security group id=" + groupId); + return true; - } + } @Override public List searchForSecurityGroupRules(ListSecurityGroupsCmd cmd) throws PermissionDeniedException, InvalidParameterValueException { - Account account = UserContext.current().getCaller(); + Account caller = UserContext.current().getCaller(); Long domainId = cmd.getDomainId(); String accountName = cmd.getAccountName(); - Long accountId = null; Long instanceId = cmd.getVirtualMachineId(); String securityGroup = cmd.getSecurityGroupName(); - Boolean recursive = Boolean.FALSE; Long id = cmd.getId(); + Long accountId = null; - // permissions check - if ((account == null) || isAdmin(account.getType())) { + if (instanceId != null) { + UserVmVO userVM = _userVMDao.findById(instanceId); + if (userVM == null) { + throw new InvalidParameterValueException("Unable to list network groups for virtual machine instance " + instanceId + "; instance not found."); + } + _accountMgr.checkAccess(caller, userVM); + return listSecurityGroupRulesByVM(instanceId.longValue()); + } + + if (_accountMgr.isAdmin(caller.getType())) { if (domainId != null) { - if ((account != null) && !_domainDao.isChildDomain(account.getDomainId(), domainId)) { - throw new PermissionDeniedException("Unable to list network groups for account " + accountName + " in domain " + domainId + "; permission denied."); + Domain domain = _accountMgr.getDomain(domainId); + if (domain == null) { + throw new InvalidParameterValueException("Unable to find domain by id " + domainId); } + _accountMgr.checkAccess(caller, domain); if (accountName != null) { - Account acct = _accountDao.findActiveAccount(accountName, domainId); - if (acct != null) { - accountId = acct.getId(); - } else { + Account account = _accountMgr.getActiveAccount(accountName, domainId); + if (account == null) { throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId); } - } - } else if (instanceId != null) { - UserVmVO userVM = _userVMDao.findById(instanceId); - if (userVM == null) { - throw new InvalidParameterValueException("Unable to list network groups for virtual machine instance " + instanceId + "; instance not found."); - } - if ((account != null) && !_domainDao.isChildDomain(account.getDomainId(), userVM.getDomainId())) { - throw new PermissionDeniedException("Unable to list network groups for virtual machine instance " + instanceId + "; permission denied."); - } - } else if (account != null) { - // either an admin is searching for their own group, or admin is listing all groups and the search needs to be restricted to domain admin's domain - if (securityGroup != null) { + _accountMgr.checkAccess(caller, account); accountId = account.getId(); - } else if (account.getType() != Account.ACCOUNT_TYPE_ADMIN) { - domainId = account.getDomainId(); - recursive = Boolean.TRUE; } } } else { - if (instanceId != null) { - UserVmVO userVM = _userVMDao.findById(instanceId); - if (userVM == null) { - throw new InvalidParameterValueException("Unable to list network groups for virtual machine instance " + instanceId + "; instance not found."); - } - - if (account != null) { - // check that the user is the owner of the VM (admin case was already verified - if (account.getId() != userVM.getAccountId()) { - throw new PermissionDeniedException("Unable to list network groups for virtual machine instance " + instanceId + "; permission denied."); - } - } - } else { - accountId = ((account != null) ? account.getId() : null); - } + // regular user can see only his own security groups + accountId = caller.getId(); } List securityRulesList = new ArrayList(); @@ -1160,153 +997,142 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); // only do a recursive domain search if the search is not limited by account or instance - if ((accountId == null) && (instanceId == null) && (domainId != null) && Boolean.TRUE.equals(recursive)) { + if ((accountId == null) && (instanceId == null) && (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)) { SearchBuilder domainSearch = _domainDao.createSearchBuilder(); domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); } SearchCriteria sc = sb.create(); - + if (id != null) { sc.setParameters("id", id); } - + + if (securityGroup != null) { + sc.setParameters("name", securityGroup); + } + if (accountId != null) { sc.setParameters("accountId", accountId); - if (securityGroup != null) { - sc.setParameters("name", securityGroup); - } else if (keyword != null) { - SearchCriteria ssc = _securityGroupRulesDao.createSearchCriteria(); - ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - sc.addAnd("name", SearchCriteria.Op.SC, ssc); - } - } else if (domainId != null) { - if (Boolean.TRUE.equals(recursive)) { - DomainVO domain = _domainDao.findById(domainId); - sc.setJoinParameters("domainSearch", "path", domain.getPath() + "%"); - } else { - sc.setParameters("domainId", domainId); - } + } + + // only do a recursive domain search if the search is not limited by account or instance + if ((accountId == null) && (instanceId == null) && (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)) { + DomainVO domain = _domainDao.findById(caller.getDomainId()); + sc.setJoinParameters("domainSearch", "path", domain.getPath() + "%"); + } + + if (keyword != null) { + SearchCriteria ssc = _securityGroupRulesDao.createSearchCriteria(); + ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + sc.addAnd("name", SearchCriteria.Op.SC, ssc); } List securityGroups = _securityGroupDao.search(sc, searchFilter); for (SecurityGroupVO group : securityGroups) { - securityRulesList.addAll(_securityGroupRulesDao.listSecurityRulesByGroupId(group.getId())); + securityRulesList.addAll(_securityGroupRulesDao.listSecurityRulesByGroupId(group.getId())); } - - if (instanceId != null) { - return listSecurityGroupRulesByVM(instanceId.longValue()); - } - + return securityRulesList; } - private List listSecurityGroupRulesByVM(long vmId) { - List results = new ArrayList(); - List networkGroupMappings = _securityGroupVMMapDao.listByInstanceId(vmId); - if (networkGroupMappings != null) { - for (SecurityGroupVMMapVO networkGroupMapping : networkGroupMappings) { - SecurityGroupVO group = _securityGroupDao.findById(networkGroupMapping.getSecurityGroupId()); - List rules = _securityGroupRulesDao.listSecurityGroupRules(group.getAccountId(), networkGroupMapping.getGroupName()); - if (rules != null) { - results.addAll(rules); - } - } - } - return results; - } + private List listSecurityGroupRulesByVM(long vmId) { + List results = new ArrayList(); + List networkGroupMappings = _securityGroupVMMapDao.listByInstanceId(vmId); + if (networkGroupMappings != null) { + for (SecurityGroupVMMapVO networkGroupMapping : networkGroupMappings) { + SecurityGroupVO group = _securityGroupDao.findById(networkGroupMapping.getSecurityGroupId()); + List rules = _securityGroupRulesDao.listSecurityGroupRules(group.getAccountId(), networkGroupMapping.getGroupName()); + if (rules != null) { + results.addAll(rules); + } + } + } + return results; + } - @Override - public void fullSync(long agentId, HashMap> newGroupStates) { - Set affectedVms = new HashSet(); - for (String vmName: newGroupStates.keySet()) { - Long vmId = newGroupStates.get(vmName).first(); - Long seqno = newGroupStates.get(vmName).second(); + @Override + public void fullSync(long agentId, HashMap> newGroupStates) { + Set affectedVms = new HashSet(); + for (String vmName : newGroupStates.keySet()) { + Long vmId = newGroupStates.get(vmName).first(); + Long seqno = newGroupStates.get(vmName).second(); - VmRulesetLogVO log = _rulesetLogDao.findByVmId(vmId); - if (log != null && log.getLogsequence() != seqno) { - affectedVms.add(vmId); - } - } - if (affectedVms.size() > 0){ - s_logger.info("Network Group full sync for agent " + agentId + " found " + affectedVms.size() + " vms out of sync"); - scheduleRulesetUpdateToHosts(affectedVms, false, null); - } - - } - - public void cleanupFinishedWork() { - Date before = new Date(System.currentTimeMillis() - 24*3600*1000l); - int numDeleted = _workDao.deleteFinishedWork(before); - if (numDeleted > 0) { - s_logger.info("Network Group Work cleanup deleted " + numDeleted + " finished work items older than " + before.toString()); - } - - } - + VmRulesetLogVO log = _rulesetLogDao.findByVmId(vmId); + if (log != null && log.getLogsequence() != seqno) { + affectedVms.add(vmId); + } + } + if (affectedVms.size() > 0) { + s_logger.info("Network Group full sync for agent " + agentId + " found " + affectedVms.size() + " vms out of sync"); + scheduleRulesetUpdateToHosts(affectedVms, false, null); + } + } - private void cleanupUnfinishedWork() { - Date before = new Date(System.currentTimeMillis() - 30*1000l); - List unfinished = _workDao.findUnfinishedWork(before); - if (unfinished.size() > 0) { - s_logger.info("Network Group Work cleanup found " + unfinished.size() + " unfinished work items older than " + before.toString()); - Set affectedVms = new HashSet(); - for (SecurityGroupWorkVO work: unfinished) { - affectedVms.add(work.getInstanceId()); - } - scheduleRulesetUpdateToHosts(affectedVms, false, null); - } else { - s_logger.debug("Network Group Work cleanup found no unfinished work items older than " + before.toString()); - } - } + public void cleanupFinishedWork() { + Date before = new Date(System.currentTimeMillis() - 24 * 3600 * 1000l); + int numDeleted = _workDao.deleteFinishedWork(before); + if (numDeleted > 0) { + s_logger.info("Network Group Work cleanup deleted " + numDeleted + " finished work items older than " + before.toString()); + } - @Override - public String getSecurityGroupsNamesForVm(long vmId) - { - try - { - ListnetworkGroupsToVmMap = _securityGroupVMMapDao.listByInstanceId(vmId); - int size = 0; - int j=0; + } + + private void cleanupUnfinishedWork() { + Date before = new Date(System.currentTimeMillis() - 30 * 1000l); + List unfinished = _workDao.findUnfinishedWork(before); + if (unfinished.size() > 0) { + s_logger.info("Network Group Work cleanup found " + unfinished.size() + " unfinished work items older than " + before.toString()); + Set affectedVms = new HashSet(); + for (SecurityGroupWorkVO work : unfinished) { + affectedVms.add(work.getInstanceId()); + } + scheduleRulesetUpdateToHosts(affectedVms, false, null); + } else { + s_logger.debug("Network Group Work cleanup found no unfinished work items older than " + before.toString()); + } + } + + @Override + public String getSecurityGroupsNamesForVm(long vmId) { + try { + List networkGroupsToVmMap = _securityGroupVMMapDao.listByInstanceId(vmId); + int size = 0; + int j = 0; StringBuilder networkGroupNames = new StringBuilder(); - if(networkGroupsToVmMap != null) - { - size = networkGroupsToVmMap.size(); - - for(SecurityGroupVMMapVO nG: networkGroupsToVmMap) - { - //get the group id and look up for the group name - SecurityGroupVO currentNetworkGroup = _securityGroupDao.findById(nG.getSecurityGroupId()); - networkGroupNames.append(currentNetworkGroup.getName()); - - if(j<(size-1)) - { - networkGroupNames.append(","); - j++; - } - } - } - - return networkGroupNames.toString(); - } - catch (Exception e) - { - s_logger.warn("Error trying to get network groups for a vm: "+e); - return null; - } + if (networkGroupsToVmMap != null) { + size = networkGroupsToVmMap.size(); - } - - @Override + for (SecurityGroupVMMapVO nG : networkGroupsToVmMap) { + // get the group id and look up for the group name + SecurityGroupVO currentNetworkGroup = _securityGroupDao.findById(nG.getSecurityGroupId()); + networkGroupNames.append(currentNetworkGroup.getName()); + + if (j < (size - 1)) { + networkGroupNames.append(","); + j++; + } + } + } + + return networkGroupNames.toString(); + } catch (Exception e) { + s_logger.warn("Error trying to get network groups for a vm: " + e); + return null; + } + + } + + @Override public List getSecurityGroupsForVm(long vmId) { - ListsecurityGroupsToVmMap = _securityGroupVMMapDao.listByInstanceId(vmId); + List securityGroupsToVmMap = _securityGroupVMMapDao.listByInstanceId(vmId); List secGrps = new ArrayList(); - if(securityGroupsToVmMap != null && securityGroupsToVmMap.size() > 0) { - for(SecurityGroupVMMapVO sG : securityGroupsToVmMap) { + if (securityGroupsToVmMap != null && securityGroupsToVmMap.size() > 0) { + for (SecurityGroupVMMapVO sG : securityGroupsToVmMap) { SecurityGroupVO currSg = _securityGroupDao.findById(sG.getSecurityGroupId()); secGrps.add(currSg); } @@ -1326,11 +1152,11 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG } if (VirtualMachine.State.isVmStarted(oldState, event, newState)) { - handleVmStarted((VMInstanceVO)vm); + handleVmStarted((VMInstanceVO) vm); } else if (VirtualMachine.State.isVmStopped(oldState, event, newState)) { - handleVmStopped((VMInstanceVO)vm); + handleVmStopped((VMInstanceVO) vm); } else if (VirtualMachine.State.isVmMigrated(oldState, event, newState)) { - handleVmMigrated((VMInstanceVO)vm); + handleVmMigrated((VMInstanceVO) vm); } return true; diff --git a/setup/db/create-schema.sql b/setup/db/create-schema.sql index 0c635b3426e..43bead576ac 100755 --- a/setup/db/create-schema.sql +++ b/setup/db/create-schema.sql @@ -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`) diff --git a/setup/db/db/schema-224to225.sql b/setup/db/db/schema-224to225.sql index 61b7bb03ba4..2c8bd5928ae 100644 --- a/setup/db/db/schema-224to225.sql +++ b/setup/db/db/schema-224to225.sql @@ -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); \ No newline at end of file +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`; + diff --git a/utils/src/com/cloud/utils/net/NetUtils.java b/utils/src/com/cloud/utils/net/NetUtils.java index 6ae00a538cf..2deba83f2a1 100755 --- a/utils/src/com/cloud/utils/net/NetUtils.java +++ b/utils/src/com/cloud/utils/net/NetUtils.java @@ -48,141 +48,141 @@ public class NetUtils { public final static int VPN_NATT_PORT = 4500; public final static int VPN_L2TP_PORT = 1701; - public final static String UDP_PROTO = "udp"; public final static String TCP_PROTO = "tcp"; public final static String ANY_PROTO = "any"; public final static String ICMP_PROTO = "icmp"; - + public final static String ALL_PROTO = "all"; + private final static Random _rand = new Random(System.currentTimeMillis()); public static long createSequenceBasedMacAddress(long macAddress) { - return macAddress | 0x060000000000l | (((long)_rand.nextInt(32768) << 25) & 0x00fffe000000l); + return macAddress | 0x060000000000l | (((long) _rand.nextInt(32768) << 25) & 0x00fffe000000l); } - - public static String getHostName() { + + public static String getHostName() { try { InetAddress localAddr = InetAddress.getLocalHost(); - if(localAddr != null) { - return localAddr.getHostName(); + if (localAddr != null) { + return localAddr.getHostName(); } - } catch(UnknownHostException e) { - s_logger.warn("UnknownHostException when trying to get host name. ", e); + } catch (UnknownHostException e) { + s_logger.warn("UnknownHostException when trying to get host name. ", e); } return "localhost"; - } - + } + public static InetAddress getLocalInetAddress() { try { return InetAddress.getLocalHost(); - } catch(UnknownHostException e) { - s_logger.warn("UnknownHostException in getLocalInetAddress().", e); + } catch (UnknownHostException e) { + s_logger.warn("UnknownHostException in getLocalInetAddress().", e); return null; } } - + public static String resolveToIp(String host) { - try { - InetAddress addr = InetAddress.getByName(host); - return ipFromInetAddress(addr); - } catch (UnknownHostException e) { - s_logger.warn("Unable to resolve " + host + " to IP due to UnknownHostException"); - return null; - } + try { + InetAddress addr = InetAddress.getByName(host); + return ipFromInetAddress(addr); + } catch (UnknownHostException e) { + s_logger.warn("Unable to resolve " + host + " to IP due to UnknownHostException"); + return null; + } } - + public static InetAddress[] getAllLocalInetAddresses() { - List addrList = new ArrayList(); - try { - for(NetworkInterface ifc : IteratorUtil.enumerationAsIterable(NetworkInterface.getNetworkInterfaces())) { - if(ifc.isUp() && !ifc.isVirtual()) { - for(InetAddress addr : IteratorUtil.enumerationAsIterable(ifc.getInetAddresses())) { - addrList.add(addr); - } - } - } - } catch (SocketException e) { - s_logger.warn("SocketException in getAllLocalInetAddresses().", e); - } - - InetAddress[] addrs = new InetAddress[addrList.size()]; - if(addrList.size() > 0) { + List addrList = new ArrayList(); + try { + for (NetworkInterface ifc : IteratorUtil.enumerationAsIterable(NetworkInterface.getNetworkInterfaces())) { + if (ifc.isUp() && !ifc.isVirtual()) { + for (InetAddress addr : IteratorUtil.enumerationAsIterable(ifc.getInetAddresses())) { + addrList.add(addr); + } + } + } + } catch (SocketException e) { + s_logger.warn("SocketException in getAllLocalInetAddresses().", e); + } + + InetAddress[] addrs = new InetAddress[addrList.size()]; + if (addrList.size() > 0) { System.arraycopy(addrList.toArray(), 0, addrs, 0, addrList.size()); } - return addrs; + return addrs; } - - public static String[] getLocalCidrs() { - List cidrList = new ArrayList(); - try { - for(NetworkInterface ifc : IteratorUtil.enumerationAsIterable(NetworkInterface.getNetworkInterfaces())) { - for (InterfaceAddress address : ifc.getInterfaceAddresses()) { - InetAddress addr = address.getAddress(); - int prefixLength = address.getNetworkPrefixLength(); - if(prefixLength < 32 && prefixLength > 0) { - String ip = ipFromInetAddress(addr); - cidrList.add(ipAndNetMaskToCidr(ip, getCidrNetmask(prefixLength))); - } - } - } - } catch(SocketException e) { - s_logger.warn("UnknownHostException in getLocalCidrs().", e); - } - - return cidrList.toArray(new String[0]); + + public static String[] getLocalCidrs() { + List cidrList = new ArrayList(); + try { + for (NetworkInterface ifc : IteratorUtil.enumerationAsIterable(NetworkInterface.getNetworkInterfaces())) { + for (InterfaceAddress address : ifc.getInterfaceAddresses()) { + InetAddress addr = address.getAddress(); + int prefixLength = address.getNetworkPrefixLength(); + if (prefixLength < 32 && prefixLength > 0) { + String ip = ipFromInetAddress(addr); + cidrList.add(ipAndNetMaskToCidr(ip, getCidrNetmask(prefixLength))); + } + } + } + } catch (SocketException e) { + s_logger.warn("UnknownHostException in getLocalCidrs().", e); + } + + return cidrList.toArray(new String[0]); } - + public static InetAddress getFirstNonLoopbackLocalInetAddress() { - InetAddress[] addrs = getAllLocalInetAddresses(); - if(addrs != null) { - for(InetAddress addr : addrs) { - if(s_logger.isInfoEnabled()) { + InetAddress[] addrs = getAllLocalInetAddresses(); + if (addrs != null) { + for (InetAddress addr : addrs) { + if (s_logger.isInfoEnabled()) { s_logger.info("Check local InetAddress : " + addr.toString() + ", total count :" + addrs.length); } - - if(!addr.isLoopbackAddress()) { + + if (!addr.isLoopbackAddress()) { return addr; } - } - } - - s_logger.warn("Unable to determine a non-loopback address, local inet address count :" + addrs.length); - return null; + } + } + + s_logger.warn("Unable to determine a non-loopback address, local inet address count :" + addrs.length); + return null; } - + public static InetAddress[] getInterfaceInetAddresses(String ifName) { - List addrList = new ArrayList(); - try { - for(NetworkInterface ifc : IteratorUtil.enumerationAsIterable(NetworkInterface.getNetworkInterfaces())) { - if(ifc.isUp() && !ifc.isVirtual() && ifc.getName().equals(ifName)) { - for(InetAddress addr : IteratorUtil.enumerationAsIterable(ifc.getInetAddresses())) { - addrList.add(addr); - } - } - } - } catch (SocketException e) { - s_logger.warn("SocketException in getAllLocalInetAddresses().", e); - } - - InetAddress[] addrs = new InetAddress[addrList.size()]; - if(addrList.size() > 0) { + List addrList = new ArrayList(); + try { + for (NetworkInterface ifc : IteratorUtil.enumerationAsIterable(NetworkInterface.getNetworkInterfaces())) { + if (ifc.isUp() && !ifc.isVirtual() && ifc.getName().equals(ifName)) { + for (InetAddress addr : IteratorUtil.enumerationAsIterable(ifc.getInetAddresses())) { + addrList.add(addr); + } + } + } + } catch (SocketException e) { + s_logger.warn("SocketException in getAllLocalInetAddresses().", e); + } + + InetAddress[] addrs = new InetAddress[addrList.size()]; + if (addrList.size() > 0) { System.arraycopy(addrList.toArray(), 0, addrs, 0, addrList.size()); } - return addrs; + return addrs; } - + public static String getLocalIPString() { InetAddress addr = getLocalInetAddress(); - if(addr != null) { - return ipFromInetAddress(addr); + if (addr != null) { + return ipFromInetAddress(addr); } return new String("127.0.0.1"); } - + public static String ipFromInetAddress(InetAddress addr) { - assert(addr != null); - + assert (addr != null); + byte[] ipBytes = addr.getAddress(); StringBuffer sb = new StringBuffer(); sb.append(ipBytes[0] & 0xff).append("."); @@ -194,92 +194,92 @@ public class NetUtils { } public static boolean isLocalAddress(InetAddress addr) { - InetAddress[] addrs = getAllLocalInetAddresses(); - - if(addrs != null) { - for(InetAddress self : addrs) { - if(self.equals(addr)) { + InetAddress[] addrs = getAllLocalInetAddresses(); + + if (addrs != null) { + for (InetAddress self : addrs) { + if (self.equals(addr)) { return true; } - } - } - return false; - } - - public static boolean isLocalAddress(String strAddress) { - - InetAddress addr; - try { - addr = InetAddress.getByName(strAddress); - return isLocalAddress(addr); - } catch (UnknownHostException e) { - } - return false; - } - - public static String getMacAddress(InetAddress address) { - StringBuffer sb = new StringBuffer(); - Formatter formatter = new Formatter(sb); - try { - NetworkInterface ni = NetworkInterface.getByInetAddress(address); - byte[] mac = ni.getHardwareAddress(); - - for (int i = 0; i < mac.length; i++) { - formatter.format("%02X%s", mac[i], (i < mac.length - 1) ? ":" : ""); - } - } catch (SocketException e) { - s_logger.error("SocketException when trying to retrieve MAC address", e); - } - return sb.toString(); - } - - public static long getMacAddressAsLong(InetAddress address) { - long macAddressAsLong = 0; - try { - NetworkInterface ni = NetworkInterface.getByInetAddress(address); - byte[] mac = ni.getHardwareAddress(); - - for (int i = 0; i < mac.length; i++) { - macAddressAsLong |= ((long)(mac[i] & 0xff) << (mac.length - i - 1)*8); } - - } catch (SocketException e) { - s_logger.error("SocketException when trying to retrieve MAC address", e); - } - - return macAddressAsLong; + } + return false; } - + + public static boolean isLocalAddress(String strAddress) { + + InetAddress addr; + try { + addr = InetAddress.getByName(strAddress); + return isLocalAddress(addr); + } catch (UnknownHostException e) { + } + return false; + } + + public static String getMacAddress(InetAddress address) { + StringBuffer sb = new StringBuffer(); + Formatter formatter = new Formatter(sb); + try { + NetworkInterface ni = NetworkInterface.getByInetAddress(address); + byte[] mac = ni.getHardwareAddress(); + + for (int i = 0; i < mac.length; i++) { + formatter.format("%02X%s", mac[i], (i < mac.length - 1) ? ":" : ""); + } + } catch (SocketException e) { + s_logger.error("SocketException when trying to retrieve MAC address", e); + } + return sb.toString(); + } + + public static long getMacAddressAsLong(InetAddress address) { + long macAddressAsLong = 0; + try { + NetworkInterface ni = NetworkInterface.getByInetAddress(address); + byte[] mac = ni.getHardwareAddress(); + + for (int i = 0; i < mac.length; i++) { + macAddressAsLong |= ((long) (mac[i] & 0xff) << (mac.length - i - 1) * 8); + } + + } catch (SocketException e) { + s_logger.error("SocketException when trying to retrieve MAC address", e); + } + + return macAddressAsLong; + } + public static boolean ipRangesOverlap(String startIp1, String endIp1, String startIp2, String endIp2) { - long startIp1Long = ip2Long(startIp1); - long endIp1Long = startIp1Long; - if (endIp1 != null) { - endIp1Long = ip2Long(endIp1); - } - long startIp2Long = ip2Long(startIp2); - long endIp2Long = startIp2Long; - if (endIp2 != null) { - endIp2Long = ip2Long(endIp2); - } - - if (startIp1Long == startIp2Long || startIp1Long == endIp2Long || endIp1Long == startIp2Long || endIp1Long == endIp2Long) { - return true; - } else if (startIp1Long > startIp2Long && startIp1Long < endIp2Long) { - return true; - } else if (endIp1Long > startIp2Long && endIp1Long < endIp2Long) { - return true; - } else if (startIp2Long > startIp1Long && startIp2Long < endIp1Long) { - return true; - } else if (endIp2Long > startIp1Long && endIp2Long < endIp1Long) { - return true; - } else { - return false; - } + long startIp1Long = ip2Long(startIp1); + long endIp1Long = startIp1Long; + if (endIp1 != null) { + endIp1Long = ip2Long(endIp1); + } + long startIp2Long = ip2Long(startIp2); + long endIp2Long = startIp2Long; + if (endIp2 != null) { + endIp2Long = ip2Long(endIp2); + } + + if (startIp1Long == startIp2Long || startIp1Long == endIp2Long || endIp1Long == startIp2Long || endIp1Long == endIp2Long) { + return true; + } else if (startIp1Long > startIp2Long && startIp1Long < endIp2Long) { + return true; + } else if (endIp1Long > startIp2Long && endIp1Long < endIp2Long) { + return true; + } else if (startIp2Long > startIp1Long && startIp2Long < endIp1Long) { + return true; + } else if (endIp2Long > startIp1Long && endIp2Long < endIp1Long) { + return true; + } else { + return false; + } } - + public static long ip2Long(String ip) { String[] tokens = ip.split("[.]"); - assert(tokens.length == 4); + assert (tokens.length == 4); long result = 0; for (int i = 0; i < tokens.length; i++) { try { @@ -288,23 +288,23 @@ public class NetUtils { throw new RuntimeException("Incorrect number", e); } } - + return result; } - + public static String long2Ip(long ip) { StringBuilder result = new StringBuilder(15); result.append((ip >> 24 & 0xff)).append("."); result.append((ip >> 16 & 0xff)).append("."); result.append((ip >> 8 & 0xff)).append("."); result.append(ip & 0xff); - + return result.toString(); } - + public static long mac2Long(String macAddress) { String[] tokens = macAddress.split(":"); - assert(tokens.length == 6); + assert (tokens.length == 6); long result = 0; for (int i = 0; i < tokens.length; i++) { result = result << 8; @@ -312,7 +312,7 @@ public class NetUtils { } return result; } - + public static String[] getNicParams(String nicName) { try { NetworkInterface nic = NetworkInterface.getByName(nicName); @@ -321,7 +321,7 @@ public class NetUtils { return null; } } - + public static String[] getNetworkParams(NetworkInterface nic) { List addrs = nic.getInterfaceAddresses(); if (addrs == null || addrs.size() == 0) { @@ -330,10 +330,7 @@ public class NetUtils { InterfaceAddress addr = null; for (InterfaceAddress iaddr : addrs) { InetAddress inet = iaddr.getAddress(); - if (!inet.isLinkLocalAddress() && - !inet.isLoopbackAddress() && - !inet.isMulticastAddress() && - inet.getAddress().length == 4) { + if (!inet.isLinkLocalAddress() && !inet.isLoopbackAddress() && !inet.isMulticastAddress() && inet.getAddress().length == 4) { addr = iaddr; break; } @@ -348,20 +345,20 @@ public class NetUtils { result[1] = byte2Mac(mac); } catch (Exception e) { } - + result[2] = prefix2Netmask(addr.getNetworkPrefixLength()); return result; } - + public static String prefix2Netmask(short prefix) { long addr = 0; for (int i = 0; i < prefix; i++) { addr = addr | (1 << (31 - i)); } - + return long2Ip(addr); } - + public static String byte2Mac(byte[] m) { StringBuilder result = new StringBuilder(17); Formatter formatter = new Formatter(result); @@ -372,95 +369,90 @@ public class NetUtils { public static String long2Mac(long macAddress) { StringBuilder result = new StringBuilder(17); Formatter formatter = new Formatter(result); - formatter.format("%02x:%02x:%02x:%02x:%02x:%02x", - (macAddress >> 40) & 0xff, - (macAddress >> 32) & 0xff, - (macAddress >> 24) & 0xff, - (macAddress >> 16) & 0xff, - (macAddress >> 8) & 0xff, - (macAddress & 0xff)); - + formatter.format("%02x:%02x:%02x:%02x:%02x:%02x", (macAddress >> 40) & 0xff, (macAddress >> 32) & 0xff, (macAddress >> 24) & 0xff, (macAddress >> 16) & 0xff, (macAddress >> 8) & 0xff, + (macAddress & 0xff)); + return result.toString(); } - + public static boolean isValidPrivateIp(String ipAddress, String guestIPAddress) { - - InetAddress privIp = parseIpAddress(ipAddress); - if (privIp == null) { + + InetAddress privIp = parseIpAddress(ipAddress); + if (privIp == null) { return false; } - if (!privIp.isSiteLocalAddress()) { - return false; - } - - String firstGuestOctet = "10"; - if (guestIPAddress != null && !guestIPAddress.isEmpty()) { - String[] guestIPList = guestIPAddress.split("\\."); - firstGuestOctet = guestIPList[0]; - } - - String[] ipList = ipAddress.split("\\."); - if (!ipList[0].equals(firstGuestOctet)) { + if (!privIp.isSiteLocalAddress()) { return false; } - - return true; + + String firstGuestOctet = "10"; + if (guestIPAddress != null && !guestIPAddress.isEmpty()) { + String[] guestIPList = guestIPAddress.split("\\."); + firstGuestOctet = guestIPList[0]; + } + + String[] ipList = ipAddress.split("\\."); + if (!ipList[0].equals(firstGuestOctet)) { + return false; + } + + return true; } - + public static boolean isSiteLocalAddress(String ipAddress) { - if (ipAddress == null) { - return false; - } else { - InetAddress ip = parseIpAddress(ipAddress); - return ip.isSiteLocalAddress(); - } + if (ipAddress == null) { + return false; + } else { + InetAddress ip = parseIpAddress(ipAddress); + return ip.isSiteLocalAddress(); + } } - + public static boolean validIpRange(String startIP, String endIP) { - if (endIP == null || endIP.isEmpty()) { + if (endIP == null || endIP.isEmpty()) { return true; } - - long startIPLong = NetUtils.ip2Long(startIP); - long endIPLong = NetUtils.ip2Long(endIP); - return (startIPLong <= endIPLong); + + long startIPLong = NetUtils.ip2Long(startIP); + long endIPLong = NetUtils.ip2Long(endIP); + return (startIPLong <= endIPLong); } - - public static boolean isValidIp(final String ip) { - final String[] ipAsList = ip.split("\\."); - - // The IP address must have four octets - if (Array.getLength(ipAsList) != 4) { - return false; - } - - for (int i = 0; i < 4; i++) { - // Each octet must be an integer - final String octetString = ipAsList[i]; - int octet; - try { - octet = Integer.parseInt(octetString); - } catch(final Exception e) { - return false; - } - // Each octet must be between 0 and 255, inclusive - if (octet < 0 || octet > 255) { + + public static boolean isValidIp(final String ip) { + final String[] ipAsList = ip.split("\\."); + + // The IP address must have four octets + if (Array.getLength(ipAsList) != 4) { + return false; + } + + for (int i = 0; i < 4; i++) { + // Each octet must be an integer + final String octetString = ipAsList[i]; + int octet; + try { + octet = Integer.parseInt(octetString); + } catch (final Exception e) { + return false; + } + // Each octet must be between 0 and 255, inclusive + if (octet < 0 || octet > 255) { return false; } - // Each octetString must have between 1 and 3 characters - if (octetString.length() < 1 || octetString.length() > 3) { + // Each octetString must have between 1 and 3 characters + if (octetString.length() < 1 || octetString.length() > 3) { return false; } - - } - - // IP is good, return true - return true; - } - - public static boolean isValidCIDR(final String cidr) { - if (cidr == null || cidr.isEmpty()) { + + } + + // IP is good, return true + return true; + } + + public static boolean isValidCIDR(final String cidr) { + if (cidr == null || cidr.isEmpty()) { return false; } String[] cidrPair = cidr.split("\\/"); @@ -473,65 +465,65 @@ public class NetUtils { return false; } int cidrSizeNum = -1; - + try { - cidrSizeNum = Integer.parseInt(cidrSize); + cidrSizeNum = Integer.parseInt(cidrSize); } catch (Exception e) { - return false; + return false; } - + if (cidrSizeNum < 0 || cidrSizeNum > 32) { return false; } - + return true; - } - - public static boolean isValidNetmask(String netmask) { - if (!isValidIp(netmask)) { + } + + public static boolean isValidNetmask(String netmask) { + if (!isValidIp(netmask)) { return false; } - - long ip = ip2Long(netmask); - int count = 0; - boolean finished = false; - for (int i = 31; i >= 0; i--) { - if (((ip >> i) & 0x1) == 0) { - finished = true; - } else { - if (finished) { + + long ip = ip2Long(netmask); + int count = 0; + boolean finished = false; + for (int i = 31; i >= 0; i--) { + if (((ip >> i) & 0x1) == 0) { + finished = true; + } else { + if (finished) { return false; } - count += 1; - } - } - - if (count == 0) { + count += 1; + } + } + + if (count == 0) { return false; } - - return true; - } - - private static InetAddress parseIpAddress(String address) { - StringTokenizer st = new StringTokenizer(address, "."); - byte[] bytes = new byte[4]; - if (st.countTokens() == 4) { - try { - for (int i = 0; i < 4; i++){ - bytes[i] = (byte)Integer.parseInt(st.nextToken()); - } - return InetAddress.getByAddress(address, bytes); - } catch (NumberFormatException nfe) { - return null; - } catch (UnknownHostException uhe){ - return null; - } - } - return null; + return true; } - + + private static InetAddress parseIpAddress(String address) { + StringTokenizer st = new StringTokenizer(address, "."); + byte[] bytes = new byte[4]; + + if (st.countTokens() == 4) { + try { + for (int i = 0; i < 4; i++) { + bytes[i] = (byte) Integer.parseInt(st.nextToken()); + } + return InetAddress.getByAddress(address, bytes); + } catch (NumberFormatException nfe) { + return null; + } catch (UnknownHostException uhe) { + return null; + } + } + return null; + } + public static String getCidrFromGatewayAndNetmask(String gatewayStr, String netmaskStr) { long netmask = ip2Long(netmaskStr); long gateway = ip2Long(gatewayStr); @@ -539,7 +531,7 @@ public class NetUtils { long size = getCidrSize(netmaskStr); return long2Ip(firstPart) + "/" + size; } - + public static String[] getIpRangeFromCidr(String cidr, long size) { assert (size < 32) : "You do know this is not for ipv6 right? Keep it smaller than 32 but you have " + size; String[] result = new String[2]; @@ -547,18 +539,18 @@ public class NetUtils { long startNetMask = ip2Long(getCidrNetmask(size)); long start = (ip & startNetMask) + 1; long end = start; - + end = end >> (32 - size); - + end++; end = (end << (32 - size)) - 2; - + result[0] = long2Ip(start); result[1] = long2Ip(end); - + return result; } - + public static Set getAllIpsFromCidr(String cidr, long size) { assert (size < 32) : "You do know this is not for ipv6 right? Keep it smaller than 32 but you have " + size; Set result = new TreeSet(); @@ -566,120 +558,119 @@ public class NetUtils { long startNetMask = ip2Long(getCidrNetmask(size)); long start = (ip & startNetMask) + 2; long end = start; - + end = end >> (32 - size); - + end++; end = (end << (32 - size)) - 2; while (start <= end) { - result.add(start); - start++; + result.add(start); + start++; } - - + return result; } - + public static String getIpRangeStartIpFromCidr(String cidr, long size) { long ip = ip2Long(cidr); long startNetMask = ip2Long(getCidrNetmask(size)); long start = (ip & startNetMask) + 1; return long2Ip(start); } - + public static String getIpRangeEndIpFromCidr(String cidr, long size) { long ip = ip2Long(cidr); long startNetMask = ip2Long(getCidrNetmask(size)); long start = (ip & startNetMask) + 1; long end = start; end = end >> (32 - size); - + end++; end = (end << (32 - size)) - 2; - return long2Ip(end); + return long2Ip(end); } - + public static boolean sameSubnet(final String ip1, final String ip2, final String netmask) { - if (ip1 == null || ip1.isEmpty() || ip2 == null || ip2.isEmpty()) { + if (ip1 == null || ip1.isEmpty() || ip2 == null || ip2.isEmpty()) { return true; } - String subnet1 = NetUtils.getSubNet(ip1, netmask); - String subnet2 = NetUtils.getSubNet(ip2, netmask); - - return (subnet1.equals(subnet2)); + String subnet1 = NetUtils.getSubNet(ip1, netmask); + String subnet2 = NetUtils.getSubNet(ip2, netmask); + + return (subnet1.equals(subnet2)); } - + public static boolean sameSubnetCIDR(final String ip1, final String ip2, final long cidrSize) { - if (ip1 == null || ip1.isEmpty() || ip2 == null || ip2.isEmpty()) { + if (ip1 == null || ip1.isEmpty() || ip2 == null || ip2.isEmpty()) { return true; } - String subnet1 = NetUtils.getCidrSubNet(ip1, cidrSize); - String subnet2 = NetUtils.getCidrSubNet(ip2, cidrSize); - - return (subnet1.equals(subnet2)); + String subnet1 = NetUtils.getCidrSubNet(ip1, cidrSize); + String subnet2 = NetUtils.getCidrSubNet(ip2, cidrSize); + + return (subnet1.equals(subnet2)); } - + public static String getSubNet(String ip, String netmask) { long ipAddr = ip2Long(ip); long subnet = ip2Long(netmask); long result = ipAddr & subnet; return long2Ip(result); } - + public static String getCidrSubNet(String ip, long cidrSize) { - long numericNetmask = (0xffffffff >> (32 - cidrSize)) << (32 - cidrSize); - String netmask = NetUtils.long2Ip(numericNetmask); - return getSubNet(ip, netmask); + long numericNetmask = (0xffffffff >> (32 - cidrSize)) << (32 - cidrSize); + String netmask = NetUtils.long2Ip(numericNetmask); + return getSubNet(ip, netmask); } - + public static String ipAndNetMaskToCidr(String ip, String netmask) { - long ipAddr = ip2Long(ip); - long subnet = ip2Long(netmask); - long result = ipAddr & subnet; - int bits = (subnet == 0)?0:1; - long subnet2 = subnet; - while ((subnet2 = (subnet2 >> 1) & subnet) != 0 ) { + long ipAddr = ip2Long(ip); + long subnet = ip2Long(netmask); + long result = ipAddr & subnet; + int bits = (subnet == 0) ? 0 : 1; + long subnet2 = subnet; + while ((subnet2 = (subnet2 >> 1) & subnet) != 0) { bits++; } - return long2Ip(result) + "/" + Integer.toString(bits); + return long2Ip(result) + "/" + Integer.toString(bits); } - - public static String [] ipAndNetMaskToRange(String ip, String netmask) { - long ipAddr = ip2Long(ip); - long subnet = ip2Long(netmask); - long start = (ipAddr & subnet) + 1; + + public static String[] ipAndNetMaskToRange(String ip, String netmask) { + long ipAddr = ip2Long(ip); + long subnet = ip2Long(netmask); + long start = (ipAddr & subnet) + 1; long end = start; - int bits = (subnet == 0)?0:1; - while ((subnet = (subnet >> 1) & subnet) != 0 ) { + int bits = (subnet == 0) ? 0 : 1; + while ((subnet = (subnet >> 1) & subnet) != 0) { bits++; } end = end >> (32 - bits); - + end++; end = (end << (32 - bits)) - 2; - - return new String[] {long2Ip(start), long2Ip(end)}; - + + return new String[] { long2Ip(start), long2Ip(end) }; + } - + public static Pair getCidr(String cidr) { String[] tokens = cidr.split("/"); return new Pair(tokens[0], Integer.parseInt(tokens[1])); } - + public static boolean isNetworkAWithinNetworkB(String cidrA, String cidrB) { - Long[] cidrALong = cidrToLong(cidrA); - Long[] cidrBLong = cidrToLong(cidrB); - if (cidrALong == null || cidrBLong == null) { - return false; - } - long shift = 32 - cidrBLong[1]; - return ((cidrALong[0]>>shift) == (cidrBLong[0]>>shift)); + Long[] cidrALong = cidrToLong(cidrA); + Long[] cidrBLong = cidrToLong(cidrB); + if (cidrALong == null || cidrBLong == null) { + return false; + } + long shift = 32 - cidrBLong[1]; + return ((cidrALong[0] >> shift) == (cidrBLong[0] >> shift)); } - + public static Long[] cidrToLong(String cidr) { - if (cidr == null || cidr.isEmpty()) { + if (cidr == null || cidr.isEmpty()) { return null; } String[] cidrPair = cidr.split("\\/"); @@ -692,21 +683,21 @@ public class NetUtils { return null; } int cidrSizeNum = -1; - + try { - cidrSizeNum = Integer.parseInt(cidrSize); + cidrSizeNum = Integer.parseInt(cidrSize); } catch (Exception e) { - return null; + return null; } - long numericNetmask = (0xffffffff >> (32 - cidrSizeNum)) << (32 - cidrSizeNum); - long ipAddr = ip2Long(cidrAddress); - Long[] cidrlong = {ipAddr & numericNetmask, (long)cidrSizeNum}; - return cidrlong; + long numericNetmask = (0xffffffff >> (32 - cidrSizeNum)) << (32 - cidrSizeNum); + long ipAddr = ip2Long(cidrAddress); + Long[] cidrlong = { ipAddr & numericNetmask, (long) cidrSizeNum }; + return cidrlong; } - + public static String getCidrSubNet(String cidr) { - if (cidr == null || cidr.isEmpty()) { + if (cidr == null || cidr.isEmpty()) { return null; } String[] cidrPair = cidr.split("\\/"); @@ -719,149 +710,149 @@ public class NetUtils { return null; } int cidrSizeNum = -1; - + try { - cidrSizeNum = Integer.parseInt(cidrSize); + cidrSizeNum = Integer.parseInt(cidrSize); } catch (Exception e) { - return null; + return null; } - long numericNetmask = (0xffffffff >> (32 - cidrSizeNum)) << (32 - cidrSizeNum); - String netmask = NetUtils.long2Ip(numericNetmask); - return getSubNet(cidrAddress, netmask); + long numericNetmask = (0xffffffff >> (32 - cidrSizeNum)) << (32 - cidrSizeNum); + String netmask = NetUtils.long2Ip(numericNetmask); + return getSubNet(cidrAddress, netmask); } - + public static String getCidrNetmask(long cidrSize) { - long numericNetmask = (0xffffffff >> (32 - cidrSize)) << (32 - cidrSize); - return long2Ip(numericNetmask); + long numericNetmask = (0xffffffff >> (32 - cidrSize)) << (32 - cidrSize); + return long2Ip(numericNetmask); } - + public static String getCidrNetmask(String cidr) { String[] cidrPair = cidr.split("\\/"); long guestCidrSize = Long.parseLong(cidrPair[1]); return getCidrNetmask(guestCidrSize); } - + public static String cidr2Netmask(String cidr) { String[] tokens = cidr.split("\\/"); return getCidrNetmask(Integer.parseInt(tokens[1])); } - + public static long getCidrSize(String netmask) { - long ip = ip2Long(netmask); - int count = 0; - for (int i = 0; i < 32; i++) { - if (((ip >> i) & 0x1) == 0) { - count++; - } else { - break; - } - } - - return 32 - count; + long ip = ip2Long(netmask); + int count = 0; + for (int i = 0; i < 32; i++) { + if (((ip >> i) & 0x1) == 0) { + count++; + } else { + break; + } + } + + return 32 - count; } - + public static boolean isValidPort(String p) { - try { - int port = Integer.parseInt(p); - return !(port > 65535 || port < 1); - } catch (NumberFormatException e) { - return false; - } + try { + int port = Integer.parseInt(p); + return !(port > 65535 || port < 1); + } catch (NumberFormatException e) { + return false; + } } - + public static boolean isValidPort(int p) { return !(p > 65535 || p < 1); } - + public static boolean isValidLBPort(String p) { - try { - int port = Integer.parseInt(p); - return !(port > 65535 || port < 1); - } catch (NumberFormatException e) { - return false; - } + try { + int port = Integer.parseInt(p); + return !(port > 65535 || port < 1); + } catch (NumberFormatException e) { + return false; + } } - + public static boolean isValidProto(String p) { - String proto = p.toLowerCase(); - return (proto.equals("tcp") || proto.equals("udp") || proto.equals("icmp")); + String proto = p.toLowerCase(); + return (proto.equals(TCP_PROTO) || proto.equals(UDP_PROTO) || proto.equals(ICMP_PROTO)); } - + public static boolean isValidSecurityGroupProto(String p) { - String proto = p.toLowerCase(); - return (proto.equals("tcp") || proto.equals("udp") || proto.equals("icmp") || proto.equals("all")); + String proto = p.toLowerCase(); + return (proto.equals(TCP_PROTO) || proto.equals(UDP_PROTO) || proto.equals(ICMP_PROTO) || proto.equals(ALL_PROTO)); } - + public static boolean isValidAlgorithm(String p) { - String algo = p.toLowerCase(); - return (algo.equals("roundrobin") || algo.equals("leastconn") || algo.equals("source")); + String algo = p.toLowerCase(); + return (algo.equals("roundrobin") || algo.equals("leastconn") || algo.equals("source")); } - + public static String getLinkLocalNetMask() { - return "255.255.0.0"; + return "255.255.0.0"; } - + public static String getLinkLocalGateway() { - return "169.254.0.1"; + return "169.254.0.1"; } - + public static String getLinkLocalCIDR() { - return "169.254.0.0/16"; + return "169.254.0.0/16"; } - + public static String[] getLinkLocalIPRange(int size) { - if (size > 16 || size <= 0) { - return null; - } - /*reserve gateway*/ - String[] range = getIpRangeFromCidr(getLinkLocalGateway(), 32 - size); - - if (range[0].equalsIgnoreCase(getLinkLocalGateway())) { - /*remove the gateway*/ - long ip = ip2Long(range[0]); - ip += 1; - range[0] = long2Ip(ip); - } - return range; + if (size > 16 || size <= 0) { + return null; + } + /* reserve gateway */ + String[] range = getIpRangeFromCidr(getLinkLocalGateway(), 32 - size); + + if (range[0].equalsIgnoreCase(getLinkLocalGateway())) { + /* remove the gateway */ + long ip = ip2Long(range[0]); + ip += 1; + range[0] = long2Ip(ip); + } + return range; } - + public static String getLinkLocalIpEnd() { - String[] cidrPair = getLinkLocalCIDR().split("\\/"); - String cidr = cidrPair[0]; - - return getIpRangeEndIpFromCidr(cidr, 32 - Long.parseLong(cidrPair[1])); + String[] cidrPair = getLinkLocalCIDR().split("\\/"); + String cidr = cidrPair[0]; + + return getIpRangeEndIpFromCidr(cidr, 32 - Long.parseLong(cidrPair[1])); } - - public static String portRangeToString(int portRange[]){ + + public static String portRangeToString(int portRange[]) { return Integer.toString(portRange[0]) + ":" + Integer.toString(portRange[1]); } // test only - private static void configLog4j() { - URL configUrl = System.class.getResource("/conf/log4j-cloud.xml"); - if(configUrl != null) { - System.out.println("Configure log4j using log4j-cloud.xml"); + private static void configLog4j() { + URL configUrl = System.class.getResource("/conf/log4j-cloud.xml"); + if (configUrl != null) { + System.out.println("Configure log4j using log4j-cloud.xml"); + + try { + File file = new File(configUrl.toURI()); + + System.out.println("Log4j configuration from : " + file.getAbsolutePath()); + DOMConfigurator.configureAndWatch(file.getAbsolutePath(), 10000); + } catch (URISyntaxException e) { + System.out.println("Unable to convert log4j configuration Url to URI"); + } + // DOMConfigurator.configure(configUrl); + } else { + System.out.println("Configure log4j with default properties"); + } + } - try { - File file = new File(configUrl.toURI()); - - System.out.println("Log4j configuration from : " + file.getAbsolutePath()); - DOMConfigurator.configureAndWatch(file.getAbsolutePath(), 10000); - } catch (URISyntaxException e) { - System.out.println("Unable to convert log4j configuration Url to URI"); - } - // DOMConfigurator.configure(configUrl); - } else { - System.out.println("Configure log4j with default properties"); - } - } - public static void main(String[] args) { - configLog4j(); - - if (args.length == 0) { - System.out.println("Must specify at least one parameter"); - } + configLog4j(); + + if (args.length == 0) { + System.out.println("Must specify at least one parameter"); + } if (args[0].equals("m2l")) { System.out.println(mac2Long(args[1])); } else if (args[0].equals("l2m")) { @@ -887,7 +878,7 @@ public class NetUtils { System.out.println("Netmask: " + result[2]); } } - } else if (args[0].equals("range")){ + } else if (args[0].equals("range")) { if (args.length < 4) { String[] result = getIpRangeFromCidr(args[1], Long.parseLong(args[2])); System.out.println("Range is " + result[0] + "-" + result[1]); @@ -895,35 +886,36 @@ public class NetUtils { System.err.println("Needs 3 parameters: " + args.length); } } else if (args[0].equals("ip2")) { - Set result = getAllIpsFromCidr("10.1.1.192", 24); - System.out.println("Number of ips: " + result.size()); - + Set result = getAllIpsFromCidr("10.1.1.192", 24); + System.out.println("Number of ips: " + result.size()); + } else if (args[0].equals("within")) { - String cidrA = args[1]; - String cidrB = args[2]; - System.out.println(NetUtils.isNetworkAWithinNetworkB(cidrA, cidrB)); - - } else if (args[0].equals("tocidr")) { - String ip = args[1]; - String mask = args[2]; - System.out.println(NetUtils.ipAndNetMaskToCidr(ip, mask)); - } else if (args[0].equals("ipmasktorange")){ - String ip = args[1]; - String mask = args[2]; - String [] range = NetUtils.ipAndNetMaskToRange(ip, mask); - - System.out.println(range[0] + " : " + range[1]); + String cidrA = args[1]; + String cidrB = args[2]; + System.out.println(NetUtils.isNetworkAWithinNetworkB(cidrA, cidrB)); + + } else if (args[0].equals("tocidr")) { + String ip = args[1]; + String mask = args[2]; + System.out.println(NetUtils.ipAndNetMaskToCidr(ip, mask)); + } else if (args[0].equals("ipmasktorange")) { + String ip = args[1]; + String mask = args[2]; + String[] range = NetUtils.ipAndNetMaskToRange(ip, mask); + + System.out.println(range[0] + " : " + range[1]); } else { System.out.println(long2Ip(NumbersUtil.parseLong(args[1], 0))); } } - + public static boolean verifyDomainNameLabel(String hostName, boolean isHostName) { - //must be between 1 and 63 characters long and may contain only the ASCII letters 'a' through 'z' (in a case-insensitive manner), - //the digits '0' through '9', and the hyphen ('-'). - //Can not start with a hyphen and digit, and must not end with a hyphen - //If it's a host name, don't allow to start with digit - + // must be between 1 and 63 characters long and may contain only the ASCII letters 'a' through 'z' (in a + // case-insensitive manner), + // the digits '0' through '9', and the hyphen ('-'). + // Can not start with a hyphen and digit, and must not end with a hyphen + // If it's a host name, don't allow to start with digit + if (hostName.length() > 63 || hostName.length() < 1) { s_logger.warn("Domain name label must be between 1 and 63 characters long"); return false; @@ -940,53 +932,53 @@ public class NetUtils { return true; } - + public static boolean verifyDomainName(String domainName) { - //don't allow domain name length to exceed 190 chars (190 + 63 (max host name length) = 253 = max domainName length + // don't allow domain name length to exceed 190 chars (190 + 63 (max host name length) = 253 = max domainName length if (domainName.length() < 1 || domainName.length() > 190) { s_logger.trace("Domain name must be between 1 and 190 characters long"); return false; } - + if (domainName.startsWith(".") || domainName.endsWith(".")) { s_logger.trace("Domain name can't start or end with ."); return false; } - + String[] domainNameLabels = domainName.split("\\."); - + for (int i = 0; i < domainNameLabels.length; i++) { if (!verifyDomainNameLabel(domainNameLabels[i], false)) { s_logger.warn("Domain name label " + domainNameLabels[i] + " is incorrect"); return false; } } - + return true; } - + public static String getDhcpRange(String cidr) { String[] splitResult = cidr.split("\\/"); long size = Long.valueOf(splitResult[1]); return NetUtils.getIpRangeStartIpFromCidr(splitResult[0], size); } - + public static boolean validateGuestCidr(String cidr) { - //RFC 1918 - The Internet Assigned Numbers Authority (IANA) has reserved the - //following three blocks of the IP address space for private internets: - //10.0.0.0 - 10.255.255.255 (10/8 prefix) - //172.16.0.0 - 172.31.255.255 (172.16/12 prefix) - //192.168.0.0 - 192.168.255.255 (192.168/16 prefix) + // RFC 1918 - The Internet Assigned Numbers Authority (IANA) has reserved the + // following three blocks of the IP address space for private internets: + // 10.0.0.0 - 10.255.255.255 (10/8 prefix) + // 172.16.0.0 - 172.31.255.255 (172.16/12 prefix) + // 192.168.0.0 - 192.168.255.255 (192.168/16 prefix) String cidr1 = "10.0.0.0/8"; String cidr2 = "172.16.0.0/12"; String cidr3 = "192.168.0.0/16"; - + if (!isValidCIDR(cidr)) { s_logger.warn("Cidr " + cidr + " is not valid"); return false; } - + if (isNetworkAWithinNetworkB(cidr, cidr1) || isNetworkAWithinNetworkB(cidr, cidr2) || isNetworkAWithinNetworkB(cidr, cidr3)) { return true; } else { @@ -994,6 +986,5 @@ public class NetUtils { return false; } } - -} +}