bug 10617: merging code from branch bug10617

This commit is contained in:
Naredula Janardhana Reddy 2011-11-10 15:23:48 +05:30
parent a2499c9e69
commit 02adbd4bd3
43 changed files with 933 additions and 1245 deletions

View File

@ -63,8 +63,8 @@ import com.cloud.agent.api.ReadyAnswer;
import com.cloud.agent.api.ReadyCommand; import com.cloud.agent.api.ReadyCommand;
import com.cloud.agent.api.RebootAnswer; import com.cloud.agent.api.RebootAnswer;
import com.cloud.agent.api.RebootCommand; import com.cloud.agent.api.RebootCommand;
import com.cloud.agent.api.SecurityIngressRuleAnswer; import com.cloud.agent.api.SecurityGroupRuleAnswer;
import com.cloud.agent.api.SecurityIngressRulesCmd; import com.cloud.agent.api.SecurityGroupRulesCmd;
import com.cloud.agent.api.StartAnswer; import com.cloud.agent.api.StartAnswer;
import com.cloud.agent.api.StartCommand; import com.cloud.agent.api.StartCommand;
import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupCommand;
@ -234,8 +234,8 @@ public class FakeComputingResource extends ServerResourceBase implements ServerR
return execute((GetStorageStatsCommand) cmd); return execute((GetStorageStatsCommand) cmd);
} else if (cmd instanceof ModifyStoragePoolCommand) { } else if (cmd instanceof ModifyStoragePoolCommand) {
return execute((ModifyStoragePoolCommand) cmd); return execute((ModifyStoragePoolCommand) cmd);
} else if (cmd instanceof SecurityIngressRulesCmd) { } else if (cmd instanceof SecurityGroupRulesCmd) {
return execute((SecurityIngressRulesCmd) cmd); return execute((SecurityGroupRulesCmd) cmd);
} else if (cmd instanceof StartCommand ) { } else if (cmd instanceof StartCommand ) {
return execute((StartCommand) cmd); return execute((StartCommand) cmd);
} else if (cmd instanceof CleanupNetworkRulesCmd) { } else if (cmd instanceof CleanupNetworkRulesCmd) {
@ -257,9 +257,9 @@ public class FakeComputingResource extends ServerResourceBase implements ServerR
return new Answer(cmd); return new Answer(cmd);
} }
private Answer execute(SecurityIngressRulesCmd cmd) { private Answer execute(SecurityGroupRulesCmd cmd) {
s_logger.info("Programmed network rules for vm " + cmd.getVmName() + " guestIp=" + cmd.getGuestIp() + ", numrules=" + cmd.getRuleSet().length); s_logger.info("Programmed network rules for vm " + cmd.getVmName() + " guestIp=" + cmd.getGuestIp() + ", numrules=" + cmd.getRuleSet().length);
return new SecurityIngressRuleAnswer(cmd); return new SecurityGroupRuleAnswer(cmd);
} }
private Answer execute(ModifyStoragePoolCommand cmd) { private Answer execute(ModifyStoragePoolCommand cmd) {

View File

@ -120,8 +120,8 @@ import com.cloud.agent.api.ReadyCommand;
import com.cloud.agent.api.RebootAnswer; import com.cloud.agent.api.RebootAnswer;
import com.cloud.agent.api.RebootCommand; import com.cloud.agent.api.RebootCommand;
import com.cloud.agent.api.RebootRouterCommand; import com.cloud.agent.api.RebootRouterCommand;
import com.cloud.agent.api.SecurityIngressRuleAnswer; import com.cloud.agent.api.SecurityGroupRuleAnswer;
import com.cloud.agent.api.SecurityIngressRulesCmd; import com.cloud.agent.api.SecurityGroupRulesCmd;
import com.cloud.agent.api.StartAnswer; import com.cloud.agent.api.StartAnswer;
import com.cloud.agent.api.StartCommand; import com.cloud.agent.api.StartCommand;
import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupCommand;
@ -913,8 +913,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
return execute((CreateStoragePoolCommand) cmd); return execute((CreateStoragePoolCommand) cmd);
} else if (cmd instanceof ModifyStoragePoolCommand) { } else if (cmd instanceof ModifyStoragePoolCommand) {
return execute((ModifyStoragePoolCommand) cmd); return execute((ModifyStoragePoolCommand) cmd);
} else if (cmd instanceof SecurityIngressRulesCmd) { } else if (cmd instanceof SecurityGroupRulesCmd) {
return execute((SecurityIngressRulesCmd) cmd); return execute((SecurityGroupRulesCmd) cmd);
} else if (cmd instanceof DeleteStoragePoolCommand) { } else if (cmd instanceof DeleteStoragePoolCommand) {
return execute((DeleteStoragePoolCommand) cmd); return execute((DeleteStoragePoolCommand) cmd);
} else if (cmd instanceof FenceCommand ) { } else if (cmd instanceof FenceCommand ) {
@ -1568,7 +1568,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
return answer; return answer;
} }
private Answer execute(SecurityIngressRulesCmd cmd) { private Answer execute(SecurityGroupRulesCmd cmd) {
String vif = null; String vif = null;
String brname = null; String brname = null;
try { try {
@ -1577,10 +1577,10 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
vif = nics.get(0).getDevName(); vif = nics.get(0).getDevName();
brname = nics.get(0).getBrName(); brname = nics.get(0).getBrName();
} catch (LibvirtException e) { } catch (LibvirtException e) {
return new SecurityIngressRuleAnswer(cmd, false, e.toString()); return new SecurityGroupRuleAnswer(cmd, false, e.toString());
} }
boolean result = add_network_rules(cmd.getVmName(), boolean result = add_network_rules(cmd.getRuleType(), cmd.getVmName(),
Long.toString(cmd.getVmId()), Long.toString(cmd.getVmId()),
cmd.getGuestIp(),cmd.getSignature(), cmd.getGuestIp(),cmd.getSignature(),
Long.toString(cmd.getSeqNum()), Long.toString(cmd.getSeqNum()),
@ -1589,10 +1589,10 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
if (!result) { if (!result) {
s_logger.warn("Failed to program network rules for vm " + cmd.getVmName()); s_logger.warn("Failed to program network rules for vm " + cmd.getVmName());
return new SecurityIngressRuleAnswer(cmd, false, "programming network rules failed"); return new SecurityGroupRuleAnswer(cmd, false, "programming network rules failed");
} else { } else {
s_logger.debug("Programmed network rules for vm " + cmd.getVmName() + " guestIp=" + cmd.getGuestIp() + ", numrules=" + cmd.getRuleSet().length); s_logger.debug("Programmed network rules for vm " + cmd.getVmName() + " guestIp=" + cmd.getGuestIp() + ", numrules=" + cmd.getRuleSet().length);
return new SecurityIngressRuleAnswer(cmd); return new SecurityGroupRuleAnswer(cmd);
} }
} }
@ -3540,7 +3540,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
return true; return true;
} }
private boolean add_network_rules(String vmName, String vmId, String guestIP, String sig, String seq, String mac, String rules, String vif, String brname) { private boolean add_network_rules(String ruleType, String vmName, String vmId, String guestIP, String sig, String seq, String mac, String rules, String vif, String brname) {
if (!_can_bridge_firewall) { if (!_can_bridge_firewall) {
return false; return false;
} }
@ -3551,6 +3551,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
cmd.add("--vmname", vmName); cmd.add("--vmname", vmName);
cmd.add("--vmid", vmId); cmd.add("--vmid", vmId);
cmd.add("--vmip", guestIP); cmd.add("--vmip", guestIP);
cmd.add("--ruletype", ruleType);
cmd.add("--sig", sig); cmd.add("--sig", sig);
cmd.add("--seq", seq); cmd.add("--seq", seq);
cmd.add("--vmmac", mac); cmd.add("--vmmac", mac);

View File

@ -1,47 +0,0 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.agent.api;
public class SecurityEgressRuleAnswer extends Answer {
Long logSequenceNumber = null;
Long vmId = null;
protected SecurityEgressRuleAnswer() {
}
public SecurityEgressRuleAnswer(SecurityEgressRulesCmd cmd) {
super(cmd);
this.logSequenceNumber = cmd.getSeqNum();
this.vmId = cmd.getVmId();
}
public SecurityEgressRuleAnswer(SecurityEgressRulesCmd cmd, boolean result, String detail) {
super(cmd, result, detail);
this.logSequenceNumber = cmd.getSeqNum();
this.vmId = cmd.getVmId();
}
public Long getLogSequenceNumber() {
return logSequenceNumber;
}
public Long getVmId() {
return vmId;
}
}

View File

@ -1,144 +0,0 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.agent.api;
public class SecurityEgressRulesCmd extends Command {
public static class EgressIpPortAndProto {
String proto;
int startPort;
int endPort;
String [] allowedCidrs;
public EgressIpPortAndProto() { }
public EgressIpPortAndProto(String proto, int startPort, int endPort,
String[] allowedCidrs) {
super();
this.proto = proto;
this.startPort = startPort;
this.endPort = endPort;
this.allowedCidrs = allowedCidrs;
}
public String[] getAllowedCidrs() {
return allowedCidrs;
}
public void setAllowedCidrs(String[] allowedCidrs) {
this.allowedCidrs = allowedCidrs;
}
public String getProto() {
return proto;
}
public int getStartPort() {
return startPort;
}
public int getEndPort() {
return endPort;
}
}
String guestIp;
String vmName;
String guestMac;
String signature;
Long seqNum;
Long vmId;
EgressIpPortAndProto [] ruleSet;
public SecurityEgressRulesCmd() {
super();
}
public SecurityEgressRulesCmd(String guestIp, String guestMac, String vmName, Long vmId, String signature, Long seqNum, EgressIpPortAndProto[] ruleSet) {
super();
this.guestIp = guestIp;
this.vmName = vmName;
this.ruleSet = ruleSet;
this.guestMac = guestMac;
this.signature = signature;
this.seqNum = seqNum;
this.vmId = vmId;
}
@Override
public boolean executeInSequence() {
return true;
}
public EgressIpPortAndProto[] getRuleSet() {
return ruleSet;
}
public void setRuleSet(EgressIpPortAndProto[] ruleSet) {
this.ruleSet = ruleSet;
}
public String getGuestIp() {
return guestIp;
}
public String getVmName() {
return vmName;
}
public String stringifyRules() {
StringBuilder ruleBuilder = new StringBuilder();
for (SecurityEgressRulesCmd.EgressIpPortAndProto ipPandP: getRuleSet()) {
ruleBuilder.append(ipPandP.getProto()).append(":").append(ipPandP.getStartPort()).append(":").append(ipPandP.getEndPort()).append(":");
for (String cidr: ipPandP.getAllowedCidrs()) {
ruleBuilder.append(cidr).append(",");
}
ruleBuilder.append("NEXT");
ruleBuilder.append(" ");
}
return ruleBuilder.toString();
}
public String getSignature() {
return signature;
}
public String getGuestMac() {
return guestMac;
}
public Long getSeqNum() {
return seqNum;
}
public Long getVmId() {
return vmId;
}
}

View File

@ -17,7 +17,7 @@
*/ */
package com.cloud.agent.api; package com.cloud.agent.api;
public class SecurityIngressRuleAnswer extends Answer { public class SecurityGroupRuleAnswer extends Answer {
public static enum FailureReason { public static enum FailureReason {
NONE, NONE,
UNKNOWN, UNKNOWN,
@ -29,23 +29,23 @@ public class SecurityIngressRuleAnswer extends Answer {
FailureReason reason = FailureReason.NONE; FailureReason reason = FailureReason.NONE;
protected SecurityIngressRuleAnswer() { protected SecurityGroupRuleAnswer() {
} }
public SecurityIngressRuleAnswer(SecurityIngressRulesCmd cmd) { public SecurityGroupRuleAnswer(SecurityGroupRulesCmd cmd) {
super(cmd); super(cmd);
this.logSequenceNumber = cmd.getSeqNum(); this.logSequenceNumber = cmd.getSeqNum();
this.vmId = cmd.getVmId(); this.vmId = cmd.getVmId();
} }
public SecurityIngressRuleAnswer(SecurityIngressRulesCmd cmd, boolean result, String detail) { public SecurityGroupRuleAnswer(SecurityGroupRulesCmd cmd, boolean result, String detail) {
super(cmd, result, detail); super(cmd, result, detail);
this.logSequenceNumber = cmd.getSeqNum(); this.logSequenceNumber = cmd.getSeqNum();
this.vmId = cmd.getVmId(); this.vmId = cmd.getVmId();
reason = FailureReason.PROGRAMMING_FAILED; reason = FailureReason.PROGRAMMING_FAILED;
} }
public SecurityIngressRuleAnswer(SecurityIngressRulesCmd cmd, boolean result, String detail, FailureReason r) { public SecurityGroupRuleAnswer(SecurityGroupRulesCmd cmd, boolean result, String detail, FailureReason r) {
super(cmd, result, detail); super(cmd, result, detail);
this.logSequenceNumber = cmd.getSeqNum(); this.logSequenceNumber = cmd.getSeqNum();
this.vmId = cmd.getVmId(); this.vmId = cmd.getVmId();

View File

@ -26,11 +26,12 @@ import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import com.cloud.agent.api.LogLevel.Log4jLevel; import com.cloud.agent.api.LogLevel.Log4jLevel;
import com.cloud.network.security.SecurityRule.SecurityRuleType;
import com.cloud.utils.net.NetUtils; import com.cloud.utils.net.NetUtils;
public class SecurityIngressRulesCmd extends Command { public class SecurityGroupRulesCmd extends Command {
private static Logger s_logger = Logger.getLogger(SecurityIngressRulesCmd.class); private static Logger s_logger = Logger.getLogger(SecurityGroupRulesCmd.class);
public static class IpPortAndProto { public static class IpPortAndProto {
String proto; String proto;
int startPort; int startPort;
@ -80,13 +81,14 @@ public class SecurityIngressRulesCmd extends Command {
Long vmId; Long vmId;
Long msId; Long msId;
IpPortAndProto [] ruleSet; IpPortAndProto [] ruleSet;
SecurityRuleType ruleType;
public SecurityIngressRulesCmd() { public SecurityGroupRulesCmd() {
super(); super();
} }
public SecurityIngressRulesCmd(String guestIp, String guestMac, String vmName, Long vmId, String signature, Long seqNum, IpPortAndProto[] ruleSet) { public SecurityGroupRulesCmd(SecurityRuleType ruleType, String guestIp, String guestMac, String vmName, Long vmId, String signature, Long seqNum, IpPortAndProto[] ruleSet) {
super(); super();
this.guestIp = guestIp; this.guestIp = guestIp;
this.vmName = vmName; this.vmName = vmName;
@ -95,12 +97,17 @@ public class SecurityIngressRulesCmd extends Command {
this.signature = signature; this.signature = signature;
this.seqNum = seqNum; this.seqNum = seqNum;
this.vmId = vmId; this.vmId = vmId;
this.ruleType = ruleType;
if (signature == null) { if (signature == null) {
String stringified = stringifyRules(); String stringified = stringifyRules();
this.signature = DigestUtils.md5Hex(stringified); this.signature = DigestUtils.md5Hex(stringified);
} }
} }
public String getRuleType(){
if (this.ruleType == SecurityRuleType.EgressRule) return SecurityRuleType.EgressRule.getType();
return SecurityRuleType.IngressRule.getType();
}
@Override @Override
public boolean executeInSequence() { public boolean executeInSequence() {
@ -129,7 +136,7 @@ public class SecurityIngressRulesCmd extends Command {
public String stringifyRules() { public String stringifyRules() {
StringBuilder ruleBuilder = new StringBuilder(); StringBuilder ruleBuilder = new StringBuilder();
for (SecurityIngressRulesCmd.IpPortAndProto ipPandP: getRuleSet()) { for (SecurityGroupRulesCmd.IpPortAndProto ipPandP: getRuleSet()) {
ruleBuilder.append(ipPandP.getProto()).append(":").append(ipPandP.getStartPort()).append(":").append(ipPandP.getEndPort()).append(":"); ruleBuilder.append(ipPandP.getProto()).append(":").append(ipPandP.getStartPort()).append(":").append(ipPandP.getEndPort()).append(":");
for (String cidr: ipPandP.getAllowedCidrs()) { for (String cidr: ipPandP.getAllowedCidrs()) {
ruleBuilder.append(cidr).append(","); ruleBuilder.append(cidr).append(",");
@ -150,7 +157,7 @@ public class SecurityIngressRulesCmd extends Command {
public String stringifyCompressedRules() { public String stringifyCompressedRules() {
StringBuilder ruleBuilder = new StringBuilder(); StringBuilder ruleBuilder = new StringBuilder();
for (SecurityIngressRulesCmd.IpPortAndProto ipPandP: getRuleSet()) { for (SecurityGroupRulesCmd.IpPortAndProto ipPandP: getRuleSet()) {
ruleBuilder.append(ipPandP.getProto()).append(":").append(ipPandP.getStartPort()).append(":").append(ipPandP.getEndPort()).append(":"); ruleBuilder.append(ipPandP.getProto()).append(":").append(ipPandP.getStartPort()).append(":").append(ipPandP.getEndPort()).append(":");
for (String cidr: ipPandP.getAllowedCidrs()) { for (String cidr: ipPandP.getAllowedCidrs()) {
//convert cidrs in the form "a.b.c.d/e" to "hexvalue of 32bit ip/e" //convert cidrs in the form "a.b.c.d/e" to "hexvalue of 32bit ip/e"
@ -162,12 +169,12 @@ public class SecurityIngressRulesCmd extends Command {
return ruleBuilder.toString(); return ruleBuilder.toString();
} }
/* /*
* Compress the ingress rules using zlib compression to allow the call to the hypervisor * Compress the security group rules using zlib compression to allow the call to the hypervisor
* to scale beyond 8k cidrs. * to scale beyond 8k cidrs.
*/ */
public String compressStringifiedRules() { public String compressStringifiedRules() {
StringBuilder ruleBuilder = new StringBuilder(); StringBuilder ruleBuilder = new StringBuilder();
for (SecurityIngressRulesCmd.IpPortAndProto ipPandP: getRuleSet()) { for (SecurityGroupRulesCmd.IpPortAndProto ipPandP: getRuleSet()) {
ruleBuilder.append(ipPandP.getProto()).append(":").append(ipPandP.getStartPort()).append(":").append(ipPandP.getEndPort()).append(":"); ruleBuilder.append(ipPandP.getProto()).append(":").append(ipPandP.getStartPort()).append(":").append(ipPandP.getEndPort()).append(":");
for (String cidr: ipPandP.getAllowedCidrs()) { for (String cidr: ipPandP.getAllowedCidrs()) {
ruleBuilder.append(cidr).append(","); ruleBuilder.append(cidr).append(",");
@ -184,7 +191,7 @@ public class SecurityIngressRulesCmd extends Command {
dzip.write(stringified.getBytes()); dzip.write(stringified.getBytes());
dzip.close(); dzip.close();
} catch (IOException e) { } catch (IOException e) {
s_logger.warn("Exception while compressing ingress rules"); s_logger.warn("Exception while compressing security group rules");
return null; return null;
} }
return Base64.encodeBase64String(out.toByteArray()); return Base64.encodeBase64String(out.toByteArray());

View File

@ -87,8 +87,7 @@ import com.cloud.network.rules.FirewallRule;
import com.cloud.network.rules.LoadBalancer; import com.cloud.network.rules.LoadBalancer;
import com.cloud.network.rules.PortForwardingRule; import com.cloud.network.rules.PortForwardingRule;
import com.cloud.network.rules.StaticNatRule; import com.cloud.network.rules.StaticNatRule;
import com.cloud.network.security.EgressRule; import com.cloud.network.security.SecurityRule;
import com.cloud.network.security.IngressRule;
import com.cloud.network.security.SecurityGroup; import com.cloud.network.security.SecurityGroup;
import com.cloud.network.security.SecurityGroupRules; import com.cloud.network.security.SecurityGroupRules;
import com.cloud.offering.DiskOffering; import com.cloud.offering.DiskOffering;
@ -187,9 +186,7 @@ public interface ResponseGenerator {
ListResponse<SecurityGroupResponse> createSecurityGroupResponses(List<? extends SecurityGroupRules> networkGroups); ListResponse<SecurityGroupResponse> createSecurityGroupResponses(List<? extends SecurityGroupRules> networkGroups);
SecurityGroupResponse createSecurityGroupResponseFromIngressRule(List<? extends IngressRule> ingressRules); SecurityGroupResponse createSecurityGroupResponseFromSecurityGroupRule(List<? extends SecurityRule> SecurityRules);
SecurityGroupResponse createSecurityGroupResponseFromEgressRule(List<? extends EgressRule> egressRules);
SecurityGroupResponse createSecurityGroupResponse(SecurityGroup group); SecurityGroupResponse createSecurityGroupResponse(SecurityGroup group);

View File

@ -0,0 +1,233 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.api.commands;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import com.cloud.api.ApiConstants;
import com.cloud.api.BaseAsyncCmd;
import com.cloud.api.BaseCmd;
import com.cloud.api.IdentityMapper;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.api.response.SecurityGroupRuleResponse;
import com.cloud.api.response.SecurityGroupResponse;
import com.cloud.async.AsyncJob;
import com.cloud.event.EventTypes;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.network.security.SecurityRule;
import com.cloud.user.Account;
import com.cloud.user.UserContext;
import com.cloud.utils.StringUtils;
@Implementation(responseObject = SecurityGroupRuleResponse.class, description = "Authorizes a particular egress rule for this security group")
@SuppressWarnings("rawtypes")
public class AuthorizeSecurityGroupEgressCmd extends BaseAsyncCmd {
public static final Logger s_logger = Logger.getLogger(AuthorizeSecurityGroupIngressCmd.class.getName());
private static final String s_name = "authorizesecuritygroupegressresponse";
// ///////////////////////////////////////////////////
// ////////////// API parameters /////////////////////
// ///////////////////////////////////////////////////
@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 egress rule")
private Integer startPort;
@Parameter(name = ApiConstants.END_PORT, type = CommandType.INTEGER, description = "end port for this egress rule")
private Integer endPort;
@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")
private Integer icmpCode;
@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")
private Map userSecurityGroupList;
@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.ACCOUNT, type=CommandType.STRING, description="an optional account for the security group. Must be used with domainId.")
private String accountName;
@IdentityMapper(entityTableName="projects")
@Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="an optional project of the security group")
private Long projectId;
@IdentityMapper(entityTableName="security_group")
@Parameter(name=ApiConstants.SECURITY_GROUP_ID, type=CommandType.LONG, description="The ID of the security group. Mutually exclusive with securityGroupName parameter")
private Long securityGroupId;
@Parameter(name=ApiConstants.SECURITY_GROUP_NAME, type=CommandType.STRING, description="The name of the security group. Mutually exclusive with securityGroupName parameter")
private String securityGroupName;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
public String getAccountName() {
return accountName;
}
public List getCidrList() {
return cidrList;
}
public Integer getEndPort() {
return endPort;
}
public Integer getIcmpCode() {
return icmpCode;
}
public Integer getIcmpType() {
return icmpType;
}
public Long getSecurityGroupId() {
if (securityGroupId != null && securityGroupName != null) {
throw new InvalidParameterValueException("securityGroupId and securityGroupName parameters are mutually exclusive");
}
if (securityGroupName != null) {
securityGroupId = _responseGenerator.getSecurityGroupId(securityGroupName, getEntityOwnerId());
if (securityGroupId == null) {
throw new InvalidParameterValueException("Unable to find security group " + securityGroupName + " for account id=" + getEntityOwnerId());
}
securityGroupName = null;
}
if (securityGroupId == null) {
throw new InvalidParameterValueException("Either securityGroupId or securityGroupName is required by authorizeSecurityGroupIngress command");
}
return securityGroupId;
}
public String getProtocol() {
if (protocol == null) {
return "all";
}
return protocol;
}
public Integer getStartPort() {
return startPort;
}
public Map getUserSecurityGroupList() {
return userSecurityGroupList;
}
// ///////////////////////////////////////////////////
// ///////////// API Implementation///////////////////
// ///////////////////////////////////////////////////
@Override
public String getCommandName() {
return s_name;
}
public static String getResultObjectName() {
return "securitygroup";
}
@Override
public long getEntityOwnerId() {
Long accountId = getAccountId(accountName, domainId, projectId);
if (accountId == null) {
return UserContext.current().getCaller().getId();
}
return accountId;
}
@Override
public String getEventType() {
return EventTypes.EVENT_SECURITY_GROUP_AUTHORIZE_EGRESS;
}
@Override
public String getEventDescription() {
StringBuilder sb = new StringBuilder();
if (getUserSecurityGroupList() != null) {
sb.append("group list(group/account): ");
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");
sb.append(group + "/" + authorizedAccountName);
while (iter.hasNext()) {
userGroup = (HashMap) iter.next();
group = (String) userGroup.get("group");
authorizedAccountName = (String) userGroup.get("account");
sb.append(", " + group + "/" + authorizedAccountName);
}
} else if (getCidrList() != null) {
sb.append("cidr list: ");
sb.append(StringUtils.join(getCidrList(), ", "));
} else {
sb.append("<error: no egress parameters>");
}
return "authorizing egress to group: " + getSecurityGroupId() + " to " + sb.toString();
}
@Override
public void execute() {
List<? extends SecurityRule> egressRules = _securityGroupService.authorizeSecurityGroupEgress(this);
if (egressRules != null && !egressRules.isEmpty()) {
SecurityGroupResponse response = _responseGenerator.createSecurityGroupResponseFromSecurityGroupRule(egressRules);
this.setResponseObject(response);
} else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to authorize security group egress rule(s)");
}
}
@Override
public AsyncJob.Type getInstanceType() {
return AsyncJob.Type.SecurityGroup;
}
@Override
public Long getInstanceId() {
return getSecurityGroupId();
}
}

View File

@ -33,18 +33,16 @@ import com.cloud.api.IdentityMapper;
import com.cloud.api.Implementation; import com.cloud.api.Implementation;
import com.cloud.api.Parameter; import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException; import com.cloud.api.ServerApiException;
import com.cloud.api.BaseCmd.CommandType; import com.cloud.api.response.SecurityGroupRuleResponse;
import com.cloud.api.response.IngressRuleResponse;
import com.cloud.api.response.SecurityGroupResponse; import com.cloud.api.response.SecurityGroupResponse;
import com.cloud.async.AsyncJob; import com.cloud.async.AsyncJob;
import com.cloud.event.EventTypes; import com.cloud.event.EventTypes;
import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.InvalidParameterValueException;
import com.cloud.network.security.IngressRule; import com.cloud.network.security.SecurityRule;
import com.cloud.user.Account;
import com.cloud.user.UserContext; import com.cloud.user.UserContext;
import com.cloud.utils.StringUtils; import com.cloud.utils.StringUtils;
@Implementation(responseObject = IngressRuleResponse.class, description = "Authorizes a particular ingress rule for this security group") @Implementation(responseObject = SecurityGroupRuleResponse.class, description = "Authorizes a particular ingress rule for this security group")
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public class AuthorizeSecurityGroupIngressCmd extends BaseAsyncCmd { 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());
@ -212,9 +210,9 @@ public class AuthorizeSecurityGroupIngressCmd extends BaseAsyncCmd {
@Override @Override
public void execute() { public void execute() {
List<? extends IngressRule> ingressRules = _securityGroupService.authorizeSecurityGroupIngress(this); List<? extends SecurityRule> ingressRules = _securityGroupService.authorizeSecurityGroupIngress(this);
if (ingressRules != null && !ingressRules.isEmpty()) { if (ingressRules != null && !ingressRules.isEmpty()) {
SecurityGroupResponse response = _responseGenerator.createSecurityGroupResponseFromIngressRule(ingressRules); SecurityGroupResponse response = _responseGenerator.createSecurityGroupResponseFromSecurityGroupRule(ingressRules);
this.setResponseObject(response); this.setResponseObject(response);
} else { } else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to authorize security group ingress rule(s)"); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to authorize security group ingress rule(s)");

View File

@ -0,0 +1,111 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.api.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.IdentityMapper;
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 egress rule from this security group")
public class RevokeSecurityGroupEgressCmd extends BaseAsyncCmd {
public static final Logger s_logger = Logger.getLogger(RevokeSecurityGroupEgressCmd.class.getName());
private static final String s_name = "revokesecuritygroupegress";
// ///////////////////////////////////////////////////
// ////////////// API parameters /////////////////////
// ///////////////////////////////////////////////////
@IdentityMapper(entityTableName="security_group_rule")
@Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "The ID of the egress rule")
private Long id;
// ///////////////////////////////////////////////////
// ///////////////// Accessors ///////////////////////
// ///////////////////////////////////////////////////
public Long getId() {
return id;
}
// ///////////////////////////////////////////////////
// ///////////// API Implementation///////////////////
// ///////////////////////////////////////////////////
@Override
public String getCommandName() {
return s_name;
}
public static String getResultObjectName() {
return "revokesecuritygroupegress";
}
@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_EGRESS;
}
@Override
public String getEventDescription() {
return "revoking egress rule id: " + getId();
}
@Override
public void execute() {
boolean result = _securityGroupService.revokeSecurityGroupEgress(this);
if (result) {
SuccessResponse response = new SuccessResponse(getCommandName());
this.setResponseObject(response);
} else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to revoke security group egress rule");
}
}
@Override
public AsyncJob.Type getInstanceType() {
return AsyncJob.Type.SecurityGroup;
}
@Override
public Long getInstanceId() {
return getId();
}
}

View File

@ -43,7 +43,7 @@ public class RevokeSecurityGroupIngressCmd extends BaseAsyncCmd {
// ////////////// API parameters ///////////////////// // ////////////// API parameters /////////////////////
// /////////////////////////////////////////////////// // ///////////////////////////////////////////////////
@IdentityMapper(entityTableName="security_ingress_rule") @IdentityMapper(entityTableName="security_group_rule")
@Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "The ID of the ingress rule") @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "The ID of the ingress rule")
private Long id; private Long id;

View File

@ -1,124 +0,0 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.api.response;
import com.cloud.api.ApiConstants;
import com.cloud.api.IdentityProxy;
import com.cloud.serializer.Param;
import com.google.gson.annotations.SerializedName;
public class IngressRuleResponse extends BaseResponse {
@SerializedName("ruleid") @Param(description="the id of the ingress rule")
private IdentityProxy ruleId = new IdentityProxy("security_ingress_rule");
@SerializedName("protocol") @Param(description="the protocol of the ingress rule")
private String protocol;
@SerializedName(ApiConstants.ICMP_TYPE) @Param(description="the type of the ICMP message response")
private Integer icmpType;
@SerializedName(ApiConstants.ICMP_CODE) @Param(description="the code for the ICMP message response")
private Integer icmpCode;
@SerializedName(ApiConstants.START_PORT) @Param(description="the starting IP of the ingress rule")
private Integer startPort;
@SerializedName(ApiConstants.END_PORT) @Param(description="the ending IP of the ingress rule ")
private Integer endPort;
@SerializedName(ApiConstants.SECURITY_GROUP_NAME) @Param(description="security group name")
private String securityGroupName;
@SerializedName(ApiConstants.ACCOUNT) @Param(description="account owning the ingress rule")
private String accountName;
@SerializedName(ApiConstants.CIDR) @Param(description="the CIDR notation for the base IP address of the ingress rule")
private String cidr;
public Long getRuleId() {
return ruleId.getValue();
}
public void setRuleId(Long ruleId) {
this.ruleId.setValue(ruleId);
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public Integer getIcmpType() {
return icmpType;
}
public void setIcmpType(Integer icmpType) {
this.icmpType = icmpType;
}
public Integer getIcmpCode() {
return icmpCode;
}
public void setIcmpCode(Integer icmpCode) {
this.icmpCode = icmpCode;
}
public Integer getStartPort() {
return startPort;
}
public void setStartPort(Integer startPort) {
this.startPort = startPort;
}
public Integer getEndPort() {
return endPort;
}
public void setEndPort(Integer endPort) {
this.endPort = endPort;
}
public String getSecurityGroupName() {
return securityGroupName;
}
public void setSecurityGroupName(String securityGroupName) {
this.securityGroupName = securityGroupName;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public String getCidr() {
return cidr;
}
public void setCidr(String cidr) {
this.cidr = cidr;
}
}

View File

@ -50,11 +50,11 @@ public class SecurityGroupResponse extends BaseResponse implements ControlledEnt
@SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name of the security group") @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name of the security group")
private String domainName; private String domainName;
@SerializedName("ingressrule") @Param(description="the list of ingress rules associated with the security group", responseObject = IngressRuleResponse.class) @SerializedName("ingressrule") @Param(description="the list of ingress rules associated with the security group", responseObject = SecurityGroupRuleResponse.class)
private List<IngressRuleResponse> ingressRules; private List<SecurityGroupRuleResponse> ingressRules;
@SerializedName("egressrule") @Param(description="the list of ingress rules associated with the security group", responseObject = EgressRuleResponse.class) @SerializedName("egressrule") @Param(description="the list of egress rules associated with the security group", responseObject = SecurityGroupRuleResponse.class)
private List<EgressRuleResponse> egressRules; private List<SecurityGroupRuleResponse> egressRules;
public void setId(Long id) { public void setId(Long id) {
this.id.setValue(id); this.id.setValue(id);
@ -84,12 +84,12 @@ public class SecurityGroupResponse extends BaseResponse implements ControlledEnt
this.domainName = domainName; this.domainName = domainName;
} }
public void setIngressRules(List<IngressRuleResponse> ingressRules) { public void setSecurityGroupIngressRules(List<SecurityGroupRuleResponse> securityGroupRules) {
this.ingressRules = ingressRules; this.ingressRules = securityGroupRules;
} }
public void setEgressRules(List<EgressRuleResponse> egressRules) { public void setSecurityGroupEgressRules(List<SecurityGroupRuleResponse> securityGroupRules) {
this.egressRules = egressRules; this.egressRules = securityGroupRules;
} }
@Override @Override

View File

@ -22,11 +22,11 @@ import com.cloud.api.IdentityProxy;
import com.cloud.serializer.Param; import com.cloud.serializer.Param;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
public class EgressRuleResponse extends BaseResponse { public class SecurityGroupRuleResponse extends BaseResponse {
@SerializedName("ruleid") @Param(description="the id of the ingress rule") @SerializedName("ruleid") @Param(description="the id of the security group rule")
private IdentityProxy ruleId = new IdentityProxy("security_egress_rule"); private IdentityProxy ruleId = new IdentityProxy("security_group_rule");
@SerializedName("protocol") @Param(description="the protocol of the ingress rule") @SerializedName("protocol") @Param(description="the protocol of the security group rule")
private String protocol; private String protocol;
@SerializedName(ApiConstants.ICMP_TYPE) @Param(description="the type of the ICMP message response") @SerializedName(ApiConstants.ICMP_TYPE) @Param(description="the type of the ICMP message response")
@ -35,19 +35,19 @@ public class EgressRuleResponse extends BaseResponse {
@SerializedName(ApiConstants.ICMP_CODE) @Param(description="the code for the ICMP message response") @SerializedName(ApiConstants.ICMP_CODE) @Param(description="the code for the ICMP message response")
private Integer icmpCode; private Integer icmpCode;
@SerializedName(ApiConstants.START_PORT) @Param(description="the starting IP of the ingress rule") @SerializedName(ApiConstants.START_PORT) @Param(description="the starting IP of the security group rule")
private Integer startPort; private Integer startPort;
@SerializedName(ApiConstants.END_PORT) @Param(description="the ending IP of the ingress rule ") @SerializedName(ApiConstants.END_PORT) @Param(description="the ending IP of the security group rule ")
private Integer endPort; private Integer endPort;
@SerializedName(ApiConstants.SECURITY_GROUP_NAME) @Param(description="security group name") @SerializedName(ApiConstants.SECURITY_GROUP_NAME) @Param(description="security group name")
private String securityGroupName; private String securityGroupName;
@SerializedName(ApiConstants.ACCOUNT) @Param(description="account owning the ingress rule") @SerializedName(ApiConstants.ACCOUNT) @Param(description="account owning the security group rule")
private String accountName; private String accountName;
@SerializedName(ApiConstants.CIDR) @Param(description="the CIDR notation for the base IP address of the ingress rule") @SerializedName(ApiConstants.CIDR) @Param(description="the CIDR notation for the base IP address of the security group rule")
private String cidr; private String cidr;
public Long getRuleId() { public Long getRuleId() {

View File

@ -174,6 +174,8 @@ public class EventTypes {
// Security Groups // Security Groups
public static final String EVENT_SECURITY_GROUP_AUTHORIZE_INGRESS = "SG.AUTH.INGRESS"; public static final String EVENT_SECURITY_GROUP_AUTHORIZE_INGRESS = "SG.AUTH.INGRESS";
public static final String EVENT_SECURITY_GROUP_REVOKE_INGRESS = "SG.REVOKE.INGRESS"; public static final String EVENT_SECURITY_GROUP_REVOKE_INGRESS = "SG.REVOKE.INGRESS";
public static final String EVENT_SECURITY_GROUP_AUTHORIZE_EGRESS = "SG.AUTH.EGRESS";
public static final String EVENT_SECURITY_GROUP_REVOKE_EGRESS = "SG.REVOKE.EGRESS";
public static final String EVENT_SECURITY_GROUP_CREATE = "SG.CREATE"; public static final String EVENT_SECURITY_GROUP_CREATE = "SG.CREATE";
public static final String EVENT_SECURITY_GROUP_DELETE = "SG.DELETE"; public static final String EVENT_SECURITY_GROUP_DELETE = "SG.DELETE";

View File

@ -1,39 +0,0 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.network.security;
import com.cloud.async.AsyncInstanceCreateStatus;
public interface EgressRule {
long getId();
long getSecurityGroupId();
int getStartPort();
int getEndPort();
String getProtocol();
AsyncInstanceCreateStatus getCreateStatus();
Long getAllowedNetworkId();
String getAllowedDestinationIpCidr();
}

View File

@ -16,6 +16,7 @@
* *
*/ */
package com.cloud.network.security; package com.cloud.network.security;
import com.cloud.network.security.SecurityRule.SecurityRuleType;
public interface SecurityGroupRules { public interface SecurityGroupRules {
long getId(); long getId();
@ -39,4 +40,6 @@ public interface SecurityGroupRules {
Long getAllowedNetworkId(); Long getAllowedNetworkId();
String getAllowedSourceIpCidr(); String getAllowedSourceIpCidr();
SecurityRuleType getRuleType();
} }

View File

@ -20,10 +20,12 @@ package com.cloud.network.security;
import java.util.List; import java.util.List;
import com.cloud.api.commands.AuthorizeSecurityGroupIngressCmd; import com.cloud.api.commands.AuthorizeSecurityGroupIngressCmd;
import com.cloud.api.commands.AuthorizeSecurityGroupEgressCmd;
import com.cloud.api.commands.CreateSecurityGroupCmd; import com.cloud.api.commands.CreateSecurityGroupCmd;
import com.cloud.api.commands.DeleteSecurityGroupCmd; import com.cloud.api.commands.DeleteSecurityGroupCmd;
import com.cloud.api.commands.ListSecurityGroupsCmd; import com.cloud.api.commands.ListSecurityGroupsCmd;
import com.cloud.api.commands.RevokeSecurityGroupIngressCmd; import com.cloud.api.commands.RevokeSecurityGroupIngressCmd;
import com.cloud.api.commands.RevokeSecurityGroupEgressCmd;
import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.PermissionDeniedException;
import com.cloud.exception.ResourceInUseException; import com.cloud.exception.ResourceInUseException;
@ -36,6 +38,7 @@ public interface SecurityGroupService {
*/ */
public SecurityGroup createSecurityGroup(CreateSecurityGroupCmd command) throws PermissionDeniedException, InvalidParameterValueException; public SecurityGroup createSecurityGroup(CreateSecurityGroupCmd command) throws PermissionDeniedException, InvalidParameterValueException;
boolean revokeSecurityGroupIngress(RevokeSecurityGroupIngressCmd cmd); boolean revokeSecurityGroupIngress(RevokeSecurityGroupIngressCmd cmd);
boolean revokeSecurityGroupEgress(RevokeSecurityGroupEgressCmd cmd);
boolean deleteSecurityGroup(DeleteSecurityGroupCmd cmd) throws ResourceInUseException; boolean deleteSecurityGroup(DeleteSecurityGroupCmd cmd) throws ResourceInUseException;
@ -46,6 +49,8 @@ public interface SecurityGroupService {
*/ */
public List<? extends SecurityGroupRules> searchForSecurityGroupRules(ListSecurityGroupsCmd cmd) throws PermissionDeniedException, InvalidParameterValueException; public List<? extends SecurityGroupRules> searchForSecurityGroupRules(ListSecurityGroupsCmd cmd) throws PermissionDeniedException, InvalidParameterValueException;
public List<? extends IngressRule> authorizeSecurityGroupIngress(AuthorizeSecurityGroupIngressCmd cmd); public List<? extends SecurityRule> authorizeSecurityGroupIngress(AuthorizeSecurityGroupIngressCmd cmd);
public List<? extends SecurityRule> authorizeSecurityGroupEgress(AuthorizeSecurityGroupEgressCmd cmd);
} }

View File

@ -23,7 +23,21 @@ import com.cloud.async.AsyncInstanceCreateStatus;
* @author ahuang * @author ahuang
* *
*/ */
public interface IngressRule { public interface SecurityRule {
public static class SecurityRuleType {
public static final SecurityRuleType IngressRule = new SecurityRuleType("ingress");
public static final SecurityRuleType EgressRule = new SecurityRuleType("egress");
public SecurityRuleType(String type) {
this._type = type;
}
public String getType(){
return _type;
}
private String _type;
}
long getId(); long getId();
long getSecurityGroupId(); long getSecurityGroupId();
@ -32,8 +46,14 @@ public interface IngressRule {
int getEndPort(); int getEndPort();
String getType();
SecurityRuleType getRuleType();
String getProtocol(); String getProtocol();
String getUuid();
AsyncInstanceCreateStatus getCreateStatus(); AsyncInstanceCreateStatus getCreateStatus();
Long getAllowedNetworkId(); Long getAllowedNetworkId();

View File

@ -224,6 +224,8 @@ createSecurityGroup=com.cloud.api.commands.CreateSecurityGroupCmd;15
deleteSecurityGroup=com.cloud.api.commands.DeleteSecurityGroupCmd;15 deleteSecurityGroup=com.cloud.api.commands.DeleteSecurityGroupCmd;15
authorizeSecurityGroupIngress=com.cloud.api.commands.AuthorizeSecurityGroupIngressCmd;15 authorizeSecurityGroupIngress=com.cloud.api.commands.AuthorizeSecurityGroupIngressCmd;15
revokeSecurityGroupIngress=com.cloud.api.commands.RevokeSecurityGroupIngressCmd;15 revokeSecurityGroupIngress=com.cloud.api.commands.RevokeSecurityGroupIngressCmd;15
authorizeSecurityGroupEgress=com.cloud.api.commands.AuthorizeSecurityGroupEgressCmd;15
revokeSecurityGroupEgress=com.cloud.api.commands.RevokeSecurityGroupEgressCmd;15
listSecurityGroups=com.cloud.api.commands.ListSecurityGroupsCmd;15 listSecurityGroups=com.cloud.api.commands.ListSecurityGroupsCmd;15
#### vm group commands #### vm group commands

View File

@ -113,10 +113,8 @@ import com.cloud.agent.api.ReadyCommand;
import com.cloud.agent.api.RebootAnswer; import com.cloud.agent.api.RebootAnswer;
import com.cloud.agent.api.RebootCommand; import com.cloud.agent.api.RebootCommand;
import com.cloud.agent.api.RebootRouterCommand; import com.cloud.agent.api.RebootRouterCommand;
import com.cloud.agent.api.SecurityEgressRuleAnswer; import com.cloud.agent.api.SecurityGroupRuleAnswer;
import com.cloud.agent.api.SecurityEgressRulesCmd; import com.cloud.agent.api.SecurityGroupRulesCmd;
import com.cloud.agent.api.SecurityIngressRuleAnswer;
import com.cloud.agent.api.SecurityIngressRulesCmd;
import com.cloud.agent.api.SetupAnswer; import com.cloud.agent.api.SetupAnswer;
import com.cloud.agent.api.SetupCommand; import com.cloud.agent.api.SetupCommand;
import com.cloud.agent.api.StartAnswer; import com.cloud.agent.api.StartAnswer;
@ -477,8 +475,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
return execute((VpnUsersCfgCommand)cmd); return execute((VpnUsersCfgCommand)cmd);
} else if (clazz == CheckSshCommand.class) { } else if (clazz == CheckSshCommand.class) {
return execute((CheckSshCommand)cmd); return execute((CheckSshCommand)cmd);
} else if (clazz == SecurityIngressRulesCmd.class) { } else if (clazz == SecurityGroupRulesCmd.class) {
return execute((SecurityIngressRulesCmd) cmd); return execute((SecurityGroupRulesCmd) cmd);
} else if (clazz == OvsCreateGreTunnelCommand.class) { } else if (clazz == OvsCreateGreTunnelCommand.class) {
return execute((OvsCreateGreTunnelCommand)cmd); return execute((OvsCreateGreTunnelCommand)cmd);
} else if (clazz == OvsSetTagAndFlowCommand.class) { } else if (clazz == OvsSetTagAndFlowCommand.class) {
@ -4679,37 +4677,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
return new OvsCreateGreTunnelAnswer(cmd, false, "EXCEPTION", _host.ip, bridge); return new OvsCreateGreTunnelAnswer(cmd, false, "EXCEPTION", _host.ip, bridge);
} }
private Answer execute(SecurityEgressRulesCmd cmd) { private Answer execute(SecurityGroupRulesCmd cmd) {
Connection conn = getConnection();
if (s_logger.isTraceEnabled()) {
s_logger.trace("Sending network rules command to " + _host.ip);
}
if (!_canBridgeFirewall) {
s_logger.info("Host " + _host.ip + " cannot do bridge firewalling");
return new SecurityEgressRuleAnswer(cmd, false, "Host " + _host.ip + " cannot do bridge firewalling");
}
String result = callHostPlugin(conn, "vmops", "network_rules",
"vmName", cmd.getVmName(),
"vmIP", cmd.getGuestIp(),
"vmMAC", cmd.getGuestMac(),
"type", "egress",
"vmID", Long.toString(cmd.getVmId()),
"signature", cmd.getSignature(),
"seqno", Long.toString(cmd.getSeqNum()),
"rules", cmd.stringifyRules());
if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) {
s_logger.warn("Failed to program network rules for vm " + cmd.getVmName());
return new SecurityEgressRuleAnswer(cmd, false, "programming network rules failed");
} else {
s_logger.info("Programmed network rules for vm " + cmd.getVmName() + " guestIp=" + cmd.getGuestIp() + ", numrules=" + cmd.getRuleSet().length);
return new SecurityEgressRuleAnswer(cmd);
}
}
private Answer execute(SecurityIngressRulesCmd cmd) {
Connection conn = getConnection(); Connection conn = getConnection();
if (s_logger.isTraceEnabled()) { if (s_logger.isTraceEnabled()) {
s_logger.trace("Sending network rules command to " + _host.ip); s_logger.trace("Sending network rules command to " + _host.ip);
@ -4717,16 +4685,16 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
if (!_canBridgeFirewall) { if (!_canBridgeFirewall) {
s_logger.warn("Host " + _host.ip + " cannot do bridge firewalling"); s_logger.warn("Host " + _host.ip + " cannot do bridge firewalling");
return new SecurityIngressRuleAnswer(cmd, false, return new SecurityGroupRuleAnswer(cmd, false,
"Host " + _host.ip + " cannot do bridge firewalling", "Host " + _host.ip + " cannot do bridge firewalling",
SecurityIngressRuleAnswer.FailureReason.CANNOT_BRIDGE_FIREWALL); SecurityGroupRuleAnswer.FailureReason.CANNOT_BRIDGE_FIREWALL);
} }
String result = callHostPlugin(conn, "vmops", "network_rules", String result = callHostPlugin(conn, "vmops", "network_rules",
"vmName", cmd.getVmName(), "vmName", cmd.getVmName(),
"vmIP", cmd.getGuestIp(), "vmIP", cmd.getGuestIp(),
"vmMAC", cmd.getGuestMac(), "vmMAC", cmd.getGuestMac(),
"type", "ingress", "type", cmd.getRuleType(),
"vmID", Long.toString(cmd.getVmId()), "vmID", Long.toString(cmd.getVmId()),
"signature", cmd.getSignature(), "signature", cmd.getSignature(),
"seqno", Long.toString(cmd.getSeqNum()), "seqno", Long.toString(cmd.getSeqNum()),
@ -4735,10 +4703,10 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) { if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) {
s_logger.warn("Failed to program network rules for vm " + cmd.getVmName()); s_logger.warn("Failed to program network rules for vm " + cmd.getVmName());
return new SecurityIngressRuleAnswer(cmd, false, "programming network rules failed"); return new SecurityGroupRuleAnswer(cmd, false, "programming network rules failed");
} else { } else {
s_logger.info("Programmed network rules for vm " + cmd.getVmName() + " guestIp=" + cmd.getGuestIp() + ", numrules=" + cmd.getRuleSet().length); s_logger.info("Programmed network rules for vm " + cmd.getVmName() + " guestIp=" + cmd.getGuestIp() + ", numrules=" + cmd.getRuleSet().length);
return new SecurityIngressRuleAnswer(cmd); return new SecurityGroupRuleAnswer(cmd);
} }
} }

View File

@ -1,141 +0,0 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.network.security;
import java.util.UUID;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import com.cloud.api.Identity;
import com.cloud.async.AsyncInstanceCreateStatus;
import com.google.gson.annotations.Expose;
@Entity
@Table(name = ("security_egress_rule"))
public class EgressRuleVO implements EgressRule, Identity {
@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)
private Long allowedNetworkId = null;
@Column(name = "allowed_ip_cidr", nullable = true)
private String allowedDestinationIpCidr = null;
@Expose
@Column(name = "create_status", updatable = true, nullable = false)
@Enumerated(value = EnumType.STRING)
private AsyncInstanceCreateStatus createStatus;
@Column(name = "uuid")
private String uuid = UUID.randomUUID().toString();
public EgressRuleVO() {
}
public EgressRuleVO(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 EgressRuleVO(long securityGroupId, int fromPort, int toPort, String protocol, String allowedIpCidr) {
this.securityGroupId = securityGroupId;
this.startPort = fromPort;
this.endPort = toPort;
this.protocol = protocol;
this.allowedDestinationIpCidr = 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;
}
@Override
public Long getAllowedNetworkId() {
return allowedNetworkId;
}
@Override
public String getAllowedDestinationIpCidr() {
return allowedDestinationIpCidr;
}
@Override
public String getUuid() {
return this.uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
}

View File

@ -34,8 +34,8 @@ import com.cloud.async.AsyncInstanceCreateStatus;
import com.google.gson.annotations.Expose; import com.google.gson.annotations.Expose;
@Entity @Entity
@Table(name = ("security_ingress_rule")) @Table(name = ("security_group_rule"))
public class IngressRuleVO implements IngressRule, Identity { public class SecurityGroupRuleVO implements SecurityRule {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id") @Column(name = "id")
@ -50,6 +50,9 @@ public class IngressRuleVO implements IngressRule, Identity {
@Column(name = "end_port") @Column(name = "end_port")
private int endPort; private int endPort;
@Column(name = "type")
private String type;
@Column(name = "protocol") @Column(name = "protocol")
private String protocol; private String protocol;
@ -67,26 +70,38 @@ public class IngressRuleVO implements IngressRule, Identity {
@Column(name = "uuid") @Column(name = "uuid")
private String uuid; private String uuid;
public IngressRuleVO() { public SecurityGroupRuleVO() {
this.uuid = UUID.randomUUID().toString(); this.uuid = UUID.randomUUID().toString();
} }
public IngressRuleVO(long securityGroupId, int fromPort, int toPort, String protocol, long allowedNetworkId) { public SecurityGroupRuleVO(SecurityRuleType type,long securityGroupId, int fromPort, int toPort, String protocol, long allowedNetworkId ) {
this.securityGroupId = securityGroupId; this.securityGroupId = securityGroupId;
this.startPort = fromPort; this.startPort = fromPort;
this.endPort = toPort; this.endPort = toPort;
this.protocol = protocol; this.protocol = protocol;
this.allowedNetworkId = allowedNetworkId; this.allowedNetworkId = allowedNetworkId;
this.uuid = UUID.randomUUID().toString(); this.uuid = UUID.randomUUID().toString();
if (type == SecurityRuleType.IngressRule)
{
this.type = SecurityRuleType.IngressRule.getType();
}else{
this.type = SecurityRuleType.EgressRule.getType();
}
} }
public IngressRuleVO(long securityGroupId, int fromPort, int toPort, String protocol, String allowedIpCidr) { public SecurityGroupRuleVO(SecurityRuleType type,long securityGroupId, int fromPort, int toPort, String protocol, String allowedIpCidr) {
this.securityGroupId = securityGroupId; this.securityGroupId = securityGroupId;
this.startPort = fromPort; this.startPort = fromPort;
this.endPort = toPort; this.endPort = toPort;
this.protocol = protocol; this.protocol = protocol;
this.allowedSourceIpCidr = allowedIpCidr; this.allowedSourceIpCidr = allowedIpCidr;
this.uuid = UUID.randomUUID().toString(); this.uuid = UUID.randomUUID().toString();
if (type == SecurityRuleType.IngressRule)
{
this.type = SecurityRuleType.IngressRule.getType();
}else{
this.type = SecurityRuleType.EgressRule.getType();
}
} }
@Override @Override
@ -94,11 +109,23 @@ public class IngressRuleVO implements IngressRule, Identity {
return id; return id;
} }
@Override
public String getType() {
return type;
}
@Override @Override
public long getSecurityGroupId() { public long getSecurityGroupId() {
return securityGroupId; return securityGroupId;
} }
public SecurityRuleType getRuleType() {
if ("ingress".equalsIgnoreCase(this.type))
return SecurityRuleType.IngressRule;
else
return SecurityRuleType.EgressRule;
}
@Override @Override
public int getStartPort() { public int getStartPort() {
return startPort; return startPort;

View File

@ -26,10 +26,11 @@ import javax.persistence.Id;
import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.SecondaryTable; import javax.persistence.SecondaryTable;
import javax.persistence.Table; import javax.persistence.Table;
import com.cloud.network.security.SecurityRule.SecurityRuleType;
@Entity @Entity
@Table(name = ("security_group")) @Table(name = ("security_group"))
@SecondaryTable(name = "security_ingress_rule", join = "left", pkJoinColumns = { @PrimaryKeyJoinColumn(name = "id", referencedColumnName = "security_group_id") }) @SecondaryTable(name = "security_group_rule", join = "left", pkJoinColumns = { @PrimaryKeyJoinColumn(name = "id", referencedColumnName = "security_group_id") })
public class SecurityGroupRulesVO implements SecurityGroupRules { public class SecurityGroupRulesVO implements SecurityGroupRules {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@ -48,22 +49,25 @@ public class SecurityGroupRulesVO implements SecurityGroupRules {
@Column(name = "account_id") @Column(name = "account_id")
private Long accountId; private Long accountId;
@Column(name = "id", table = "security_ingress_rule", insertable = false, updatable = false) @Column(name = "id", table = "security_group_rule", insertable = false, updatable = false)
private Long ruleId; private Long ruleId;
@Column(name = "start_port", table = "security_ingress_rule", insertable = false, updatable = false) @Column(name = "start_port", table = "security_group_rule", insertable = false, updatable = false)
private int startPort; private int startPort;
@Column(name = "end_port", table = "security_ingress_rule", insertable = false, updatable = false) @Column(name = "end_port", table = "security_group_rule", insertable = false, updatable = false)
private int endPort; private int endPort;
@Column(name = "protocol", table = "security_ingress_rule", insertable = false, updatable = false) @Column(name = "protocol", table = "security_group_rule", insertable = false, updatable = false)
private String protocol; private String protocol;
@Column(name = "allowed_network_id", table = "security_ingress_rule", insertable = false, updatable = false, nullable = true) @Column(name = "type", table = "security_group_rule", insertable = false, updatable = false)
private String type;
@Column(name = "allowed_network_id", table = "security_group_rule", insertable = false, updatable = false, nullable = true)
private Long allowedNetworkId = null; private Long allowedNetworkId = null;
@Column(name = "allowed_ip_cidr", table = "security_ingress_rule", insertable = false, updatable = false, nullable = true) @Column(name = "allowed_ip_cidr", table = "security_group_rule", insertable = false, updatable = false, nullable = true)
private String allowedSourceIpCidr = null; private String allowedSourceIpCidr = null;
public SecurityGroupRulesVO() { public SecurityGroupRulesVO() {
@ -129,6 +133,15 @@ public class SecurityGroupRulesVO implements SecurityGroupRules {
return protocol; return protocol;
} }
@Override
public SecurityRuleType getRuleType() {
if ("ingress".equalsIgnoreCase(this.type)) {
return SecurityRuleType.IngressRule;
} else {
return SecurityRuleType.EgressRule;
}
}
@Override @Override
public Long getAllowedNetworkId() { public Long getAllowedNetworkId() {
return allowedNetworkId; return allowedNetworkId;

View File

@ -55,8 +55,8 @@ import com.cloud.agent.api.ReadyAnswer;
import com.cloud.agent.api.ReadyCommand; import com.cloud.agent.api.ReadyCommand;
import com.cloud.agent.api.RebootAnswer; import com.cloud.agent.api.RebootAnswer;
import com.cloud.agent.api.RebootCommand; import com.cloud.agent.api.RebootCommand;
import com.cloud.agent.api.SecurityIngressRuleAnswer; import com.cloud.agent.api.SecurityGroupRuleAnswer;
import com.cloud.agent.api.SecurityIngressRulesCmd; import com.cloud.agent.api.SecurityGroupRulesCmd;
import com.cloud.agent.api.StartAnswer; import com.cloud.agent.api.StartAnswer;
import com.cloud.agent.api.StartCommand; import com.cloud.agent.api.StartCommand;
import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupCommand;
@ -1045,7 +1045,7 @@ public class OvmResourceBase implements ServerResource, HypervisorResource {
} }
} }
private Answer execute(SecurityIngressRulesCmd cmd) { private Answer execute(SecurityGroupRulesCmd cmd) {
boolean result = false; boolean result = false;
try { try {
OvmVif.Details vif = getVifFromVm(cmd.getVmName(), null); OvmVif.Details vif = getVifFromVm(cmd.getVmName(), null);
@ -1059,10 +1059,10 @@ public class OvmResourceBase implements ServerResource, HypervisorResource {
if (!result) { if (!result) {
s_logger.warn("Failed to program network rules for vm " + cmd.getVmName()); s_logger.warn("Failed to program network rules for vm " + cmd.getVmName());
return new SecurityIngressRuleAnswer(cmd, false, "programming network rules failed"); return new SecurityGroupRuleAnswer(cmd, false, "programming network rules failed");
} else { } else {
s_logger.info("Programmed network rules for vm " + cmd.getVmName() + " guestIp=" + cmd.getGuestIp() + ", numrules=" + cmd.getRuleSet().length); s_logger.info("Programmed network rules for vm " + cmd.getVmName() + " guestIp=" + cmd.getGuestIp() + ", numrules=" + cmd.getRuleSet().length);
return new SecurityIngressRuleAnswer(cmd); return new SecurityGroupRuleAnswer(cmd);
} }
} }
@ -1270,8 +1270,8 @@ public class OvmResourceBase implements ServerResource, HypervisorResource {
return execute((FenceCommand)cmd); return execute((FenceCommand)cmd);
} else if (clazz == AttachIsoCommand.class) { } else if (clazz == AttachIsoCommand.class) {
return execute((AttachIsoCommand)cmd); return execute((AttachIsoCommand)cmd);
} else if (clazz == SecurityIngressRulesCmd.class) { } else if (clazz == SecurityGroupRulesCmd.class) {
return execute((SecurityIngressRulesCmd) cmd); return execute((SecurityGroupRulesCmd) cmd);
} else if (clazz == CleanupNetworkRulesCmd.class) { } else if (clazz == CleanupNetworkRulesCmd.class) {
return execute((CleanupNetworkRulesCmd) cmd); return execute((CleanupNetworkRulesCmd) cmd);
} else if (clazz == PrepareOCFS2NodesCommand.class) { } else if (clazz == PrepareOCFS2NodesCommand.class) {

View File

@ -476,6 +476,7 @@ def ipset(ipsetname, proto, start, end, ips):
def destroy_network_rules_for_vm(session, args): def destroy_network_rules_for_vm(session, args):
vm_name = args.pop('vmName') vm_name = args.pop('vmName')
vmchain = chain_name(vm_name) vmchain = chain_name(vm_name)
vmchain_egress = chain_name(vm_name) + "-eg"
vmchain_default = chain_name_def(vm_name) vmchain_default = chain_name_def(vm_name)
delete_rules_for_vm_in_bridge_firewall_chain(vm_name) delete_rules_for_vm_in_bridge_firewall_chain(vm_name)
@ -492,9 +493,14 @@ def destroy_network_rules_for_vm(session, args):
util.pread2(['iptables', '-F', vmchain]) util.pread2(['iptables', '-F', vmchain])
util.pread2(['iptables', '-X', vmchain]) util.pread2(['iptables', '-X', vmchain])
except: except:
util.SMlog("Ignoring failure to delete chain " + vmchain) util.SMlog("Ignoring failure to delete ingress chain " + vmchain)
try:
util.pread2(['iptables', '-F', vmchain_egress])
util.pread2(['iptables', '-X', vmchain_egress])
except:
util.SMlog("Ignoring failure to delete egress chain " + vmchain_egress)
remove_rule_log_for_vm(vm_name) remove_rule_log_for_vm(vm_name)
@ -671,6 +677,7 @@ def default_network_rules(session, args):
vmchain = chain_name(vm_name) vmchain = chain_name(vm_name)
vmchain_egress = chain_name(vm_name) +"-eg"
vmchain_default = chain_name_def(vm_name) vmchain_default = chain_name_def(vm_name)
destroy_ebtables_rules(vmchain) destroy_ebtables_rules(vmchain)
@ -681,6 +688,11 @@ def default_network_rules(session, args):
except: except:
util.pread2(['iptables', '-F', vmchain]) util.pread2(['iptables', '-F', vmchain])
try:
util.pread2(['iptables', '-N', vmchain_egress])
except:
util.pread2(['iptables', '-F', vmchain_egress])
try: try:
util.pread2(['iptables', '-N', vmchain_default]) util.pread2(['iptables', '-N', vmchain_default])
except: except:
@ -698,7 +710,8 @@ def default_network_rules(session, args):
#don't let vm spoof its ip address #don't let vm spoof its ip address
for v in vifs: for v in vifs:
util.pread2(['iptables', '-A', vmchain_default, '-m', 'physdev', '--physdev-is-bridged', '--physdev-in', v, '--source', vm_ip, '-j', 'RETURN']) util.pread2(['iptables', '-A', vmchain_default, '-m', 'physdev', '--physdev-is-bridged', '--physdev-in', v, '--source', vm_ip,'-p', 'udp', '--dport', '53', '-j', 'RETURN'])
util.pread2(['iptables', '-A', vmchain_default, '-m', 'physdev', '--physdev-is-bridged', '--physdev-in', v, '--source', vm_ip, '-j', vmchain_egress])
util.pread2(['iptables', '-A', vmchain_default, '-j', vmchain]) util.pread2(['iptables', '-A', vmchain_default, '-j', vmchain])
except: except:
util.SMlog("Failed to program default rules for vm " + vm_name) util.SMlog("Failed to program default rules for vm " + vm_name)
@ -900,7 +913,7 @@ def cleanup_rules(session, args):
instance = 'VM' instance = 'VM'
try: try:
chainscmd = "iptables-save | grep '^:' | awk '{print $1}' | cut -d':' -f2 | sed 's/-def/-%s/'|sort|uniq" % instance chainscmd = "iptables-save | grep '^:' | awk '{print $1}' | cut -d':' -f2 | sed 's/-def/-%s/' | sed 's/-eg//' |sort|uniq" % instance
chains = util.pread2(['/bin/bash', '-c', chainscmd]).split('\n') chains = util.pread2(['/bin/bash', '-c', chainscmd]).split('\n')
cleaned = 0 cleaned = 0
cleanup = [] cleanup = []
@ -1026,6 +1039,7 @@ def network_rules(session, args):
vm_name = args.get('vmName') vm_name = args.get('vmName')
vm_ip = args.get('vmIP') vm_ip = args.get('vmIP')
vm_id = args.get('vmID') vm_id = args.get('vmID')
type = args.get('type')
signature = args.pop('signature') signature = args.pop('signature')
seqno = args.pop('seqno') seqno = args.pop('seqno')
deflated = 'false' deflated = 'false'
@ -1055,7 +1069,14 @@ def network_rules(session, args):
except: except:
pass pass
vmchain = chain_name(vm_name) if type == 'egress':
vmchain = chain_name(vm_name) + "-eg"
direction = "dst"
action = "RETURN"
else:
vmchain = chain_name(vm_name)
direction = "src"
action = "ACCEPT"
reason = 'seqno_change_or_sig_change' reason = 'seqno_change_or_sig_change'
[reprogramDefault, reprogramChain, rewriteLog] = \ [reprogramDefault, reprogramChain, rewriteLog] = \
check_rule_log_for_vm (vm_name, vm_id, vm_ip, domid, signature, seqno) check_rule_log_for_vm (vm_name, vm_id, vm_ip, domid, signature, seqno)
@ -1114,32 +1135,39 @@ def network_rules(session, args):
util.SMlog(" failed to create ipset for rule " + str(tokens)) util.SMlog(" failed to create ipset for rule " + str(tokens))
if protocol == 'all': if protocol == 'all':
iptables = ['iptables', '-I', vmchain, '-m', 'state', '--state', 'NEW', '-m', 'set', '--match-set', ipsetname, 'src', '-j', 'ACCEPT'] iptables = ['iptables', '-I', vmchain, '-m', 'state', '--state', 'NEW', '-m', 'set', '--match-set', ipsetname, direction, '-j', action]
elif protocol != 'icmp': elif protocol != 'icmp':
iptables = ['iptables', '-I', vmchain, '-p', protocol, '-m', protocol, '--dport', range, '-m', 'state', '--state', 'NEW', '-m', 'set', '--match-set', ipsetname, 'src', '-j', 'ACCEPT'] iptables = ['iptables', '-I', vmchain, '-p', protocol, '-m', protocol, '--dport', range, '-m', 'state', '--state', 'NEW', '-m', 'set', '--match-set', ipsetname, direction, '-j', action]
else: else:
range = start + "/" + end range = start + "/" + end
if start == "-1": if start == "-1":
range = "any" range = "any"
iptables = ['iptables', '-I', vmchain, '-p', 'icmp', '--icmp-type', range, '-m', 'set', '--match-set', ipsetname, 'src', '-j', 'ACCEPT'] iptables = ['iptables', '-I', vmchain, '-p', 'icmp', '--icmp-type', range, '-m', 'set', '--match-set', ipsetname, direction, '-j', action]
cmds.append(iptables) cmds.append(iptables)
util.SMlog(iptables) util.SMlog(iptables)
if allow_any and protocol != 'all': if allow_any and protocol != 'all':
if protocol != 'icmp': if protocol != 'icmp':
iptables = ['iptables', '-I', vmchain, '-p', protocol, '-m', protocol, '--dport', range, '-m', 'state', '--state', 'NEW', '-j', 'ACCEPT'] iptables = ['iptables', '-I', vmchain, '-p', protocol, '-m', protocol, '--dport', range, '-m', 'state', '--state', 'NEW', '-j', action]
else: else:
range = start + "/" + end range = start + "/" + end
if start == "-1": if start == "-1":
range = "any" range = "any"
iptables = ['iptables', '-I', vmchain, '-p', 'icmp', '--icmp-type', range, '-j', 'ACCEPT'] iptables = ['iptables', '-I', vmchain, '-p', 'icmp', '--icmp-type', range, '-j', action]
cmds.append(iptables) cmds.append(iptables)
util.SMlog(iptables) util.SMlog(iptables)
util.pread2(['iptables', '-F', vmchain]) util.pread2(['iptables', '-F', vmchain])
for cmd in cmds: for cmd in cmds:
util.pread2(cmd) util.pread2(cmd)
util.pread2(['iptables', '-A', vmchain, '-j', 'DROP'])
if type == 'egress':
if len(cmds) == 0 :
util.pread2(['iptables', '-A', vmchain, '-j', 'RETURN'])
else:
util.pread2(['iptables', '-A', vmchain, '-j', 'DROP'])
else:
util.pread2(['iptables', '-A', vmchain, '-j', 'DROP'])
if write_rule_log_for_vm(vm_name, vm_id, vm_ip, domid, signature, seqno) == False: if write_rule_log_for_vm(vm_name, vm_id, vm_ip, domid, signature, seqno) == False:
return 'false' return 'false'

View File

@ -82,6 +82,7 @@ def ipset(ipsetname, proto, start, end, ips):
def destroy_network_rules_for_vm(vm_name, vif=None): def destroy_network_rules_for_vm(vm_name, vif=None):
vmchain = vm_name vmchain = vm_name
vmchain_egress = vm_name + "-eg"
vmchain_default = None vmchain_default = None
delete_rules_for_vm_in_bridge_firewall_chain(vm_name) delete_rules_for_vm_in_bridge_firewall_chain(vm_name)
@ -112,6 +113,18 @@ def destroy_network_rules_for_vm(vm_name, vif=None):
except: except:
logging.debug("Ignoring failure to delete chain " + vmchain) logging.debug("Ignoring failure to delete chain " + vmchain)
try:
execute("iptables -F " + vmchain_egress)
except:
logging.debug("Ignoring failure to delete chain " + vmchain_egress)
try:
execute("iptables -X " + vmchain_egress)
except:
logging.debug("Ignoring failure to delete chain " + vmchain_egress)
if vif is not None: if vif is not None:
try: try:
dnats = execute("iptables -t nat -S | grep " + vif + " | sed 's/-A/-D/'").split("\n") dnats = execute("iptables -t nat -S | grep " + vif + " | sed 's/-A/-D/'").split("\n")
@ -246,6 +259,7 @@ def default_network_rules(vm_name, vm_id, vm_ip, vm_mac, vif, brname):
domID = getvmId(vm_name) domID = getvmId(vm_name)
delete_rules_for_vm_in_bridge_firewall_chain(vmName) delete_rules_for_vm_in_bridge_firewall_chain(vmName)
vmchain = vm_name vmchain = vm_name
vmchain_egress = vm_name +"-eg"
vmchain_default = '-'.join(vmchain.split('-')[:-1]) + "-def" vmchain_default = '-'.join(vmchain.split('-')[:-1]) + "-def"
destroy_ebtables_rules(vmName, vif) destroy_ebtables_rules(vmName, vif)
@ -255,6 +269,11 @@ def default_network_rules(vm_name, vm_id, vm_ip, vm_mac, vif, brname):
except: except:
execute("iptables -F " + vmchain) execute("iptables -F " + vmchain)
try:
execute("iptables -N " + vmchain_egress)
except:
execute("iptables -F " + vmchain_egress)
try: try:
execute("iptables -N " + vmchain_default) execute("iptables -N " + vmchain_default)
except: except:
@ -270,7 +289,8 @@ def default_network_rules(vm_name, vm_id, vm_ip, vm_mac, vif, brname):
#don't let vm spoof its ip address #don't let vm spoof its ip address
if vm_ip is not None: if vm_ip is not None:
execute("iptables -A " + vmchain_default + " -m physdev --physdev-is-bridged --physdev-in " + vif + " --source " + vm_ip + " -j ACCEPT") execute("iptables -A " + vmchain_default + " -m physdev --physdev-is-bridged --physdev-in " + vif + " --source " + vm_ip + " -p udp --dport 57 -j RETURN ")
execute("iptables -A " + vmchain_default + " -m physdev --physdev-is-bridged --physdev-in " + vif + " --source " + vm_ip + " -j " + vmchain_egress)
execute("iptables -A " + vmchain_default + " -j " + vmchain) execute("iptables -A " + vmchain_default + " -j " + vmchain)
execute("iptables -A " + vmchain + " -j DROP") execute("iptables -A " + vmchain + " -j DROP")
except: except:
@ -468,7 +488,7 @@ def cleanup_rules_for_dead_vms():
def cleanup_rules(): def cleanup_rules():
try: try:
chainscmd = "iptables-save | grep '^:' | grep -v '.*-def' | awk '{print $1}' | cut -d':' -f2" chainscmd = "iptables-save | grep '^:' | grep -v '.*-def' | grep -v '.*-eg' | awk '{print $1}' | cut -d':' -f2"
chains = execute(chainscmd).split('\n') chains = execute(chainscmd).split('\n')
cleaned = 0 cleaned = 0
cleanup = [] cleanup = []
@ -552,11 +572,20 @@ def remove_rule_log_for_vm(vmName):
return result return result
def add_network_rules(vm_name, vm_id, vm_ip, signature, seqno, vmMac, rules, vif, brname): def add_network_rules(vm_name, vm_id, vm_ip, signature, seqno, vmMac, rules, vif, brname,ruletype):
try: try:
vmName = vm_name vmName = vm_name
domId = getvmId(vmName) domId = getvmId(vmName)
vmchain = vm_name
if ruletype == 'egress':
vmchain = vm_name + "-eg"
direction = "-d"
action = "RETURN"
else:
vmchain = vm_name
direction = "-s"
action = "ACCEPT"
changes = [] changes = []
changes = check_rule_log_for_vm(vmName, vm_id, vm_ip, domId, signature, seqno) changes = check_rule_log_for_vm(vmName, vm_id, vm_ip, domId, signature, seqno)
@ -596,28 +625,35 @@ def add_network_rules(vm_name, vm_id, vm_ip, signature, seqno, vmMac, rules, vif
if ips: if ips:
if protocol == 'all': if protocol == 'all':
for ip in ips: for ip in ips:
execute("iptables -I " + vmchain + " -m state --state NEW -s " + ip + " -j ACCEPT") execute("iptables -I " + vmchain + " -m state --state NEW " + direction + " " + ip + " -j "+action)
elif protocol != 'icmp': elif protocol != 'icmp':
for ip in ips: for ip in ips:
execute("iptables -I " + vmchain + " -p " + protocol + " -m " + protocol + " --dport " + range + " -m state --state NEW -s " + ip + " -j ACCEPT") execute("iptables -I " + vmchain + " -p " + protocol + " -m " + protocol + " --dport " + range + " -m state --state NEW " + direction + " " + ip + " -j "+action)
else: else:
range = start + "/" + end range = start + "/" + end
if start == "-1": if start == "-1":
range = "any" range = "any"
for ip in ips: for ip in ips:
execute("iptables -I " + vmchain + " -p icmp --icmp-type " + range + " -s " + ip + " -j ACCEPT") execute("iptables -I " + vmchain + " -p icmp --icmp-type " + range + " " + direction + " " + ip + " -j "+action)
if allow_any and protocol != 'all': if allow_any and protocol != 'all':
if protocol != 'icmp': if protocol != 'icmp':
execute("iptables -I " + vmchain + " -p " + protocol + " -m " + protocol + " --dport " + range + " -m state --state NEW -j ACCEPT") execute("iptables -I " + vmchain + " -p " + protocol + " -m " + protocol + " --dport " + range + " -m state --state NEW -j "+action)
else: else:
range = start + "/" + end range = start + "/" + end
if start == "-1": if start == "-1":
range = "any" range = "any"
execute("iptables -I " + vmchain + " -p icmp --icmp-type " + range + " -j ACCEPT") execute("iptables -I " + vmchain + " -p icmp --icmp-type " + range + " -j "+action)
if ruletype == 'egress':
iptables = "iptables -A " + vmchain + " -j DROP" if len(lines) == 0 :
execute(iptables) iptables = "iptables -A " + vmchain + " -j RETURN"
execute(iptables)
else:
iptables = "iptables -A " + vmchain + " -j DROP"
execute(iptables)
else:
iptables = "iptables -A " + vmchain + " -j DROP"
execute(iptables)
if write_rule_log_for_vm(vmName, vm_id, vm_ip, domId, signature, seqno) == False: if write_rule_log_for_vm(vmName, vm_id, vm_ip, domId, signature, seqno) == False:
return 'false' return 'false'
@ -704,6 +740,7 @@ if __name__ == '__main__':
parser.add_option("--vmid", dest="vmID") parser.add_option("--vmid", dest="vmID")
parser.add_option("--vmmac", dest="vmMAC") parser.add_option("--vmmac", dest="vmMAC")
parser.add_option("--vif", dest="vif") parser.add_option("--vif", dest="vif")
parser.add_option("--ruletype", dest="ruletype")
parser.add_option("--sig", dest="sig") parser.add_option("--sig", dest="sig")
parser.add_option("--seq", dest="seq") parser.add_option("--seq", dest="seq")
parser.add_option("--rules", dest="rules") parser.add_option("--rules", dest="rules")
@ -724,7 +761,7 @@ if __name__ == '__main__':
elif cmd == "get_rule_logs_for_vms": elif cmd == "get_rule_logs_for_vms":
get_rule_logs_for_vms() get_rule_logs_for_vms()
elif cmd == "add_network_rules": elif cmd == "add_network_rules":
add_network_rules(option.vmName, option.vmID, option.vmIP, option.sig, option.seq, option.vmMAC, option.rules, option.vif, option.brname) add_network_rules(option.vmName, option.vmID, option.vmIP, option.sig, option.seq, option.vmMAC, option.rules, option.vif, option.brname,option.ruletype)
elif cmd == "cleanup_rules": elif cmd == "cleanup_rules":
cleanup_rules() cleanup_rules()
elif cmd == "post_default_network_rules": elif cmd == "post_default_network_rules":

View File

@ -45,7 +45,6 @@ import com.cloud.api.response.CreateCmdResponse;
import com.cloud.api.response.DiskOfferingResponse; import com.cloud.api.response.DiskOfferingResponse;
import com.cloud.api.response.DomainResponse; import com.cloud.api.response.DomainResponse;
import com.cloud.api.response.DomainRouterResponse; import com.cloud.api.response.DomainRouterResponse;
import com.cloud.api.response.EgressRuleResponse;
import com.cloud.api.response.EventResponse; import com.cloud.api.response.EventResponse;
import com.cloud.api.response.ExtractResponse; import com.cloud.api.response.ExtractResponse;
import com.cloud.api.response.FirewallResponse; import com.cloud.api.response.FirewallResponse;
@ -53,8 +52,8 @@ import com.cloud.api.response.FirewallRuleResponse;
import com.cloud.api.response.HostResponse; import com.cloud.api.response.HostResponse;
import com.cloud.api.response.HypervisorCapabilitiesResponse; import com.cloud.api.response.HypervisorCapabilitiesResponse;
import com.cloud.api.response.IPAddressResponse; import com.cloud.api.response.IPAddressResponse;
import com.cloud.api.response.IngressRuleResponse; import com.cloud.api.response.SecurityGroupResponse;
import com.cloud.api.response.IngressRuleResultObject; import com.cloud.api.response.SecurityGroupResultObject;
import com.cloud.api.response.InstanceGroupResponse; import com.cloud.api.response.InstanceGroupResponse;
import com.cloud.api.response.IpForwardingRuleResponse; import com.cloud.api.response.IpForwardingRuleResponse;
import com.cloud.api.response.ListResponse; import com.cloud.api.response.ListResponse;
@ -127,8 +126,8 @@ import com.cloud.network.rules.FirewallRule;
import com.cloud.network.rules.LoadBalancer; import com.cloud.network.rules.LoadBalancer;
import com.cloud.network.rules.PortForwardingRule; import com.cloud.network.rules.PortForwardingRule;
import com.cloud.network.rules.StaticNatRule; import com.cloud.network.rules.StaticNatRule;
import com.cloud.network.security.EgressRule; import com.cloud.network.security.SecurityRule;
import com.cloud.network.security.IngressRule; import com.cloud.network.security.SecurityRule.SecurityRuleType;
import com.cloud.network.security.SecurityGroup; import com.cloud.network.security.SecurityGroup;
import com.cloud.network.security.SecurityGroupRules; import com.cloud.network.security.SecurityGroupRules;
import com.cloud.offering.DiskOffering; import com.cloud.offering.DiskOffering;
@ -180,6 +179,8 @@ import com.cloud.vm.VmStats;
import com.cloud.vm.dao.UserVmData; import com.cloud.vm.dao.UserVmData;
import com.cloud.vm.dao.UserVmData.NicData; import com.cloud.vm.dao.UserVmData.NicData;
import com.cloud.vm.dao.UserVmData.SecurityGroupData; import com.cloud.vm.dao.UserVmData.SecurityGroupData;
import com.cloud.api.response.SecurityGroupRuleResponse;
import com.cloud.api.response.SecurityGroupRuleResultObject;
public class ApiResponseHelper implements ResponseGenerator { public class ApiResponseHelper implements ResponseGenerator {
@ -1771,8 +1772,10 @@ public class ApiResponseHelper implements ResponseGenerator {
} }
@Override @Override
public ListResponse<SecurityGroupResponse> createSecurityGroupResponses(List<? extends SecurityGroupRules> networkGroups) { public ListResponse<SecurityGroupResponse> createSecurityGroupResponses(
List<SecurityGroupResultObject> groupResultObjs = SecurityGroupResultObject.transposeNetworkGroups(networkGroups); List<? extends SecurityGroupRules> networkGroups) {
List<SecurityGroupResultObject> groupResultObjs = SecurityGroupResultObject
.transposeNetworkGroups(networkGroups);
ListResponse<SecurityGroupResponse> response = new ListResponse<SecurityGroupResponse>(); ListResponse<SecurityGroupResponse> response = new ListResponse<SecurityGroupResponse>();
List<SecurityGroupResponse> netGrpResponses = new ArrayList<SecurityGroupResponse>(); List<SecurityGroupResponse> netGrpResponses = new ArrayList<SecurityGroupResponse>();
@ -1784,34 +1787,46 @@ public class ApiResponseHelper implements ResponseGenerator {
populateOwner(netGrpResponse, networkGroup); populateOwner(netGrpResponse, networkGroup);
List<IngressRuleResultObject> ingressRules = networkGroup.getIngressRules(); List<SecurityGroupRuleResultObject> securityGroupRules = networkGroup
if ((ingressRules != null) && !ingressRules.isEmpty()) { .getSecurityGroupRules();
List<IngressRuleResponse> ingressRulesResponse = new ArrayList<IngressRuleResponse>(); if ((securityGroupRules != null) && !securityGroupRules.isEmpty()) {
List<SecurityGroupRuleResponse> ingressRulesResponse = new ArrayList<SecurityGroupRuleResponse>();
List<SecurityGroupRuleResponse> egressRulesResponse = new ArrayList<SecurityGroupRuleResponse>();
for (SecurityGroupRuleResultObject securityGroupRule : securityGroupRules) {
SecurityGroupRuleResponse ruleData = new SecurityGroupRuleResponse();
ruleData.setRuleId(securityGroupRule.getId());
ruleData.setProtocol(securityGroupRule.getProtocol());
for (IngressRuleResultObject ingressRule : ingressRules) { if ("icmp"
IngressRuleResponse ingressData = new IngressRuleResponse(); .equalsIgnoreCase(securityGroupRule.getProtocol())) {
ruleData.setIcmpType(securityGroupRule.getStartPort());
ingressData.setRuleId(ingressRule.getId()); ruleData.setIcmpCode(securityGroupRule.getEndPort());
ingressData.setProtocol(ingressRule.getProtocol());
if ("icmp".equalsIgnoreCase(ingressRule.getProtocol())) {
ingressData.setIcmpType(ingressRule.getStartPort());
ingressData.setIcmpCode(ingressRule.getEndPort());
} else { } else {
ingressData.setStartPort(ingressRule.getStartPort()); ruleData.setStartPort(securityGroupRule.getStartPort());
ingressData.setEndPort(ingressRule.getEndPort()); ruleData.setEndPort(securityGroupRule.getEndPort());
} }
if (ingressRule.getAllowedSecurityGroup() != null) { if (securityGroupRule.getAllowedSecurityGroup() != null) {
ingressData.setSecurityGroupName(ingressRule.getAllowedSecurityGroup()); ruleData.setSecurityGroupName(securityGroupRule
ingressData.setAccountName(ingressRule.getAllowedSecGroupAcct()); .getAllowedSecurityGroup());
ruleData.setAccountName(securityGroupRule
.getAllowedSecGroupAcct());
} else { } else {
ingressData.setCidr(ingressRule.getAllowedSourceIpCidr()); ruleData.setCidr(securityGroupRule
.getAllowedSourceIpCidr());
} }
ingressData.setObjectName("ingressrule"); if (securityGroupRule.getRuleType() == SecurityRuleType.IngressRule) {
ingressRulesResponse.add(ingressData); ruleData.setObjectName("ingressrule");
ingressRulesResponse.add(ruleData);
} else {
ruleData.setObjectName("egressrule");
egressRulesResponse.add(ruleData);
}
} }
netGrpResponse.setIngressRules(ingressRulesResponse); netGrpResponse
.setSecurityGroupIngressRules(ingressRulesResponse);
netGrpResponse.setSecurityGroupEgressRules(egressRulesResponse);
} }
netGrpResponse.setObjectName("securitygroup"); netGrpResponse.setObjectName("securitygroup");
netGrpResponses.add(netGrpResponse); netGrpResponses.add(netGrpResponse);
@ -2180,14 +2195,14 @@ public class ApiResponseHelper implements ResponseGenerator {
} }
@Override @Override
public SecurityGroupResponse createSecurityGroupResponseFromIngressRule(List<? extends IngressRule> ingressRules) { public SecurityGroupResponse createSecurityGroupResponseFromSecurityGroupRule(List<? extends SecurityRule> securityRules) {
SecurityGroupResponse response = new SecurityGroupResponse(); SecurityGroupResponse response = new SecurityGroupResponse();
Map<Long, Account> securiytGroupAccounts = new HashMap<Long, Account>(); Map<Long, Account> securiytGroupAccounts = new HashMap<Long, Account>();
Map<Long, SecurityGroup> allowedSecurityGroups = new HashMap<Long, SecurityGroup>(); Map<Long, SecurityGroup> allowedSecurityGroups = new HashMap<Long, SecurityGroup>();
Map<Long, Account> allowedSecuriytGroupAccounts = new HashMap<Long, Account>(); Map<Long, Account> allowedSecuriytGroupAccounts = new HashMap<Long, Account>();
if ((ingressRules != null) && !ingressRules.isEmpty()) { if ((securityRules != null) && !securityRules.isEmpty()) {
SecurityGroup securityGroup = ApiDBUtils.findSecurityGroupById(ingressRules.get(0).getSecurityGroupId()); SecurityGroup securityGroup = ApiDBUtils.findSecurityGroupById(securityRules.get(0).getSecurityGroupId());
response.setId(securityGroup.getId()); response.setId(securityGroup.getId());
response.setName(securityGroup.getName()); response.setName(securityGroup.getName());
response.setDescription(securityGroup.getDescription()); response.setDescription(securityGroup.getDescription());
@ -2202,21 +2217,22 @@ public class ApiResponseHelper implements ResponseGenerator {
populateAccount(response, account.getId()); populateAccount(response, account.getId());
populateDomain(response, account.getDomainId()); populateDomain(response, account.getDomainId());
List<IngressRuleResponse> responses = new ArrayList<IngressRuleResponse>(); List<SecurityGroupRuleResponse> egressResponses = new ArrayList<SecurityGroupRuleResponse>();
for (IngressRule ingressRule : ingressRules) { List<SecurityGroupRuleResponse> ingressResponses = new ArrayList<SecurityGroupRuleResponse>();
IngressRuleResponse ingressData = new IngressRuleResponse(); for (SecurityRule securityRule : securityRules) {
SecurityGroupRuleResponse securityGroupData = new SecurityGroupRuleResponse();
ingressData.setRuleId(ingressRule.getId()); securityGroupData.setRuleId(securityRule.getId());
ingressData.setProtocol(ingressRule.getProtocol()); securityGroupData.setProtocol(securityRule.getProtocol());
if ("icmp".equalsIgnoreCase(ingressRule.getProtocol())) { if ("icmp".equalsIgnoreCase(securityRule.getProtocol())) {
ingressData.setIcmpType(ingressRule.getStartPort()); securityGroupData.setIcmpType(securityRule.getStartPort());
ingressData.setIcmpCode(ingressRule.getEndPort()); securityGroupData.setIcmpCode(securityRule.getEndPort());
} else { } else {
ingressData.setStartPort(ingressRule.getStartPort()); securityGroupData.setStartPort(securityRule.getStartPort());
ingressData.setEndPort(ingressRule.getEndPort()); securityGroupData.setEndPort(securityRule.getEndPort());
} }
Long allowedSecurityGroupId = ingressRule.getAllowedNetworkId(); Long allowedSecurityGroupId = securityRule.getAllowedNetworkId();
if (allowedSecurityGroupId != null) { if (allowedSecurityGroupId != null) {
SecurityGroup allowedSecurityGroup = allowedSecurityGroups.get(allowedSecurityGroupId); SecurityGroup allowedSecurityGroup = allowedSecurityGroups.get(allowedSecurityGroupId);
if (allowedSecurityGroup == null) { if (allowedSecurityGroup == null) {
@ -2224,7 +2240,7 @@ public class ApiResponseHelper implements ResponseGenerator {
allowedSecurityGroups.put(allowedSecurityGroupId, allowedSecurityGroup); allowedSecurityGroups.put(allowedSecurityGroupId, allowedSecurityGroup);
} }
ingressData.setSecurityGroupName(allowedSecurityGroup.getName()); securityGroupData.setSecurityGroupName(allowedSecurityGroup.getName());
Account allowedAccount = allowedSecuriytGroupAccounts.get(allowedSecurityGroup.getAccountId()); Account allowedAccount = allowedSecuriytGroupAccounts.get(allowedSecurityGroup.getAccountId());
if (allowedAccount == null) { if (allowedAccount == null) {
@ -2232,84 +2248,21 @@ public class ApiResponseHelper implements ResponseGenerator {
allowedSecuriytGroupAccounts.put(allowedAccount.getId(), allowedAccount); allowedSecuriytGroupAccounts.put(allowedAccount.getId(), allowedAccount);
} }
ingressData.setAccountName(allowedAccount.getAccountName()); securityGroupData.setAccountName(allowedAccount.getAccountName());
} else { } else {
ingressData.setCidr(ingressRule.getAllowedSourceIpCidr()); securityGroupData.setCidr(securityRule.getAllowedSourceIpCidr());
}
if (securityRule.getRuleType() == SecurityRuleType.IngressRule) {
securityGroupData.setObjectName("ingressrule");
ingressResponses.add(securityGroupData);
} else {
securityGroupData.setObjectName("egressrule");
egressResponses.add(securityGroupData);
} }
ingressData.setObjectName("ingressrule");
responses.add(ingressData);
} }
response.setIngressRules(responses); response.setSecurityGroupIngressRules(ingressResponses);
response.setObjectName("securitygroup"); response.setSecurityGroupEgressRules(egressResponses);
}
return response;
}
@Override
public SecurityGroupResponse createSecurityGroupResponseFromEgressRule(List<? extends EgressRule> egressRules) {
SecurityGroupResponse response = new SecurityGroupResponse();
Map<Long, Account> securiytGroupAccounts = new HashMap<Long, Account>();
Map<Long, SecurityGroup> allowedSecurityGroups = new HashMap<Long, SecurityGroup>();
Map<Long, Account> allowedSecuriytGroupAccounts = new HashMap<Long, Account>();
if ((egressRules != null) && !egressRules.isEmpty()) {
SecurityGroup securityGroup = ApiDBUtils.findSecurityGroupById(egressRules.get(0).getSecurityGroupId());
response.setId(securityGroup.getId());
response.setName(securityGroup.getName());
response.setDescription(securityGroup.getDescription());
Account account = securiytGroupAccounts.get(securityGroup.getAccountId());
if (account == null) {
account = ApiDBUtils.findAccountById(securityGroup.getAccountId());
securiytGroupAccounts.put(securityGroup.getAccountId(), account);
}
populateAccount(response, account.getId());
populateDomain(response, account.getDomainId());
List<EgressRuleResponse> responses = new ArrayList<EgressRuleResponse>();
for (EgressRule egressRule : egressRules) {
EgressRuleResponse egressData = new EgressRuleResponse();
egressData.setRuleId(egressRule.getId());
egressData.setProtocol(egressRule.getProtocol());
if ("icmp".equalsIgnoreCase(egressRule.getProtocol())) {
egressData.setIcmpType(egressRule.getStartPort());
egressData.setIcmpCode(egressRule.getEndPort());
} else {
egressData.setStartPort(egressRule.getStartPort());
egressData.setEndPort(egressRule.getEndPort());
}
Long allowedSecurityGroupId = egressRule.getAllowedNetworkId();
if (allowedSecurityGroupId != null) {
SecurityGroup allowedSecurityGroup = allowedSecurityGroups.get(allowedSecurityGroupId);
if (allowedSecurityGroup == null) {
allowedSecurityGroup = ApiDBUtils.findSecurityGroupById(allowedSecurityGroupId);
allowedSecurityGroups.put(allowedSecurityGroupId, allowedSecurityGroup);
}
egressData.setSecurityGroupName(allowedSecurityGroup.getName());
Account allowedAccount = allowedSecuriytGroupAccounts.get(allowedSecurityGroup.getAccountId());
if (allowedAccount == null) {
allowedAccount = ApiDBUtils.findAccountById(allowedSecurityGroup.getAccountId());
allowedSecuriytGroupAccounts.put(allowedAccount.getId(), allowedAccount);
}
egressData.setAccountName(allowedAccount.getAccountName());
} else {
egressData.setCidr(egressRule.getAllowedDestinationIpCidr());
}
egressData.setObjectName("egressrule");
responses.add(egressData);
}
response.setEgressRules(responses);
response.setObjectName("securitygroup"); response.setObjectName("securitygroup");
} }
@ -2740,3 +2693,4 @@ public class ApiResponseHelper implements ResponseGenerator {
return vmResponse; return vmResponse;
} }
} }

View File

@ -1,112 +0,0 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.api.response;
import com.cloud.serializer.Param;
public class EgressRuleResultObject {
@Param(name="id")
private Long id;
@Param(name="startport")
private int startPort;
@Param(name="endport")
private int endPort;
@Param(name="protocol")
private String protocol;
@Param(name="securitygroup")
private String allowedSecurityGroup = null;
@Param(name="account")
private String allowedSecGroupAcct = null;
@Param(name="cidr")
private String allowedDestinationIpCidr = null;
public EgressRuleResultObject() { }
public EgressRuleResultObject(Long id, int startPort, int endPort, String protocol, String allowedSecurityGroup, String allowedSecGroupAcct, String allowedSourceIpCidr) {
this.id = id;
this.startPort = startPort;
this.endPort = endPort;
this.protocol = protocol;
this.allowedSecurityGroup = allowedSecurityGroup;
this.allowedSecGroupAcct = allowedSecGroupAcct;
this.allowedDestinationIpCidr = allowedSourceIpCidr;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public int getStartPort() {
return startPort;
}
public void setStartPort(int startPort) {
this.startPort = startPort;
}
public int getEndPort() {
return endPort;
}
public void setEndPort(int endPort) {
this.endPort = endPort;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public String getAllowedSecurityGroup() {
return allowedSecurityGroup;
}
public void setAllowedSecurityGroup(String allowedSecurityGroup) {
this.allowedSecurityGroup = allowedSecurityGroup;
}
public String getAllowedSecGroupAcct() {
return allowedSecGroupAcct;
}
public void setAllowedSecGroupAcct(String allowedSecGroupAcct) {
this.allowedSecGroupAcct = allowedSecGroupAcct;
}
public String getAllowedDestinationIpCidr() {
return allowedDestinationIpCidr;
}
public void setAllowedDestinationIpCidr(String allowedDestinationIpCidr) {
this.allowedDestinationIpCidr = allowedDestinationIpCidr;
}
}

View File

@ -49,20 +49,20 @@ public class SecurityGroupResultObject implements ControlledEntity{
@Param(name = "accountname") @Param(name = "accountname")
private String accountName = null; private String accountName = null;
@Param(name = "ingressrules") @Param(name = "securitygrouprules")
private List<IngressRuleResultObject> ingressRules = null; private List<SecurityGroupRuleResultObject> securityGroupRules = null;
public SecurityGroupResultObject() { public SecurityGroupResultObject() {
} }
public SecurityGroupResultObject(Long id, String name, String description, long domainId, long accountId, String accountName, List<IngressRuleResultObject> ingressRules) { public SecurityGroupResultObject(Long id, String name, String description, long domainId, long accountId, String accountName, List<SecurityGroupRuleResultObject> ingressRules) {
this.id = id; this.id = id;
this.name = name; this.name = name;
this.description = description; this.description = description;
this.domainId = domainId; this.domainId = domainId;
this.accountId = accountId; this.accountId = accountId;
this.accountName = accountName; this.accountName = accountName;
this.ingressRules = ingressRules; this.securityGroupRules = ingressRules;
} }
public Long getId() { public Long getId() {
@ -113,21 +113,22 @@ public class SecurityGroupResultObject implements ControlledEntity{
this.accountName = accountName; this.accountName = accountName;
} }
public List<IngressRuleResultObject> getIngressRules() { public List<SecurityGroupRuleResultObject> getSecurityGroupRules() {
return ingressRules; return securityGroupRules;
} }
public void setIngressRules(List<IngressRuleResultObject> ingressRules) { public void setSecurityGroupRules(List<SecurityGroupRuleResultObject> securityGroupRules) {
this.ingressRules = ingressRules; this.securityGroupRules = securityGroupRules;
} }
public static List<SecurityGroupResultObject> transposeNetworkGroups(List<? extends SecurityGroupRules> groups) { public static List<SecurityGroupResultObject> transposeNetworkGroups(
List<? extends SecurityGroupRules> groups) {
List<SecurityGroupResultObject> resultObjects = new ArrayList<SecurityGroupResultObject>(); List<SecurityGroupResultObject> resultObjects = new ArrayList<SecurityGroupResultObject>();
Map<Long, SecurityGroup> allowedSecurityGroups = new HashMap<Long, SecurityGroup>(); Map<Long, SecurityGroup> allowedSecurityGroups = new HashMap<Long, SecurityGroup>();
Map<Long, Account> accounts = new HashMap<Long, Account>(); Map<Long, Account> accounts = new HashMap<Long, Account>();
if ((groups != null) && !groups.isEmpty()) { if ((groups != null) && !groups.isEmpty()) {
List<IngressRuleResultObject> ingressDataList = new ArrayList<IngressRuleResultObject>(); List<SecurityGroupRuleResultObject> securityGroupRuleDataList = new ArrayList<SecurityGroupRuleResultObject>();
SecurityGroupResultObject currentGroup = null; SecurityGroupResultObject currentGroup = null;
List<Long> processedGroups = new ArrayList<Long>(); List<Long> processedGroups = new ArrayList<Long>();
@ -137,9 +138,10 @@ public class SecurityGroupResultObject implements ControlledEntity{
processedGroups.add(groupId); processedGroups.add(groupId);
if (currentGroup != null) { if (currentGroup != null) {
if (!ingressDataList.isEmpty()) { if (!securityGroupRuleDataList.isEmpty()) {
currentGroup.setIngressRules(ingressDataList); currentGroup
ingressDataList = new ArrayList<IngressRuleResultObject>(); .setSecurityGroupRules(securityGroupRuleDataList);
securityGroupRuleDataList = new ArrayList<SecurityGroupRuleResultObject>();
} }
resultObjects.add(currentGroup); resultObjects.add(currentGroup);
} }
@ -153,7 +155,8 @@ public class SecurityGroupResultObject implements ControlledEntity{
Account account = accounts.get(netGroupRule.getAccountId()); Account account = accounts.get(netGroupRule.getAccountId());
if (account == null) { if (account == null) {
account = ApiDBUtils.findAccountById(netGroupRule.getAccountId()); account = ApiDBUtils.findAccountById(netGroupRule
.getAccountId());
accounts.put(account.getId(), account); accounts.put(account.getId(), account);
} }
@ -164,41 +167,60 @@ public class SecurityGroupResultObject implements ControlledEntity{
} }
if (netGroupRule.getRuleId() != null) { if (netGroupRule.getRuleId() != null) {
// there's at least one ingress rule for this network group, add the ingress rule data // there's at least one securitygroup rule for this network
IngressRuleResultObject ingressData = new IngressRuleResultObject(); // group, add the securitygroup rule data
ingressData.setEndPort(netGroupRule.getEndPort()); SecurityGroupRuleResultObject securityGroupRuleData = new SecurityGroupRuleResultObject();
ingressData.setStartPort(netGroupRule.getStartPort()); securityGroupRuleData.setEndPort(netGroupRule.getEndPort());
ingressData.setId(netGroupRule.getRuleId()); securityGroupRuleData.setStartPort(netGroupRule
ingressData.setProtocol(netGroupRule.getProtocol()); .getStartPort());
securityGroupRuleData.setId(netGroupRule.getRuleId());
securityGroupRuleData.setProtocol(netGroupRule
.getProtocol());
securityGroupRuleData.setRuleType(netGroupRule
.getRuleType());
Long allowedSecurityGroupId = netGroupRule.getAllowedNetworkId(); Long allowedSecurityGroupId = netGroupRule
.getAllowedNetworkId();
if (allowedSecurityGroupId != null) { if (allowedSecurityGroupId != null) {
SecurityGroup allowedSecurityGroup = allowedSecurityGroups.get(allowedSecurityGroupId); SecurityGroup allowedSecurityGroup = allowedSecurityGroups
.get(allowedSecurityGroupId);
if (allowedSecurityGroup == null) { if (allowedSecurityGroup == null) {
allowedSecurityGroup = ApiDBUtils.findSecurityGroupById(allowedSecurityGroupId); allowedSecurityGroup = ApiDBUtils
allowedSecurityGroups.put(allowedSecurityGroupId, allowedSecurityGroup); .findSecurityGroupById(allowedSecurityGroupId);
allowedSecurityGroups.put(allowedSecurityGroupId,
allowedSecurityGroup);
} }
ingressData.setAllowedSecurityGroup(allowedSecurityGroup.getName()); securityGroupRuleData
.setAllowedSecurityGroup(allowedSecurityGroup
.getName());
Account allowedAccount = accounts.get(allowedSecurityGroup.getAccountId()); Account allowedAccount = accounts
.get(allowedSecurityGroup.getAccountId());
if (allowedAccount == null) { if (allowedAccount == null) {
allowedAccount = ApiDBUtils.findAccountById(allowedSecurityGroup.getAccountId()); allowedAccount = ApiDBUtils
.findAccountById(allowedSecurityGroup
.getAccountId());
accounts.put(allowedAccount.getId(), allowedAccount); accounts.put(allowedAccount.getId(), allowedAccount);
} }
ingressData.setAllowedSecGroupAcct(allowedAccount.getAccountName()); securityGroupRuleData
.setAllowedSecGroupAcct(allowedAccount
.getAccountName());
} else if (netGroupRule.getAllowedSourceIpCidr() != null) { } else if (netGroupRule.getAllowedSourceIpCidr() != null) {
ingressData.setAllowedSourceIpCidr(netGroupRule.getAllowedSourceIpCidr()); securityGroupRuleData
.setAllowedSourceIpCidr(netGroupRule
.getAllowedSourceIpCidr());
} }
ingressDataList.add(ingressData); securityGroupRuleDataList.add(securityGroupRuleData);
} }
} }
// all rules have been processed, add the final data into the list // all rules have been processed, add the final data into the list
if (currentGroup != null) { if (currentGroup != null) {
if (!ingressDataList.isEmpty()) { if (!securityGroupRuleDataList.isEmpty()) {
currentGroup.setIngressRules(ingressDataList); currentGroup
.setSecurityGroupRules(securityGroupRuleDataList);
} }
resultObjects.add(currentGroup); resultObjects.add(currentGroup);
} }

View File

@ -18,9 +18,10 @@
package com.cloud.api.response; package com.cloud.api.response;
import com.cloud.network.security.SecurityRule.SecurityRuleType;
import com.cloud.serializer.Param; import com.cloud.serializer.Param;
public class IngressRuleResultObject { public class SecurityGroupRuleResultObject {
@Param(name="id") @Param(name="id")
private Long id; private Long id;
@ -42,9 +43,11 @@ public class IngressRuleResultObject {
@Param(name="cidr") @Param(name="cidr")
private String allowedSourceIpCidr = null; private String allowedSourceIpCidr = null;
public IngressRuleResultObject() { } private SecurityRuleType type;
public IngressRuleResultObject(Long id, int startPort, int endPort, String protocol, String allowedSecurityGroup, String allowedSecGroupAcct, String allowedSourceIpCidr) { public SecurityGroupRuleResultObject() { }
public SecurityGroupRuleResultObject(Long id, int startPort, int endPort, String protocol, String allowedSecurityGroup, String allowedSecGroupAcct, String allowedSourceIpCidr) {
this.id = id; this.id = id;
this.startPort = startPort; this.startPort = startPort;
this.endPort = endPort; this.endPort = endPort;
@ -66,6 +69,15 @@ public class IngressRuleResultObject {
return startPort; return startPort;
} }
public void setRuleType(SecurityRuleType type) {
this.type = type;
}
public SecurityRuleType getRuleType() {
return type;
}
public void setStartPort(int startPort) { public void setStartPort(int startPort) {
this.startPort = startPort; this.startPort = startPort;
} }

View File

@ -100,7 +100,7 @@ import com.cloud.network.router.VirtualNetworkApplianceManagerImpl;
import com.cloud.network.rules.RulesManagerImpl; import com.cloud.network.rules.RulesManagerImpl;
import com.cloud.network.rules.dao.PortForwardingRulesDaoImpl; import com.cloud.network.rules.dao.PortForwardingRulesDaoImpl;
import com.cloud.network.security.SecurityGroupManagerImpl2; import com.cloud.network.security.SecurityGroupManagerImpl2;
import com.cloud.network.security.dao.IngressRuleDaoImpl; import com.cloud.network.security.dao.SecurityGroupRuleDaoImpl;
import com.cloud.network.security.dao.SecurityGroupDaoImpl; import com.cloud.network.security.dao.SecurityGroupDaoImpl;
import com.cloud.network.security.dao.SecurityGroupRulesDaoImpl; import com.cloud.network.security.dao.SecurityGroupRulesDaoImpl;
import com.cloud.network.security.dao.SecurityGroupVMMapDaoImpl; import com.cloud.network.security.dao.SecurityGroupVMMapDaoImpl;
@ -210,7 +210,7 @@ public class DefaultComponentLibrary extends ComponentLibraryBase implements Com
addDao("LoadBalancerVMMapDao", LoadBalancerVMMapDaoImpl.class); addDao("LoadBalancerVMMapDao", LoadBalancerVMMapDaoImpl.class);
addDao("DataCenterIpAddressDao", DataCenterIpAddressDaoImpl.class); addDao("DataCenterIpAddressDao", DataCenterIpAddressDaoImpl.class);
addDao("SecurityGroupDao", SecurityGroupDaoImpl.class); addDao("SecurityGroupDao", SecurityGroupDaoImpl.class);
addDao("IngressRuleDao", IngressRuleDaoImpl.class); addDao("SecurityGroupRuleDao", SecurityGroupRuleDaoImpl.class);
addDao("SecurityGroupVMMapDao", SecurityGroupVMMapDaoImpl.class); addDao("SecurityGroupVMMapDao", SecurityGroupVMMapDaoImpl.class);
addDao("SecurityGroupRulesDao", SecurityGroupRulesDaoImpl.class); addDao("SecurityGroupRulesDao", SecurityGroupRulesDaoImpl.class);
addDao("SecurityGroupWorkDao", SecurityGroupWorkDaoImpl.class); addDao("SecurityGroupWorkDao", SecurityGroupWorkDaoImpl.class);

View File

@ -33,10 +33,10 @@ import com.cloud.agent.api.Answer;
import com.cloud.agent.api.CleanupNetworkRulesCmd; import com.cloud.agent.api.CleanupNetworkRulesCmd;
import com.cloud.agent.api.Command; import com.cloud.agent.api.Command;
import com.cloud.agent.api.PingRoutingWithNwGroupsCommand; import com.cloud.agent.api.PingRoutingWithNwGroupsCommand;
import com.cloud.agent.api.SecurityIngressRuleAnswer; import com.cloud.agent.api.SecurityGroupRuleAnswer;
import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupCommand;
import com.cloud.agent.api.StartupRoutingCommand; import com.cloud.agent.api.StartupRoutingCommand;
import com.cloud.agent.api.SecurityIngressRuleAnswer.FailureReason; import com.cloud.agent.api.SecurityGroupRuleAnswer.FailureReason;
import com.cloud.agent.manager.Commands; import com.cloud.agent.manager.Commands;
import com.cloud.exception.AgentUnavailableException; import com.cloud.exception.AgentUnavailableException;
import com.cloud.host.HostVO; import com.cloud.host.HostVO;
@ -89,8 +89,8 @@ public class SecurityGroupListener implements Listener {
List<Long> affectedVms = new ArrayList<Long>(); List<Long> affectedVms = new ArrayList<Long>();
int commandNum = 0; int commandNum = 0;
for (Answer ans: answers) { for (Answer ans: answers) {
if (ans instanceof SecurityIngressRuleAnswer) { if (ans instanceof SecurityGroupRuleAnswer) {
SecurityIngressRuleAnswer ruleAnswer = (SecurityIngressRuleAnswer) ans; SecurityGroupRuleAnswer ruleAnswer = (SecurityGroupRuleAnswer) ans;
if (ans.getResult()) { if (ans.getResult()) {
s_logger.debug("Successfully programmed rule " + ruleAnswer.toString() + " into host " + agentId); s_logger.debug("Successfully programmed rule " + ruleAnswer.toString() + " into host " + agentId);
_workDao.updateStep(ruleAnswer.getVmId(), ruleAnswer.getLogSequenceNumber(), Step.Done); _workDao.updateStep(ruleAnswer.getVmId(), ruleAnswer.getLogSequenceNumber(), Step.Done);

View File

@ -42,14 +42,16 @@ import org.apache.log4j.Logger;
import com.cloud.agent.AgentManager; import com.cloud.agent.AgentManager;
import com.cloud.agent.api.NetworkRulesSystemVmCommand; import com.cloud.agent.api.NetworkRulesSystemVmCommand;
import com.cloud.agent.api.SecurityIngressRulesCmd; import com.cloud.agent.api.SecurityGroupRulesCmd;
import com.cloud.agent.api.SecurityIngressRulesCmd.IpPortAndProto; import com.cloud.agent.api.SecurityGroupRulesCmd.IpPortAndProto;
import com.cloud.agent.manager.Commands; import com.cloud.agent.manager.Commands;
import com.cloud.api.commands.AuthorizeSecurityGroupIngressCmd; import com.cloud.api.commands.AuthorizeSecurityGroupIngressCmd;
import com.cloud.api.commands.AuthorizeSecurityGroupEgressCmd;
import com.cloud.api.commands.CreateSecurityGroupCmd; import com.cloud.api.commands.CreateSecurityGroupCmd;
import com.cloud.api.commands.DeleteSecurityGroupCmd; import com.cloud.api.commands.DeleteSecurityGroupCmd;
import com.cloud.api.commands.ListSecurityGroupsCmd; import com.cloud.api.commands.ListSecurityGroupsCmd;
import com.cloud.api.commands.RevokeSecurityGroupIngressCmd; import com.cloud.api.commands.RevokeSecurityGroupIngressCmd;
import com.cloud.api.commands.RevokeSecurityGroupEgressCmd;
import com.cloud.configuration.Config; import com.cloud.configuration.Config;
import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.domain.Domain; import com.cloud.domain.Domain;
@ -65,7 +67,7 @@ import com.cloud.exception.ResourceInUseException;
import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.network.NetworkManager; import com.cloud.network.NetworkManager;
import com.cloud.network.security.SecurityGroupWork.Step; import com.cloud.network.security.SecurityGroupWork.Step;
import com.cloud.network.security.dao.IngressRuleDao; import com.cloud.network.security.dao.SecurityGroupRuleDao;
import com.cloud.network.security.dao.SecurityGroupDao; import com.cloud.network.security.dao.SecurityGroupDao;
import com.cloud.network.security.dao.SecurityGroupRulesDao; import com.cloud.network.security.dao.SecurityGroupRulesDao;
import com.cloud.network.security.dao.SecurityGroupVMMapDao; import com.cloud.network.security.dao.SecurityGroupVMMapDao;
@ -107,6 +109,7 @@ import com.cloud.vm.VirtualMachine.State;
import com.cloud.vm.VirtualMachineManager; import com.cloud.vm.VirtualMachineManager;
import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.UserVmDao;
import com.cloud.vm.dao.VMInstanceDao; import com.cloud.vm.dao.VMInstanceDao;
import com.cloud.network.security.SecurityRule.SecurityRuleType;
import edu.emory.mathcs.backport.java.util.Collections; import edu.emory.mathcs.backport.java.util.Collections;
@ -117,7 +120,7 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG
@Inject @Inject
SecurityGroupDao _securityGroupDao; SecurityGroupDao _securityGroupDao;
@Inject @Inject
IngressRuleDao _ingressRuleDao; SecurityGroupRuleDao _securityGroupRuleDao;
@Inject @Inject
SecurityGroupVMMapDao _securityGroupVMMapDao; SecurityGroupVMMapDao _securityGroupVMMapDao;
@Inject @Inject
@ -326,14 +329,14 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG
} }
protected Map<PortAndProto, Set<String>> generateRulesForVM(Long userVmId) { protected Map<PortAndProto, Set<String>> generateRulesForVM(Long userVmId, SecurityRuleType type) {
Map<PortAndProto, Set<String>> allowed = new TreeMap<PortAndProto, Set<String>>(); Map<PortAndProto, Set<String>> allowed = new TreeMap<PortAndProto, Set<String>>();
List<SecurityGroupVMMapVO> groupsForVm = _securityGroupVMMapDao.listByInstanceId(userVmId); List<SecurityGroupVMMapVO> groupsForVm = _securityGroupVMMapDao.listByInstanceId(userVmId);
for (SecurityGroupVMMapVO mapVO : groupsForVm) { for (SecurityGroupVMMapVO mapVO : groupsForVm) {
List<IngressRuleVO> rules = _ingressRuleDao.listBySecurityGroupId(mapVO.getSecurityGroupId()); List<SecurityGroupRuleVO> rules = _securityGroupRuleDao.listBySecurityGroupId(mapVO.getSecurityGroupId(), type);
for (IngressRuleVO rule : rules) { for (SecurityGroupRuleVO rule : rules) {
PortAndProto portAndProto = new PortAndProto(rule.getProtocol(), rule.getStartPort(), rule.getEndPort()); PortAndProto portAndProto = new PortAndProto(rule.getProtocol(), rule.getStartPort(), rule.getEndPort());
Set<String> cidrs = allowed.get(portAndProto); Set<String> cidrs = allowed.get(portAndProto);
if (cidrs == null) { if (cidrs == null) {
@ -446,9 +449,9 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG
List<SecurityGroupVMMapVO> groupsForVm = _securityGroupVMMapDao.listByInstanceId(vm.getId()); List<SecurityGroupVMMapVO> groupsForVm = _securityGroupVMMapDao.listByInstanceId(vm.getId());
// For each group, find the ingress rules that allow the group // For each group, find the ingress rules that allow the group
for (SecurityGroupVMMapVO mapVO : groupsForVm) {// FIXME: use custom sql in the dao for (SecurityGroupVMMapVO mapVO : groupsForVm) {// FIXME: use custom sql in the dao
List<IngressRuleVO> allowingRules = _ingressRuleDao.listByAllowedSecurityGroupId(mapVO.getSecurityGroupId()); List<SecurityGroupRuleVO> allowingRules = _securityGroupRuleDao.listByAllowedSecurityGroupId(mapVO.getSecurityGroupId());
// For each ingress rule that allows a group that the vm belongs to, find the group it belongs to // For each ingress rule that allows a group that the vm belongs to, find the group it belongs to
affectedVms.addAll(getAffectedVmsForIngressRules(allowingRules)); affectedVms.addAll(getAffectedVmsForSecurityRules(allowingRules));
} }
return affectedVms; return affectedVms;
} }
@ -458,18 +461,18 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG
List<SecurityGroupVMMapVO> groupsForVm = _securityGroupVMMapDao.listByInstanceId(vm.getId()); List<SecurityGroupVMMapVO> groupsForVm = _securityGroupVMMapDao.listByInstanceId(vm.getId());
// For each group, find the ingress rules that allow the group // For each group, find the ingress rules that allow the group
for (SecurityGroupVMMapVO mapVO : groupsForVm) {// FIXME: use custom sql in the dao for (SecurityGroupVMMapVO mapVO : groupsForVm) {// FIXME: use custom sql in the dao
List<IngressRuleVO> allowingRules = _ingressRuleDao.listByAllowedSecurityGroupId(mapVO.getSecurityGroupId()); List<SecurityGroupRuleVO> allowingRules = _securityGroupRuleDao.listByAllowedSecurityGroupId(mapVO.getSecurityGroupId());
// For each ingress rule that allows a group that the vm belongs to, find the group it belongs to // For each ingress rule that allows a group that the vm belongs to, find the group it belongs to
affectedVms.addAll(getAffectedVmsForIngressRules(allowingRules)); affectedVms.addAll(getAffectedVmsForSecurityRules(allowingRules));
} }
return affectedVms; return affectedVms;
} }
protected List<Long> getAffectedVmsForIngressRules(List<IngressRuleVO> allowingRules) { protected List<Long> getAffectedVmsForSecurityRules(List<SecurityGroupRuleVO> allowingRules) {
Set<Long> distinctGroups = new HashSet<Long>(); Set<Long> distinctGroups = new HashSet<Long>();
List<Long> affectedVms = new ArrayList<Long>(); List<Long> affectedVms = new ArrayList<Long>();
for (IngressRuleVO allowingRule : allowingRules) { for (SecurityGroupRuleVO allowingRule : allowingRules) {
distinctGroups.add(allowingRule.getSecurityGroupId()); distinctGroups.add(allowingRule.getSecurityGroupId());
} }
for (Long groupId : distinctGroups) { for (Long groupId : distinctGroups) {
@ -479,16 +482,16 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG
return affectedVms; return affectedVms;
} }
protected SecurityIngressRulesCmd generateRulesetCmd(String vmName, String guestIp, String guestMac, Long vmId, String signature, long seqnum, Map<PortAndProto, Set<String>> rules) { protected SecurityGroupRulesCmd generateRulesetCmd(SecurityRuleType ruleType, String vmName, String guestIp, String guestMac, Long vmId, String signature, long seqnum, Map<PortAndProto, Set<String>> rules) {
List<IpPortAndProto> result = new ArrayList<IpPortAndProto>(); List<IpPortAndProto> result = new ArrayList<IpPortAndProto>();
for (PortAndProto pAp : rules.keySet()) { for (PortAndProto pAp : rules.keySet()) {
Set<String> cidrs = rules.get(pAp); Set<String> cidrs = rules.get(pAp);
if (cidrs.size() > 0) { if (cidrs.size() > 0) {
IpPortAndProto ipPortAndProto = new SecurityIngressRulesCmd.IpPortAndProto(pAp.getProto(), pAp.getStartPort(), pAp.getEndPort(), cidrs.toArray(new String[cidrs.size()])); IpPortAndProto ipPortAndProto = new SecurityGroupRulesCmd.IpPortAndProto(pAp.getProto(), pAp.getStartPort(), pAp.getEndPort(), cidrs.toArray(new String[cidrs.size()]));
result.add(ipPortAndProto); result.add(ipPortAndProto);
} }
} }
return new SecurityIngressRulesCmd(guestIp, guestMac, vmName, vmId, signature, seqnum, result.toArray(new IpPortAndProto[result.size()])); return new SecurityGroupRulesCmd(ruleType,guestIp, guestMac, vmName, vmId, signature, seqnum, result.toArray(new IpPortAndProto[result.size()]));
} }
protected void handleVmStopped(VMInstanceVO vm) { protected void handleVmStopped(VMInstanceVO vm) {
@ -519,11 +522,11 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG
scheduleRulesetUpdateToHosts(affectedVms, true, null); scheduleRulesetUpdateToHosts(affectedVms, true, null);
} }
} }
@Override @Override
@DB @DB
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public List<IngressRuleVO> authorizeSecurityGroupIngress(AuthorizeSecurityGroupIngressCmd cmd) { @ActionEvent(eventType = EventTypes.EVENT_SECURITY_GROUP_AUTHORIZE_EGRESS, eventDescription = "Adding Egress Rule ", async = true)
public List<SecurityGroupRuleVO> authorizeSecurityGroupEgress(AuthorizeSecurityGroupEgressCmd cmd) {
Long securityGroupId = cmd.getSecurityGroupId(); Long securityGroupId = cmd.getSecurityGroupId();
String protocol = cmd.getProtocol(); String protocol = cmd.getProtocol();
Integer startPort = cmd.getStartPort(); Integer startPort = cmd.getStartPort();
@ -532,10 +535,30 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG
Integer icmpCode = cmd.getIcmpCode(); Integer icmpCode = cmd.getIcmpCode();
List<String> cidrList = cmd.getCidrList(); List<String> cidrList = cmd.getCidrList();
Map groupList = cmd.getUserSecurityGroupList(); Map groupList = cmd.getUserSecurityGroupList();
return authorizeSecurityGroupRule(securityGroupId,protocol,startPort,endPort,icmpType,icmpCode,cidrList,groupList,SecurityRuleType.EgressRule);
}
@Override
@DB
@SuppressWarnings("rawtypes")
@ActionEvent(eventType = EventTypes.EVENT_SECURITY_GROUP_AUTHORIZE_INGRESS, eventDescription = "Adding Ingress Rule ", async = true)
public List<SecurityGroupRuleVO> 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<String> cidrList = cmd.getCidrList();
Map groupList = cmd.getUserSecurityGroupList();
return authorizeSecurityGroupRule(securityGroupId,protocol,startPort,endPort,icmpType,icmpCode,cidrList,groupList,SecurityRuleType.IngressRule);
}
private List<SecurityGroupRuleVO> authorizeSecurityGroupRule(Long securityGroupId,String protocol,Integer startPort,Integer endPort,Integer icmpType,Integer icmpCode,List<String> cidrList,Map groupList,SecurityRuleType ruleType) {
Integer startPortOrType = null; Integer startPortOrType = null;
Integer endPortOrCode = null; Integer endPortOrCode = null;
// Validate parameters // Validate parameters
SecurityGroup securityGroup = _securityGroupDao.findById(securityGroupId); SecurityGroup securityGroup = _securityGroupDao.findById(securityGroupId);
if (securityGroup == null) { if (securityGroup == null) {
throw new InvalidParameterValueException("Unable to find security group by id " + securityGroupId); throw new InvalidParameterValueException("Unable to find security group by id " + securityGroupId);
@ -620,13 +643,13 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG
Account authorizedAccount = _accountDao.findActiveAccount(authorizedAccountName, domainId); Account authorizedAccount = _accountDao.findActiveAccount(authorizedAccountName, domainId);
if (authorizedAccount == null) { if (authorizedAccount == null) {
throw new InvalidParameterValueException("Nonexistent account: " + authorizedAccountName + " when trying to authorize ingress for " + securityGroupId + ":" + protocol + ":" throw new InvalidParameterValueException("Nonexistent account: " + authorizedAccountName + " when trying to authorize security group rule for " + securityGroupId + ":" + protocol + ":"
+ startPortOrType + ":" + endPortOrCode); + startPortOrType + ":" + endPortOrCode);
} }
SecurityGroupVO groupVO = _securityGroupDao.findByAccountAndName(authorizedAccount.getId(), group); SecurityGroupVO groupVO = _securityGroupDao.findByAccountAndName(authorizedAccount.getId(), group);
if (groupVO == null) { if (groupVO == null) {
throw new InvalidParameterValueException("Nonexistent group " + group + " for account " + authorizedAccountName + "/" + domainId + " is given, unable to authorize ingress."); throw new InvalidParameterValueException("Nonexistent group " + group + " for account " + authorizedAccountName + "/" + domainId + " is given, unable to authorize security group rule.");
} }
// Check permissions // Check permissions
@ -650,7 +673,7 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG
s_logger.warn("Could not acquire lock on network security group: id= " + securityGroupId); s_logger.warn("Could not acquire lock on network security group: id= " + securityGroupId);
return null; return null;
} }
List<IngressRuleVO> newRules = new ArrayList<IngressRuleVO>(); List<SecurityGroupRuleVO> newRules = new ArrayList<SecurityGroupRuleVO>();
try { try {
for (final SecurityGroupVO ngVO : authorizedGroups2) { for (final SecurityGroupVO ngVO : authorizedGroups2) {
final Long ngId = ngVO.getId(); final Long ngId = ngVO.getId();
@ -663,23 +686,23 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG
return null; return null;
} }
} }
IngressRuleVO ingressRule = _ingressRuleDao.findByProtoPortsAndAllowedGroupId(securityGroup.getId(), protocol, startPortOrType, endPortOrCode, ngVO.getId()); SecurityGroupRuleVO securityGroupRule = _securityGroupRuleDao.findByProtoPortsAndAllowedGroupId(securityGroup.getId(), protocol, startPortOrType, endPortOrCode, ngVO.getId());
if (ingressRule != null) { if ((securityGroupRule != null) && (securityGroupRule.getRuleType() == ruleType)) {
continue; // rule already exists. continue; // rule already exists.
} }
ingressRule = new IngressRuleVO(securityGroup.getId(), startPortOrType, endPortOrCode, protocol, ngVO.getId()); securityGroupRule = new SecurityGroupRuleVO(ruleType,securityGroup.getId(), startPortOrType, endPortOrCode, protocol, ngVO.getId());
ingressRule = _ingressRuleDao.persist(ingressRule); securityGroupRule = _securityGroupRuleDao.persist(securityGroupRule);
newRules.add(ingressRule); newRules.add(securityGroupRule);
} }
if (cidrList != null) { if (cidrList != null) {
for (String cidr : cidrList) { for (String cidr : cidrList) {
IngressRuleVO ingressRule = _ingressRuleDao.findByProtoPortsAndCidr(securityGroup.getId(), protocol, startPortOrType, endPortOrCode, cidr); SecurityGroupRuleVO securityGroupRule = _securityGroupRuleDao.findByProtoPortsAndCidr(securityGroup.getId(), protocol, startPortOrType, endPortOrCode, cidr);
if (ingressRule != null) { if ((securityGroupRule != null) && (securityGroupRule.getRuleType() == ruleType)) {
continue; continue;
} }
ingressRule = new IngressRuleVO(securityGroup.getId(), startPortOrType, endPortOrCode, protocol, cidr); securityGroupRule = new SecurityGroupRuleVO(ruleType,securityGroup.getId(), startPortOrType, endPortOrCode, protocol, cidr);
ingressRule = _ingressRuleDao.persist(ingressRule); securityGroupRule = _securityGroupRuleDao.persist(securityGroupRule);
newRules.add(ingressRule); newRules.add(securityGroupRule);
} }
} }
if (s_logger.isDebugEnabled()) { if (s_logger.isDebugEnabled()) {
@ -691,8 +714,8 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG
scheduleRulesetUpdateToHosts(affectedVms, true, null); scheduleRulesetUpdateToHosts(affectedVms, true, null);
return newRules; return newRules;
} catch (Exception e) { } catch (Exception e) {
s_logger.warn("Exception caught when adding ingress rules ", e); s_logger.warn("Exception caught when adding security group rules ", e);
throw new CloudRuntimeException("Exception caught when adding ingress rules", e); throw new CloudRuntimeException("Exception caught when adding security group rules", e);
} finally { } finally {
if (securityGroup != null) { if (securityGroup != null) {
_securityGroupDao.releaseFromLockTable(securityGroup.getId()); _securityGroupDao.releaseFromLockTable(securityGroup.getId());
@ -702,15 +725,35 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG
@Override @Override
@DB @DB
@ActionEvent(eventType = EventTypes.EVENT_SECURITY_GROUP_REVOKE_EGRESS, eventDescription = "Revoking Egress Rule ", async = true)
public boolean revokeSecurityGroupEgress(RevokeSecurityGroupEgressCmd cmd) {
Long id = cmd.getId();
return revokeSecurityGroupRule(id, SecurityRuleType.EgressRule);
}
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_SECURITY_GROUP_REVOKE_INGRESS, eventDescription = "Revoking Ingress Rule ", async = true)
public boolean revokeSecurityGroupIngress(RevokeSecurityGroupIngressCmd cmd) { public boolean revokeSecurityGroupIngress(RevokeSecurityGroupIngressCmd cmd) {
Long id = cmd.getId();
return revokeSecurityGroupRule(id, SecurityRuleType.IngressRule);
}
private boolean revokeSecurityGroupRule(Long id, SecurityRuleType type) {
// input validation // input validation
Account caller = UserContext.current().getCaller(); Account caller = UserContext.current().getCaller();
Long id = cmd.getId();
IngressRuleVO rule = _ingressRuleDao.findById(id); SecurityGroupRuleVO rule = _securityGroupRuleDao.findById(id);
if (rule == null) { if (rule == null) {
s_logger.debug("Unable to find ingress rule with id " + id); s_logger.debug("Unable to find security rule with id " + id);
throw new InvalidParameterValueException("Unable to find ingress rule with id " + id); throw new InvalidParameterValueException("Unable to find security rule with id " + id);
}
// check type
if (type != rule.getRuleType()) {
s_logger.debug("Mismatch in rule type for security rule with id " + id );
throw new InvalidParameterValueException("Mismatch in rule type for security rule with id " + id);
} }
// Check permissions // Check permissions
@ -729,8 +772,8 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG
return false; return false;
} }
_ingressRuleDao.remove(id); _securityGroupRuleDao.remove(id);
s_logger.debug("revokeSecurityGroupIngress succeeded for ingress rule id: " + id); s_logger.debug("revokeSecurityGroupIngress succeeded for security rule id: " + id);
final ArrayList<Long> affectedVms = new ArrayList<Long>(); final ArrayList<Long> affectedVms = new ArrayList<Long>();
affectedVms.addAll(_securityGroupVMMapDao.listVmIdsBySecurityGroup(groupHandle.getId())); affectedVms.addAll(_securityGroupVMMapDao.listVmIdsBySecurityGroup(groupHandle.getId()));
@ -738,8 +781,8 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG
return true; return true;
} catch (Exception e) { } catch (Exception e) {
s_logger.warn("Exception caught when deleting ingress rules ", e); s_logger.warn("Exception caught when deleting security rules ", e);
throw new CloudRuntimeException("Exception caught when deleting ingress rules", e); throw new CloudRuntimeException("Exception caught when deleting security rules", e);
} finally { } finally {
if (groupHandle != null) { if (groupHandle != null) {
_securityGroupDao.releaseFromLockTable(groupHandle.getId()); _securityGroupDao.releaseFromLockTable(groupHandle.getId());
@ -883,16 +926,26 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG
seqnum = log.getLogsequence(); seqnum = log.getLogsequence();
if (vm != null && vm.getState() == State.Running) { if (vm != null && vm.getState() == State.Running) {
Map<PortAndProto, Set<String>> rules = generateRulesForVM(userVmId); Map<PortAndProto, Set<String>> rules = generateRulesForVM(userVmId, SecurityRuleType.IngressRule);
agentId = vm.getHostId(); agentId = vm.getHostId();
if (agentId != null) { if (agentId != null) {
SecurityIngressRulesCmd cmd = generateRulesetCmd(vm.getInstanceName(), vm.getPrivateIpAddress(), vm.getPrivateMacAddress(), vm.getId(), generateRulesetSignature(rules), seqnum, SecurityGroupRulesCmd cmd = generateRulesetCmd(SecurityRuleType.IngressRule, vm.getInstanceName(), vm.getPrivateIpAddress(), vm.getPrivateMacAddress(), vm.getId(), generateRulesetSignature(rules), seqnum,
rules); rules);
Commands cmds = new Commands(cmd); Commands cmds = new Commands(cmd);
try { try {
_agentMgr.send(agentId, cmds, _answerListener); _agentMgr.send(agentId, cmds, _answerListener);
} catch (AgentUnavailableException e) { } catch (AgentUnavailableException e) {
s_logger.debug("Unable to send updates for vm: " + userVmId + "(agentid=" + agentId + ")"); s_logger.debug("Unable to send ingress rules updates for vm: " + userVmId + "(agentid=" + agentId + ")");
_workDao.updateStep(work.getInstanceId(), seqnum, Step.Done);
}
cmd = generateRulesetCmd(SecurityRuleType.EgressRule, vm.getInstanceName(), vm.getPrivateIpAddress(), vm.getPrivateMacAddress(), vm.getId(), generateRulesetSignature(rules), seqnum,
rules);
cmds = new Commands(cmd);
try {
_agentMgr.send(agentId, cmds, _answerListener);
} catch (AgentUnavailableException e) {
s_logger.debug("Unable to send egress rules updates for vm: " + userVmId + "(agentid=" + agentId + ")");
_workDao.updateStep(work.getInstanceId(), seqnum, Step.Done); _workDao.updateStep(work.getInstanceId(), seqnum, Step.Done);
} }
} }
@ -1000,7 +1053,7 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG
throw new InvalidParameterValueException("The network group default is reserved"); throw new InvalidParameterValueException("The network group default is reserved");
} }
List<IngressRuleVO> allowingRules = _ingressRuleDao.listByAllowedSecurityGroupId(groupId); List<SecurityGroupRuleVO> allowingRules = _securityGroupRuleDao.listByAllowedSecurityGroupId(groupId);
List<SecurityGroupVMMapVO> securityGroupVmMap = _securityGroupVMMapDao.listBySecurityGroup(groupId); List<SecurityGroupVMMapVO> securityGroupVmMap = _securityGroupVMMapDao.listBySecurityGroup(groupId);
if (!allowingRules.isEmpty()) { if (!allowingRules.isEmpty()) {
throw new ResourceInUseException("Cannot delete group when there are ingress rules that allow this group"); throw new ResourceInUseException("Cannot delete group when there are ingress rules that allow this group");

View File

@ -28,7 +28,7 @@ import java.util.concurrent.ConcurrentHashMap;
import javax.ejb.Local; import javax.ejb.Local;
import javax.naming.ConfigurationException; import javax.naming.ConfigurationException;
import com.cloud.agent.api.SecurityIngressRulesCmd; import com.cloud.agent.api.SecurityGroupRulesCmd;
import com.cloud.agent.manager.Commands; import com.cloud.agent.manager.Commands;
import com.cloud.configuration.Config; import com.cloud.configuration.Config;
import com.cloud.exception.AgentUnavailableException; import com.cloud.exception.AgentUnavailableException;
@ -39,7 +39,7 @@ import com.cloud.utils.Profiler;
import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.mgmt.JmxUtil; import com.cloud.utils.mgmt.JmxUtil;
import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.VirtualMachine.State;
import com.cloud.network.security.SecurityRule.SecurityRuleType;
/** /**
* Same as the base class -- except it uses the abstracted security group work queue * Same as the base class -- except it uses the abstracted security group work queue
@ -147,7 +147,8 @@ public class SecurityGroupManagerImpl2 extends SecurityGroupManagerImpl{
continue; continue;
} }
work.setLogsequenceNumber(rulesetLog.getLogsequence()); work.setLogsequenceNumber(rulesetLog.getLogsequence());
sendRulesetUpdates(work); sendRulesetUpdates(work, SecurityRuleType.IngressRule);
sendRulesetUpdates(work, SecurityRuleType.EgressRule);
_mBean.logUpdateDetails(work.getInstanceId(), work.getLogsequenceNumber()); _mBean.logUpdateDetails(work.getInstanceId(), work.getLogsequenceNumber());
}catch (Exception e) { }catch (Exception e) {
s_logger.error("Problem during SG work " + work, e); s_logger.error("Problem during SG work " + work, e);
@ -161,7 +162,7 @@ public class SecurityGroupManagerImpl2 extends SecurityGroupManagerImpl{
} }
public void sendRulesetUpdates(SecurityGroupWork work){ public void sendRulesetUpdates(SecurityGroupWork work, SecurityRuleType ruleType){
Long userVmId = work.getInstanceId(); Long userVmId = work.getInstanceId();
UserVm vm = _userVMDao.findById(userVmId); UserVm vm = _userVMDao.findById(userVmId);
@ -176,8 +177,8 @@ public class SecurityGroupManagerImpl2 extends SecurityGroupManagerImpl{
+ ": too many messages outstanding on host " + agentId); + ": too many messages outstanding on host " + agentId);
return; return;
} }
Map<PortAndProto, Set<String>> rules = generateRulesForVM(userVmId); Map<PortAndProto, Set<String>> rules = generateRulesForVM(userVmId, ruleType);
SecurityIngressRulesCmd cmd = generateRulesetCmd(vm.getInstanceName(), vm.getPrivateIpAddress(), SecurityGroupRulesCmd cmd = generateRulesetCmd(ruleType, vm.getInstanceName(), vm.getPrivateIpAddress(),
vm.getPrivateMacAddress(), vm.getId(), null, vm.getPrivateMacAddress(), vm.getId(), null,
work.getLogsequenceNumber(), rules); work.getLogsequenceNumber(), rules);
cmd.setMsId(_serverId); cmd.setMsId(_serverId);
@ -218,14 +219,14 @@ public class SecurityGroupManagerImpl2 extends SecurityGroupManagerImpl{
* then we get all ips, including the default nic ip. This is also probably the correct behavior. * then we get all ips, including the default nic ip. This is also probably the correct behavior.
*/ */
@Override @Override
protected Map<PortAndProto, Set<String>> generateRulesForVM(Long userVmId) { protected Map<PortAndProto, Set<String>> generateRulesForVM(Long userVmId, SecurityRuleType type) {
Map<PortAndProto, Set<String>> allowed = new TreeMap<PortAndProto, Set<String>>(); Map<PortAndProto, Set<String>> allowed = new TreeMap<PortAndProto, Set<String>>();
List<SecurityGroupVMMapVO> groupsForVm = _securityGroupVMMapDao.listByInstanceId(userVmId); List<SecurityGroupVMMapVO> groupsForVm = _securityGroupVMMapDao.listByInstanceId(userVmId);
for (SecurityGroupVMMapVO mapVO : groupsForVm) { for (SecurityGroupVMMapVO mapVO : groupsForVm) {
List<IngressRuleVO> rules = _ingressRuleDao.listBySecurityGroupId(mapVO.getSecurityGroupId()); List<SecurityGroupRuleVO> rules = _securityGroupRuleDao.listBySecurityGroupId(mapVO.getSecurityGroupId(), type);
for (IngressRuleVO rule : rules) { for (SecurityGroupRuleVO rule : rules) {
PortAndProto portAndProto = new PortAndProto(rule.getProtocol(), rule.getStartPort(), rule.getEndPort()); PortAndProto portAndProto = new PortAndProto(rule.getProtocol(), rule.getStartPort(), rule.getEndPort());
Set<String> cidrs = allowed.get(portAndProto); Set<String> cidrs = allowed.get(portAndProto);
if (cidrs == null) { if (cidrs == null) {

View File

@ -14,6 +14,7 @@ import com.cloud.network.security.LocalSecurityGroupWorkQueue.LocalSecurityGroup
import com.cloud.network.security.SecurityGroupWork.Step; import com.cloud.network.security.SecurityGroupWork.Step;
import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine.Type; import com.cloud.vm.VirtualMachine.Type;
import com.cloud.network.security.SecurityRule.SecurityRuleType;
public class SecurityManagerMBeanImpl extends StandardMBean implements SecurityGroupManagerMBean, RuleUpdateLog { public class SecurityManagerMBeanImpl extends StandardMBean implements SecurityGroupManagerMBean, RuleUpdateLog {
SecurityGroupManagerImpl2 _sgMgr; SecurityGroupManagerImpl2 _sgMgr;
@ -118,7 +119,8 @@ public class SecurityManagerMBeanImpl extends StandardMBean implements SecurityG
@Override @Override
public void tryRulesetUpdateForVmBypassSchedulerVeryDangerous(Long vmId, Long seqno) { public void tryRulesetUpdateForVmBypassSchedulerVeryDangerous(Long vmId, Long seqno) {
LocalSecurityGroupWork work = new LocalSecurityGroupWorkQueue.LocalSecurityGroupWork(vmId, seqno, Step.Scheduled); LocalSecurityGroupWork work = new LocalSecurityGroupWorkQueue.LocalSecurityGroupWork(vmId, seqno, Step.Scheduled);
_sgMgr.sendRulesetUpdates(work); _sgMgr.sendRulesetUpdates(work, SecurityRuleType.IngressRule);
_sgMgr.sendRulesetUpdates(work, SecurityRuleType.EgressRule);
} }
@Override @Override

View File

@ -1,36 +0,0 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.network.security.dao;
import java.util.List;
import com.cloud.network.security.EgressRuleVO;
import com.cloud.utils.db.GenericDao;
public interface EgressRuleDao extends GenericDao<EgressRuleVO, Long> {
List<EgressRuleVO> listBySecurityGroupId(long networkGroupId);
List<EgressRuleVO> listByAllowedSecurityGroupId(long networkGroupId);
EgressRuleVO findByProtoPortsAndCidr(long networkGroupId, String proto, int startPort, int endPort, String cidr);
EgressRuleVO findByProtoPortsAndGroup(String proto, int startPort, int endPort, String networkGroup);
EgressRuleVO findByProtoPortsAndAllowedGroupId(long networkGroupId, String proto, int startPort, int endPort, Long allowedGroupId);
int deleteBySecurityGroup(long securityGroupId);
int deleteByPortProtoAndGroup(long securityGroupId, String protocol, int startPort,int endPort, Long id);
int deleteByPortProtoAndCidr(long securityGroupId, String protocol, int startPort,int endPort, String cidr);
}

View File

@ -1,167 +0,0 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.network.security.dao;
import java.util.List;
import java.util.Map;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import com.cloud.network.security.EgressRuleVO;
import com.cloud.network.security.SecurityGroupVO;
import com.cloud.utils.component.Inject;
import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.JoinBuilder;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
@Local(value={EgressRuleDao.class})
public class EgressRuleDaoImpl extends GenericDaoBase<EgressRuleVO, Long> implements EgressRuleDao {
@Inject SecurityGroupDao _securityGroupDao;
protected SearchBuilder<EgressRuleVO> securityGroupIdSearch;
protected SearchBuilder<EgressRuleVO> allowedSecurityGroupIdSearch;
protected SearchBuilder<EgressRuleVO> protoPortsAndCidrSearch;
protected SearchBuilder<EgressRuleVO> protoPortsAndSecurityGroupNameSearch;
protected SearchBuilder<EgressRuleVO> protoPortsAndSecurityGroupIdSearch;
protected EgressRuleDaoImpl() {
securityGroupIdSearch = createSearchBuilder();
securityGroupIdSearch.and("securityGroupId", securityGroupIdSearch.entity().getSecurityGroupId(), SearchCriteria.Op.EQ);
securityGroupIdSearch.done();
allowedSecurityGroupIdSearch = createSearchBuilder();
allowedSecurityGroupIdSearch.and("allowedNetworkId", allowedSecurityGroupIdSearch.entity().getAllowedNetworkId(), SearchCriteria.Op.EQ);
allowedSecurityGroupIdSearch.done();
protoPortsAndCidrSearch = createSearchBuilder();
protoPortsAndCidrSearch.and("securityGroupId", protoPortsAndCidrSearch.entity().getSecurityGroupId(), SearchCriteria.Op.EQ);
protoPortsAndCidrSearch.and("proto", protoPortsAndCidrSearch.entity().getProtocol(), SearchCriteria.Op.EQ);
protoPortsAndCidrSearch.and("startPort", protoPortsAndCidrSearch.entity().getStartPort(), SearchCriteria.Op.EQ);
protoPortsAndCidrSearch.and("endPort", protoPortsAndCidrSearch.entity().getEndPort(), SearchCriteria.Op.EQ);
protoPortsAndCidrSearch.and("cidr", protoPortsAndCidrSearch.entity().getAllowedDestinationIpCidr(), SearchCriteria.Op.EQ);
protoPortsAndCidrSearch.done();
protoPortsAndSecurityGroupIdSearch = createSearchBuilder();
protoPortsAndSecurityGroupIdSearch.and("securityGroupId", protoPortsAndSecurityGroupIdSearch.entity().getSecurityGroupId(), SearchCriteria.Op.EQ);
protoPortsAndSecurityGroupIdSearch.and("proto", protoPortsAndSecurityGroupIdSearch.entity().getProtocol(), SearchCriteria.Op.EQ);
protoPortsAndSecurityGroupIdSearch.and("startPort", protoPortsAndSecurityGroupIdSearch.entity().getStartPort(), SearchCriteria.Op.EQ);
protoPortsAndSecurityGroupIdSearch.and("endPort", protoPortsAndSecurityGroupIdSearch.entity().getEndPort(), SearchCriteria.Op.EQ);
protoPortsAndSecurityGroupIdSearch.and("allowedNetworkId", protoPortsAndSecurityGroupIdSearch.entity().getAllowedNetworkId(), SearchCriteria.Op.EQ);
}
public List<EgressRuleVO> listBySecurityGroupId(long securityGroupId) {
SearchCriteria<EgressRuleVO> sc = securityGroupIdSearch.create();
sc.setParameters("securityGroupId", securityGroupId);
return listBy(sc);
}
public int deleteBySecurityGroup(long securityGroupId) {
SearchCriteria<EgressRuleVO> sc = securityGroupIdSearch.create();
sc.setParameters("securityGroupId", securityGroupId);
return expunge(sc);
}
@Override
public List<EgressRuleVO> listByAllowedSecurityGroupId(long securityGroupId) {
SearchCriteria<EgressRuleVO> sc = allowedSecurityGroupIdSearch.create();
sc.setParameters("allowedNetworkId", securityGroupId);
return listBy(sc);
}
@Override
public EgressRuleVO findByProtoPortsAndCidr(long securityGroupId, String proto, int startPort,
int endPort, String cidr) {
SearchCriteria<EgressRuleVO> sc = protoPortsAndCidrSearch.create();
sc.setParameters("securityGroupId", securityGroupId);
sc.setParameters("proto", proto);
sc.setParameters("startPort", startPort);
sc.setParameters("endPort", endPort);
sc.setParameters("cidr", cidr);
return findOneIncludingRemovedBy(sc);
}
@Override
public EgressRuleVO findByProtoPortsAndGroup(String proto, int startPort,
int endPort, String securityGroup) {
SearchCriteria<EgressRuleVO> sc = protoPortsAndSecurityGroupNameSearch.create();
sc.setParameters("proto", proto);
sc.setParameters("startPort", startPort);
sc.setParameters("endPort", endPort);
sc.setJoinParameters("groupName", "groupName", securityGroup);
return findOneIncludingRemovedBy(sc);
}
@Override
public boolean configure(String name, Map<String, Object> params)
throws ConfigurationException {
protoPortsAndSecurityGroupNameSearch = createSearchBuilder();
protoPortsAndSecurityGroupNameSearch.and("proto", protoPortsAndSecurityGroupNameSearch.entity().getProtocol(), SearchCriteria.Op.EQ);
protoPortsAndSecurityGroupNameSearch.and("startPort", protoPortsAndSecurityGroupNameSearch.entity().getStartPort(), SearchCriteria.Op.EQ);
protoPortsAndSecurityGroupNameSearch.and("endPort", protoPortsAndSecurityGroupNameSearch.entity().getEndPort(), SearchCriteria.Op.EQ);
SearchBuilder<SecurityGroupVO> ngSb = _securityGroupDao.createSearchBuilder();
ngSb.and("groupName", ngSb.entity().getName(), SearchCriteria.Op.EQ);
protoPortsAndSecurityGroupNameSearch.join("groupName", ngSb, protoPortsAndSecurityGroupNameSearch.entity().getAllowedNetworkId(), ngSb.entity().getId(), JoinBuilder.JoinType.INNER);
protoPortsAndSecurityGroupNameSearch.done();
return super.configure(name, params);
}
@Override
public int deleteByPortProtoAndGroup(long securityGroupId, String protocol, int startPort, int endPort, Long allowedGroupId) {
SearchCriteria<EgressRuleVO> sc = protoPortsAndSecurityGroupIdSearch.create();
sc.setParameters("securityGroupId", securityGroupId);
sc.setParameters("proto", protocol);
sc.setParameters("startPort", startPort);
sc.setParameters("endPort", endPort);
sc.setParameters("allowedNetworkId", allowedGroupId);
return expunge(sc);
}
@Override
public int deleteByPortProtoAndCidr(long securityGroupId, String protocol, int startPort, int endPort, String cidr) {
SearchCriteria<EgressRuleVO> sc = protoPortsAndCidrSearch.create();
sc.setParameters("securityGroupId", securityGroupId);
sc.setParameters("proto", protocol);
sc.setParameters("startPort", startPort);
sc.setParameters("endPort", endPort);
sc.setParameters("cidr", cidr);
return expunge(sc);
}
@Override
public EgressRuleVO findByProtoPortsAndAllowedGroupId(long securityGroupId, String proto,
int startPort, int endPort, Long allowedGroupId) {
SearchCriteria<EgressRuleVO> sc = protoPortsAndSecurityGroupIdSearch.create();
sc.addAnd("securityGroupId", SearchCriteria.Op.EQ, securityGroupId);
sc.setParameters("proto", proto);
sc.setParameters("startPort", startPort);
sc.setParameters("endPort", endPort);
sc.setParameters("allowedNetworkId", allowedGroupId);
return findOneIncludingRemovedBy(sc);
}
}

View File

@ -20,15 +20,16 @@ package com.cloud.network.security.dao;
import java.util.List; import java.util.List;
import com.cloud.network.security.IngressRuleVO; import com.cloud.network.security.SecurityGroupRuleVO;
import com.cloud.network.security.SecurityRule.SecurityRuleType;
import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.GenericDao;
public interface IngressRuleDao extends GenericDao<IngressRuleVO, Long> { public interface SecurityGroupRuleDao extends GenericDao<SecurityGroupRuleVO, Long> {
List<IngressRuleVO> listBySecurityGroupId(long networkGroupId); List<SecurityGroupRuleVO> listBySecurityGroupId(long securityGroupId, SecurityRuleType type);
List<IngressRuleVO> listByAllowedSecurityGroupId(long networkGroupId); List<SecurityGroupRuleVO> listByAllowedSecurityGroupId(long networkGroupId);
IngressRuleVO findByProtoPortsAndCidr(long networkGroupId, String proto, int startPort, int endPort, String cidr); SecurityGroupRuleVO findByProtoPortsAndCidr(long networkGroupId, String proto, int startPort, int endPort, String cidr);
IngressRuleVO findByProtoPortsAndGroup(String proto, int startPort, int endPort, String networkGroup); SecurityGroupRuleVO findByProtoPortsAndGroup(String proto, int startPort, int endPort, String networkGroup);
IngressRuleVO findByProtoPortsAndAllowedGroupId(long networkGroupId, String proto, int startPort, int endPort, Long allowedGroupId); SecurityGroupRuleVO findByProtoPortsAndAllowedGroupId(long networkGroupId, String proto, int startPort, int endPort, Long allowedGroupId);
int deleteBySecurityGroup(long securityGroupId); int deleteBySecurityGroup(long securityGroupId);
int deleteByPortProtoAndGroup(long securityGroupId, String protocol, int startPort,int endPort, Long id); int deleteByPortProtoAndGroup(long securityGroupId, String protocol, int startPort,int endPort, Long id);
int deleteByPortProtoAndCidr(long securityGroupId, String protocol, int startPort,int endPort, String cidr); int deleteByPortProtoAndCidr(long securityGroupId, String protocol, int startPort,int endPort, String cidr);

View File

@ -24,32 +24,39 @@ import java.util.Map;
import javax.ejb.Local; import javax.ejb.Local;
import javax.naming.ConfigurationException; import javax.naming.ConfigurationException;
import com.cloud.network.security.IngressRuleVO; import com.cloud.network.security.SecurityGroupRuleVO;
import com.cloud.network.security.SecurityGroupVO; import com.cloud.network.security.SecurityGroupVO;
import com.cloud.network.security.SecurityRule.SecurityRuleType;
import com.cloud.utils.component.Inject; import com.cloud.utils.component.Inject;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.JoinBuilder; import com.cloud.utils.db.JoinBuilder;
import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria;
@Local(value={IngressRuleDao.class}) @Local(value={SecurityGroupRuleDao.class})
public class IngressRuleDaoImpl extends GenericDaoBase<IngressRuleVO, Long> implements IngressRuleDao { public class SecurityGroupRuleDaoImpl extends GenericDaoBase<SecurityGroupRuleVO, Long> implements SecurityGroupRuleDao {
@Inject SecurityGroupDao _securityGroupDao; @Inject SecurityGroupDao _securityGroupDao;
protected SearchBuilder<IngressRuleVO> securityGroupIdSearch; protected SearchBuilder<SecurityGroupRuleVO> securityGroupIdSearch;
protected SearchBuilder<IngressRuleVO> allowedSecurityGroupIdSearch; protected SearchBuilder<SecurityGroupRuleVO> securityGroupIdAndTypeSearch;
protected SearchBuilder<IngressRuleVO> protoPortsAndCidrSearch; protected SearchBuilder<SecurityGroupRuleVO> allowedSecurityGroupIdSearch;
protected SearchBuilder<IngressRuleVO> protoPortsAndSecurityGroupNameSearch; protected SearchBuilder<SecurityGroupRuleVO> protoPortsAndCidrSearch;
protected SearchBuilder<IngressRuleVO> protoPortsAndSecurityGroupIdSearch; protected SearchBuilder<SecurityGroupRuleVO> protoPortsAndSecurityGroupNameSearch;
protected SearchBuilder<SecurityGroupRuleVO> protoPortsAndSecurityGroupIdSearch;
protected IngressRuleDaoImpl() { protected SecurityGroupRuleDaoImpl() {
securityGroupIdSearch = createSearchBuilder(); securityGroupIdSearch = createSearchBuilder();
securityGroupIdSearch.and("securityGroupId", securityGroupIdSearch.entity().getSecurityGroupId(), SearchCriteria.Op.EQ); securityGroupIdSearch.and("securityGroupId", securityGroupIdSearch.entity().getSecurityGroupId(), SearchCriteria.Op.EQ);
securityGroupIdSearch.done(); securityGroupIdSearch.done();
securityGroupIdAndTypeSearch = createSearchBuilder();
securityGroupIdAndTypeSearch.and("securityGroupId", securityGroupIdAndTypeSearch.entity().getSecurityGroupId(), SearchCriteria.Op.EQ);
securityGroupIdAndTypeSearch.and("type", securityGroupIdAndTypeSearch.entity().getType(), SearchCriteria.Op.EQ);
securityGroupIdAndTypeSearch.done();
allowedSecurityGroupIdSearch = createSearchBuilder(); allowedSecurityGroupIdSearch = createSearchBuilder();
allowedSecurityGroupIdSearch.and("allowedNetworkId", allowedSecurityGroupIdSearch.entity().getAllowedNetworkId(), SearchCriteria.Op.EQ); allowedSecurityGroupIdSearch.and("allowedNetworkId", allowedSecurityGroupIdSearch.entity().getAllowedNetworkId(), SearchCriteria.Op.EQ);
allowedSecurityGroupIdSearch.done(); allowedSecurityGroupIdSearch.done();
@ -71,29 +78,37 @@ public class IngressRuleDaoImpl extends GenericDaoBase<IngressRuleVO, Long> impl
} }
public List<IngressRuleVO> listBySecurityGroupId(long securityGroupId) { public List<SecurityGroupRuleVO> listBySecurityGroupId(long securityGroupId, SecurityRuleType type) {
SearchCriteria<IngressRuleVO> sc = securityGroupIdSearch.create(); SearchCriteria<SecurityGroupRuleVO> sc = securityGroupIdAndTypeSearch.create();
sc.setParameters("securityGroupId", securityGroupId); sc.setParameters("securityGroupId", securityGroupId);
String dbType;
if (type == SecurityRuleType.EgressRule) {
dbType = SecurityRuleType.EgressRule.getType();
}else {
dbType = SecurityRuleType.IngressRule.getType();
}
sc.setParameters("type", dbType);
return listBy(sc); return listBy(sc);
} }
public int deleteBySecurityGroup(long securityGroupId) { public int deleteBySecurityGroup(long securityGroupId) {
SearchCriteria<IngressRuleVO> sc = securityGroupIdSearch.create(); SearchCriteria<SecurityGroupRuleVO> sc = securityGroupIdSearch.create();
sc.setParameters("securityGroupId", securityGroupId); sc.setParameters("securityGroupId", securityGroupId);
return expunge(sc); return expunge(sc);
} }
@Override @Override
public List<IngressRuleVO> listByAllowedSecurityGroupId(long securityGroupId) { public List<SecurityGroupRuleVO> listByAllowedSecurityGroupId(long securityGroupId) {
SearchCriteria<IngressRuleVO> sc = allowedSecurityGroupIdSearch.create(); SearchCriteria<SecurityGroupRuleVO> sc = allowedSecurityGroupIdSearch.create();
sc.setParameters("allowedNetworkId", securityGroupId); sc.setParameters("allowedNetworkId", securityGroupId);
return listBy(sc); return listBy(sc);
} }
@Override @Override
public IngressRuleVO findByProtoPortsAndCidr(long securityGroupId, String proto, int startPort, public SecurityGroupRuleVO findByProtoPortsAndCidr(long securityGroupId, String proto, int startPort,
int endPort, String cidr) { int endPort, String cidr) {
SearchCriteria<IngressRuleVO> sc = protoPortsAndCidrSearch.create(); SearchCriteria<SecurityGroupRuleVO> sc = protoPortsAndCidrSearch.create();
sc.setParameters("securityGroupId", securityGroupId); sc.setParameters("securityGroupId", securityGroupId);
sc.setParameters("proto", proto); sc.setParameters("proto", proto);
sc.setParameters("startPort", startPort); sc.setParameters("startPort", startPort);
@ -103,9 +118,9 @@ public class IngressRuleDaoImpl extends GenericDaoBase<IngressRuleVO, Long> impl
} }
@Override @Override
public IngressRuleVO findByProtoPortsAndGroup(String proto, int startPort, public SecurityGroupRuleVO findByProtoPortsAndGroup(String proto, int startPort,
int endPort, String securityGroup) { int endPort, String securityGroup) {
SearchCriteria<IngressRuleVO> sc = protoPortsAndSecurityGroupNameSearch.create(); SearchCriteria<SecurityGroupRuleVO> sc = protoPortsAndSecurityGroupNameSearch.create();
sc.setParameters("proto", proto); sc.setParameters("proto", proto);
sc.setParameters("startPort", startPort); sc.setParameters("startPort", startPort);
sc.setParameters("endPort", endPort); sc.setParameters("endPort", endPort);
@ -129,7 +144,7 @@ public class IngressRuleDaoImpl extends GenericDaoBase<IngressRuleVO, Long> impl
@Override @Override
public int deleteByPortProtoAndGroup(long securityGroupId, String protocol, int startPort, int endPort, Long allowedGroupId) { public int deleteByPortProtoAndGroup(long securityGroupId, String protocol, int startPort, int endPort, Long allowedGroupId) {
SearchCriteria<IngressRuleVO> sc = protoPortsAndSecurityGroupIdSearch.create(); SearchCriteria<SecurityGroupRuleVO> sc = protoPortsAndSecurityGroupIdSearch.create();
sc.setParameters("securityGroupId", securityGroupId); sc.setParameters("securityGroupId", securityGroupId);
sc.setParameters("proto", protocol); sc.setParameters("proto", protocol);
sc.setParameters("startPort", startPort); sc.setParameters("startPort", startPort);
@ -142,7 +157,7 @@ public class IngressRuleDaoImpl extends GenericDaoBase<IngressRuleVO, Long> impl
@Override @Override
public int deleteByPortProtoAndCidr(long securityGroupId, String protocol, int startPort, int endPort, String cidr) { public int deleteByPortProtoAndCidr(long securityGroupId, String protocol, int startPort, int endPort, String cidr) {
SearchCriteria<IngressRuleVO> sc = protoPortsAndCidrSearch.create(); SearchCriteria<SecurityGroupRuleVO> sc = protoPortsAndCidrSearch.create();
sc.setParameters("securityGroupId", securityGroupId); sc.setParameters("securityGroupId", securityGroupId);
sc.setParameters("proto", protocol); sc.setParameters("proto", protocol);
sc.setParameters("startPort", startPort); sc.setParameters("startPort", startPort);
@ -153,9 +168,9 @@ public class IngressRuleDaoImpl extends GenericDaoBase<IngressRuleVO, Long> impl
} }
@Override @Override
public IngressRuleVO findByProtoPortsAndAllowedGroupId(long securityGroupId, String proto, public SecurityGroupRuleVO findByProtoPortsAndAllowedGroupId(long securityGroupId, String proto,
int startPort, int endPort, Long allowedGroupId) { int startPort, int endPort, Long allowedGroupId) {
SearchCriteria<IngressRuleVO> sc = protoPortsAndSecurityGroupIdSearch.create(); SearchCriteria<SecurityGroupRuleVO> sc = protoPortsAndSecurityGroupIdSearch.create();
sc.addAnd("securityGroupId", SearchCriteria.Op.EQ, securityGroupId); sc.addAnd("securityGroupId", SearchCriteria.Op.EQ, securityGroupId);
sc.setParameters("proto", proto); sc.setParameters("proto", proto);
sc.setParameters("startPort", startPort); sc.setParameters("startPort", startPort);

View File

@ -22,7 +22,7 @@ import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import com.cloud.api.response.IngressRuleResponse; import com.cloud.api.response.SecurityGroupRuleResponse;
public class UserVmData { public class UserVmData {
private Long id; private Long id;
@ -580,7 +580,7 @@ public class UserVmData {
private String domainName; private String domainName;
private Long jobId; private Long jobId;
private Integer jobStatus; private Integer jobStatus;
private List<IngressRuleResponse> ingressRules; private List<SecurityGroupRuleResponse> securityGroupRules;
public String getObjectName() { public String getObjectName() {
return objectName; return objectName;
@ -637,15 +637,14 @@ public class UserVmData {
public void setDomainName(String domainName) { public void setDomainName(String domainName) {
this.domainName = domainName; this.domainName = domainName;
} }
/* FIXME : the below functions are not used, so commenting out later need to include egress list
public List<IngressRuleResponse> getIngressRules() { public List<SecurityGroupRuleResponse> getIngressRules() {
return ingressRules; return securityGroupRules;
}
public void setIngressRules(List<IngressRuleResponse> ingressRules) {
this.ingressRules = ingressRules;
} }
public void setIngressRules(List<SecurityGroupRuleResponse> securityGroupRules) {
this.securityGroupRules = securityGroupRules;
} */
@Override @Override
public int hashCode() { public int hashCode() {

View File

@ -107,8 +107,7 @@ DROP TABLE IF EXISTS `cloud`.`ovs_vm_flow_log`;
DROP TABLE IF EXISTS `cloud`.`ovs_work`; DROP TABLE IF EXISTS `cloud`.`ovs_work`;
DROP TABLE IF EXISTS `cloud`.`remote_access_vpn`; DROP TABLE IF EXISTS `cloud`.`remote_access_vpn`;
DROP TABLE IF EXISTS `cloud`.`resource_count`; DROP TABLE IF EXISTS `cloud`.`resource_count`;
DROP TABLE IF EXISTS `cloud`.`security_ingress_rule`; DROP TABLE IF EXISTS `cloud`.`security_group_rule`;
DROP TABLE IF EXISTS `cloud`.`security_egress_rule`;
DROP TABLE IF EXISTS `cloud`.`stack_maid`; DROP TABLE IF EXISTS `cloud`.`stack_maid`;
DROP TABLE IF EXISTS `cloud`.`storage_pool_work`; DROP TABLE IF EXISTS `cloud`.`storage_pool_work`;
DROP TABLE IF EXISTS `cloud`.`user_vm_details`; DROP TABLE IF EXISTS `cloud`.`user_vm_details`;
@ -1516,10 +1515,11 @@ CREATE TABLE `cloud`.`security_group` (
CONSTRAINT `uc_security_group__uuid` UNIQUE (`uuid`) CONSTRAINT `uc_security_group__uuid` UNIQUE (`uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `cloud`.`security_ingress_rule` ( CREATE TABLE `cloud`.`security_group_rule` (
`id` bigint unsigned NOT NULL auto_increment, `id` bigint unsigned NOT NULL auto_increment,
`uuid` varchar(40), `uuid` varchar(40),
`security_group_id` bigint unsigned NOT NULL, `security_group_id` bigint unsigned NOT NULL,
`type` varchar(10) default 'ingress',
`start_port` varchar(10) default NULL, `start_port` varchar(10) default NULL,
`end_port` varchar(10) default NULL, `end_port` varchar(10) default NULL,
`protocol` varchar(16) NOT NULL default 'TCP', `protocol` varchar(16) NOT NULL default 'TCP',
@ -1527,21 +1527,7 @@ CREATE TABLE `cloud`.`security_ingress_rule` (
`allowed_ip_cidr` varchar(44), `allowed_ip_cidr` varchar(44),
`create_status` varchar(32) COMMENT 'rule creation status', `create_status` varchar(32) COMMENT 'rule creation status',
PRIMARY KEY (`id`), PRIMARY KEY (`id`),
CONSTRAINT `uc_security_ingress_rule__uuid` UNIQUE (`uuid`) CONSTRAINT `uc_security_group_rule__uuid` UNIQUE (`uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `cloud`.`security_egress_rule` (
`id` bigint unsigned NOT NULL auto_increment,
`uuid` varchar(40),
`security_group_id` bigint unsigned NOT NULL,
`start_port` varchar(10) default NULL,
`end_port` varchar(10) default NULL,
`protocol` varchar(16) NOT NULL default 'TCP',
`allowed_network_id` bigint unsigned,
`allowed_ip_cidr` varchar(44),
`create_status` varchar(32) COMMENT 'rule creation status',
PRIMARY KEY (`id`),
CONSTRAINT `uc_security_egress_rule__uuid` UNIQUE (`uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `cloud`.`security_group_vm_map` ( CREATE TABLE `cloud`.`security_group_vm_map` (

View File

@ -187,11 +187,9 @@ ALTER TABLE `cloud`.`firewall_rules` ADD CONSTRAINT `uc_firewall_rules__uuid` UN
ALTER TABLE `cloud`.`cluster` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`cluster` ADD COLUMN `uuid` varchar(40);
ALTER TABLE `cloud`.`cluster` ADD CONSTRAINT `uc_cluster__uuid` UNIQUE (`uuid`); ALTER TABLE `cloud`.`cluster` ADD CONSTRAINT `uc_cluster__uuid` UNIQUE (`uuid`);
ALTER TABLE `cloud`.`security_ingress_rule` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`security_group_rule` ADD COLUMN `uuid` varchar(40);
ALTER TABLE `cloud`.`security_ingress_rule` ADD CONSTRAINT `uc_security_ingress_rule__uuid` UNIQUE (`uuid`); ALTER TABLE `cloud`.`security_group_rule` ADD CONSTRAINT `uc_security_ingress_rule__uuid` UNIQUE (`uuid`);
ALTER TABLE `cloud`.`security_egress_rule` ADD COLUMN `uuid` varchar(40);
ALTER TABLE `cloud`.`security_egress_rule` ADD CONSTRAINT `uc_security_egress_rule__uuid` UNIQUE (`uuid`);
ALTER TABLE `cloud`.`network_offerings` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`network_offerings` ADD COLUMN `uuid` varchar(40);
ALTER TABLE `cloud`.`network_offerings` ADD CONSTRAINT `uc_network_offerings__uuid` UNIQUE (`uuid`); ALTER TABLE `cloud`.`network_offerings` ADD CONSTRAINT `uc_network_offerings__uuid` UNIQUE (`uuid`);
@ -217,3 +215,6 @@ ALTER TABLE `cloud`.`guest_os_category` ADD CONSTRAINT `uc_guest_os_category__uu
ALTER TABLE `cloud`.`nics` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`nics` ADD COLUMN `uuid` varchar(40);
ALTER TABLE `cloud`.`nics` ADD CONSTRAINT `uc_nics__uuid` UNIQUE (`uuid`); ALTER TABLE `cloud`.`nics` ADD CONSTRAINT `uc_nics__uuid` UNIQUE (`uuid`);
ALTER TABLE `cloud`.`security_ingress_rule` RENAME TO `security_group_rule`;
ALTER TABLE `cloud`.`security_group_rule` ADD COLUMN `type` varchar(10) default 'ingress' AFTER security_group_id;