Merge release branch 4.7 to 4.8

* 4.7:
  CLOUDSTACK-9254: Make longer names display pretty
  CLOUDSTACK-9245 - Deletes ACL items when destroying the VPC or deleting the ACL itself
  CLOUDSTACK-9245 - Formatting NetworkACLServiceImpl class
  CLOUDSTACK-9245 - Formatting VpcManagerImpl class
  CLOUDSTACK-9245 - Formatting NetworkACLManagerImpl class
  More VR performance!
This commit is contained in:
Remi Bergsma 2016-01-26 08:39:28 +01:00
commit 8c60ad214f
8 changed files with 473 additions and 448 deletions

View File

@ -96,9 +96,8 @@ public interface NetworkACLService {
Pair<List<? extends NetworkACLItem>, Integer> listNetworkACLItems(ListNetworkACLsCmd cmd); Pair<List<? extends NetworkACLItem>, Integer> listNetworkACLItems(ListNetworkACLsCmd cmd);
/** /**
* Revoked ACL Item with specified Id * Revoke ACL Item with specified Id
* @param ruleId * @param ruleId
* @param apply
* @return * @return
*/ */
boolean revokeNetworkACLItem(long ruleId); boolean revokeNetworkACLItem(long ruleId);
@ -121,7 +120,7 @@ public interface NetworkACLService {
* @throws ResourceUnavailableException * @throws ResourceUnavailableException
*/ */
NetworkACLItem updateNetworkACLItem(Long id, String protocol, List<String> sourceCidrList, NetworkACLItem.TrafficType trafficType, String action, Integer number, NetworkACLItem updateNetworkACLItem(Long id, String protocol, List<String> sourceCidrList, NetworkACLItem.TrafficType trafficType, String action, Integer number,
Integer sourcePortStart, Integer sourcePortEnd, Integer icmpCode, Integer icmpType, String newUUID, Boolean forDisplay) throws ResourceUnavailableException; Integer sourcePortStart, Integer sourcePortEnd, Integer icmpCode, Integer icmpType, String newUUID, Boolean forDisplay) throws ResourceUnavailableException;
/** /**
* Associates ACL with specified Network * Associates ACL with specified Network

View File

@ -86,8 +86,8 @@ public class NetworkACLManagerImpl extends ManagerBase implements NetworkACLMana
MessageBus _messageBus; MessageBus _messageBus;
@Override @Override
public NetworkACL createNetworkACL(String name, String description, long vpcId, Boolean forDisplay) { public NetworkACL createNetworkACL(final String name, final String description, final long vpcId, final Boolean forDisplay) {
NetworkACLVO acl = new NetworkACLVO(name, description, vpcId); final NetworkACLVO acl = new NetworkACLVO(name, description, vpcId);
if (forDisplay != null) { if (forDisplay != null) {
acl.setDisplay(forDisplay); acl.setDisplay(forDisplay);
} }
@ -95,23 +95,23 @@ public class NetworkACLManagerImpl extends ManagerBase implements NetworkACLMana
} }
@Override @Override
public boolean applyNetworkACL(long aclId) throws ResourceUnavailableException { public boolean applyNetworkACL(final long aclId) throws ResourceUnavailableException {
boolean handled = true; boolean handled = true;
boolean aclApplyStatus = true; boolean aclApplyStatus = true;
List<NetworkACLItemVO> rules = _networkACLItemDao.listByACL(aclId); final List<NetworkACLItemVO> rules = _networkACLItemDao.listByACL(aclId);
//Find all networks using this ACL and apply the ACL //Find all networks using this ACL and apply the ACL
List<NetworkVO> networks = _networkDao.listByAclId(aclId); final List<NetworkVO> networks = _networkDao.listByAclId(aclId);
for (NetworkVO network : networks) { for (final NetworkVO network : networks) {
if (!applyACLItemsToNetwork(network.getId(), rules)) { if (!applyACLItemsToNetwork(network.getId(), rules)) {
handled = false; handled = false;
break; break;
} }
} }
List<VpcGatewayVO> vpcGateways = _vpcGatewayDao.listByAclIdAndType(aclId, VpcGateway.Type.Private); final List<VpcGatewayVO> vpcGateways = _vpcGatewayDao.listByAclIdAndType(aclId, VpcGateway.Type.Private);
for (VpcGatewayVO vpcGateway : vpcGateways) { for (final VpcGatewayVO vpcGateway : vpcGateways) {
PrivateGateway privateGateway = _vpcSvc.getVpcPrivateGateway(vpcGateway.getId()); final PrivateGateway privateGateway = _vpcSvc.getVpcPrivateGateway(vpcGateway.getId());
if (!applyACLToPrivateGw(privateGateway)) { if (!applyACLToPrivateGw(privateGateway)) {
aclApplyStatus = false; aclApplyStatus = false;
@ -121,11 +121,11 @@ public class NetworkACLManagerImpl extends ManagerBase implements NetworkACLMana
} }
if (handled && aclApplyStatus) { if (handled && aclApplyStatus) {
for (NetworkACLItem rule : rules) { for (final NetworkACLItem rule : rules) {
if (rule.getState() == NetworkACLItem.State.Revoke) { if (rule.getState() == NetworkACLItem.State.Revoke) {
removeRule(rule); removeRule(rule);
} else if (rule.getState() == NetworkACLItem.State.Add) { } else if (rule.getState() == NetworkACLItem.State.Add) {
NetworkACLItemVO ruleVO = _networkACLItemDao.findById(rule.getId()); final NetworkACLItemVO ruleVO = _networkACLItemDao.findById(rule.getId());
ruleVO.setState(NetworkACLItem.State.Active); ruleVO.setState(NetworkACLItem.State.Active);
_networkACLItemDao.update(ruleVO.getId(), ruleVO); _networkACLItemDao.update(ruleVO.getId(), ruleVO);
} }
@ -135,35 +135,36 @@ public class NetworkACLManagerImpl extends ManagerBase implements NetworkACLMana
} }
@Override @Override
public NetworkACL getNetworkACL(long id) { public NetworkACL getNetworkACL(final long id) {
return _networkACLDao.findById(id); return _networkACLDao.findById(id);
} }
@Override @Override
public boolean deleteNetworkACL(NetworkACL acl) { public boolean deleteNetworkACL(final NetworkACL acl) {
List<NetworkACLItemVO> aclItems = _networkACLItemDao.listByACL(acl.getId()); final long aclId = acl.getId();
if (aclItems.size() > 0) { final List<NetworkVO> networks = _networkDao.listByAclId(aclId);
throw new CloudRuntimeException("ACL is not empty. Cannot delete network ACL: " + acl.getUuid());
}
List<NetworkVO> networks = _networkDao.listByAclId(acl.getId());
if (networks != null && networks.size() > 0) { if (networks != null && networks.size() > 0) {
throw new CloudRuntimeException("ACL is still associated with " + networks.size() + " tier(s). Cannot delete network ACL: " + acl.getUuid()); throw new CloudRuntimeException("ACL is still associated with " + networks.size() + " tier(s). Cannot delete network ACL: " + acl.getUuid());
} }
List<VpcGatewayVO> pvtGateways = _vpcGatewayDao.listByAclIdAndType(acl.getId(), VpcGateway.Type.Private); final List<VpcGatewayVO> pvtGateways = _vpcGatewayDao.listByAclIdAndType(aclId, VpcGateway.Type.Private);
if (pvtGateways != null && pvtGateways.size() > 0) { if (pvtGateways != null && pvtGateways.size() > 0) {
throw new CloudRuntimeException("ACL is still associated with " + pvtGateways.size() + " private gateway(s). Cannot delete network ACL: " + acl.getUuid()); throw new CloudRuntimeException("ACL is still associated with " + pvtGateways.size() + " private gateway(s). Cannot delete network ACL: " + acl.getUuid());
} }
return _networkACLDao.remove(acl.getId()); final List<NetworkACLItemVO> aclItems = _networkACLItemDao.listByACL(aclId);
for (final NetworkACLItemVO networkACLItem : aclItems) {
revokeNetworkACLItem(networkACLItem.getId());
}
return _networkACLDao.remove(aclId);
} }
@Override @Override
public boolean replaceNetworkACLForPrivateGw(NetworkACL acl, PrivateGateway gateway) throws ResourceUnavailableException { public boolean replaceNetworkACLForPrivateGw(final NetworkACL acl, final PrivateGateway gateway) throws ResourceUnavailableException {
VpcGatewayVO vpcGatewayVo = _vpcGatewayDao.findById(gateway.getId()); final VpcGatewayVO vpcGatewayVo = _vpcGatewayDao.findById(gateway.getId());
List<NetworkACLItemVO> aclItems = _networkACLItemDao.listByACL(acl.getId()); final List<NetworkACLItemVO> aclItems = _networkACLItemDao.listByACL(acl.getId());
if (aclItems == null || aclItems.isEmpty()) { if (aclItems == null || aclItems.isEmpty()) {
//Revoke ACL Items of the existing ACL if the new network acl is empty //Revoke ACL Items of the existing ACL if the new network acl is empty
//Other wise existing rules will not be removed on the router elelment //Other wise existing rules will not be removed on the router elelment
@ -182,9 +183,9 @@ public class NetworkACLManagerImpl extends ManagerBase implements NetworkACLMana
} }
@Override @Override
public boolean replaceNetworkACL(NetworkACL acl, NetworkVO network) throws ResourceUnavailableException { public boolean replaceNetworkACL(final NetworkACL acl, final NetworkVO network) throws ResourceUnavailableException {
NetworkOffering guestNtwkOff = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId()); final NetworkOffering guestNtwkOff = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId());
if (guestNtwkOff == null) { if (guestNtwkOff == null) {
throw new InvalidParameterValueException("Can't find network offering associated with network: " + network.getUuid()); throw new InvalidParameterValueException("Can't find network offering associated with network: " + network.getUuid());
@ -198,7 +199,7 @@ public class NetworkACLManagerImpl extends ManagerBase implements NetworkACLMana
if (network.getNetworkACLId() != null) { if (network.getNetworkACLId() != null) {
//Revoke ACL Items of the existing ACL if the new ACL is empty //Revoke ACL Items of the existing ACL if the new ACL is empty
//Existing rules won't be removed otherwise //Existing rules won't be removed otherwise
List<NetworkACLItemVO> aclItems = _networkACLItemDao.listByACL(acl.getId()); final List<NetworkACLItemVO> aclItems = _networkACLItemDao.listByACL(acl.getId());
if (aclItems == null || aclItems.isEmpty()) { if (aclItems == null || aclItems.isEmpty()) {
s_logger.debug("New network ACL is empty. Revoke existing rules before applying ACL"); s_logger.debug("New network ACL is empty. Revoke existing rules before applying ACL");
if (!revokeACLItemsForNetwork(network.getId())) { if (!revokeACLItemsForNetwork(network.getId())) {
@ -212,7 +213,7 @@ public class NetworkACLManagerImpl extends ManagerBase implements NetworkACLMana
if (_networkDao.update(network.getId(), network)) { if (_networkDao.update(network.getId(), network)) {
s_logger.debug("Updated network: " + network.getId() + " with Network ACL Id: " + acl.getId() + ", Applying ACL items"); s_logger.debug("Updated network: " + network.getId() + " with Network ACL Id: " + acl.getId() + ", Applying ACL items");
//Apply ACL to network //Apply ACL to network
Boolean result = applyACLToNetwork(network.getId()); final Boolean result = applyACLToNetwork(network.getId());
if (result) { if (result) {
// public message on message bus, so that network elements implementing distributed routing capability // public message on message bus, so that network elements implementing distributed routing capability
// can act on the event // can act on the event
@ -234,16 +235,16 @@ public class NetworkACLManagerImpl extends ManagerBase implements NetworkACLMana
} }
final Integer numberFinal = number; final Integer numberFinal = number;
NetworkACLItemVO newRule = Transaction.execute(new TransactionCallback<NetworkACLItemVO>() { final NetworkACLItemVO newRule = Transaction.execute(new TransactionCallback<NetworkACLItemVO>() {
@Override @Override
public NetworkACLItemVO doInTransaction(TransactionStatus status) { public NetworkACLItemVO doInTransaction(final TransactionStatus status) {
NetworkACLItem.Action ruleAction = NetworkACLItem.Action.Allow; NetworkACLItem.Action ruleAction = NetworkACLItem.Action.Allow;
if ("deny".equalsIgnoreCase(action)) { if ("deny".equalsIgnoreCase(action)) {
ruleAction = NetworkACLItem.Action.Deny; ruleAction = NetworkACLItem.Action.Deny;
} }
NetworkACLItemVO newRule = NetworkACLItemVO newRule =
new NetworkACLItemVO(portStart, portEnd, protocol.toLowerCase(), aclId, sourceCidrList, icmpCode, icmpType, trafficType, ruleAction, numberFinal); new NetworkACLItemVO(portStart, portEnd, protocol.toLowerCase(), aclId, sourceCidrList, icmpCode, icmpType, trafficType, ruleAction, numberFinal);
if (forDisplay != null) { if (forDisplay != null) {
newRule.setDisplay(forDisplay); newRule.setDisplay(forDisplay);
@ -264,14 +265,14 @@ public class NetworkACLManagerImpl extends ManagerBase implements NetworkACLMana
} }
@Override @Override
public NetworkACLItem getNetworkACLItem(long ruleId) { public NetworkACLItem getNetworkACLItem(final long ruleId) {
return _networkACLItemDao.findById(ruleId); return _networkACLItemDao.findById(ruleId);
} }
@Override @Override
public boolean revokeNetworkACLItem(long ruleId) { public boolean revokeNetworkACLItem(final long ruleId) {
NetworkACLItemVO rule = _networkACLItemDao.findById(ruleId); final NetworkACLItemVO rule = _networkACLItemDao.findById(ruleId);
revokeRule(rule); revokeRule(rule);
@ -280,7 +281,7 @@ public class NetworkACLManagerImpl extends ManagerBase implements NetworkACLMana
try { try {
applyNetworkACL(rule.getAclId()); applyNetworkACL(rule.getAclId());
success = true; success = true;
} catch (ResourceUnavailableException e) { } catch (final ResourceUnavailableException e) {
return false; return false;
} }
@ -288,7 +289,7 @@ public class NetworkACLManagerImpl extends ManagerBase implements NetworkACLMana
} }
@DB @DB
private void revokeRule(NetworkACLItemVO rule) { private void revokeRule(final NetworkACLItemVO rule) {
if (rule.getState() == State.Staged) { if (rule.getState() == State.Staged) {
if (s_logger.isDebugEnabled()) { if (s_logger.isDebugEnabled()) {
s_logger.debug("Found a rule that is still in stage state so just removing it: " + rule); s_logger.debug("Found a rule that is still in stage state so just removing it: " + rule);
@ -301,12 +302,12 @@ public class NetworkACLManagerImpl extends ManagerBase implements NetworkACLMana
} }
@Override @Override
public boolean revokeACLItemsForNetwork(long networkId) throws ResourceUnavailableException { public boolean revokeACLItemsForNetwork(final long networkId) throws ResourceUnavailableException {
Network network = _networkDao.findById(networkId); final Network network = _networkDao.findById(networkId);
if (network.getNetworkACLId() == null) { if (network.getNetworkACLId() == null) {
return true; return true;
} }
List<NetworkACLItemVO> aclItems = _networkACLItemDao.listByACL(network.getNetworkACLId()); final List<NetworkACLItemVO> aclItems = _networkACLItemDao.listByACL(network.getNetworkACLId());
if (aclItems.isEmpty()) { if (aclItems.isEmpty()) {
s_logger.debug("Found no network ACL Items for network id=" + networkId); s_logger.debug("Found no network ACL Items for network id=" + networkId);
return true; return true;
@ -316,14 +317,14 @@ public class NetworkACLManagerImpl extends ManagerBase implements NetworkACLMana
s_logger.debug("Releasing " + aclItems.size() + " Network ACL Items for network id=" + networkId); s_logger.debug("Releasing " + aclItems.size() + " Network ACL Items for network id=" + networkId);
} }
for (NetworkACLItemVO aclItem : aclItems) { for (final NetworkACLItemVO aclItem : aclItems) {
// Mark all Network ACLs rules as Revoke, but don't update in DB // Mark all Network ACLs rules as Revoke, but don't update in DB
if (aclItem.getState() == State.Add || aclItem.getState() == State.Active) { if (aclItem.getState() == State.Add || aclItem.getState() == State.Active) {
aclItem.setState(State.Revoke); aclItem.setState(State.Revoke);
} }
} }
boolean success = applyACLItemsToNetwork(network.getId(), aclItems); final boolean success = applyACLItemsToNetwork(network.getId(), aclItems);
if (s_logger.isDebugEnabled() && success) { if (s_logger.isDebugEnabled() && success) {
s_logger.debug("Successfully released Network ACLs for network id=" + networkId + " and # of rules now = " + aclItems.size()); s_logger.debug("Successfully released Network ACLs for network id=" + networkId + " and # of rules now = " + aclItems.size());
@ -333,9 +334,9 @@ public class NetworkACLManagerImpl extends ManagerBase implements NetworkACLMana
} }
@Override @Override
public boolean revokeACLItemsForPrivateGw(PrivateGateway gateway) throws ResourceUnavailableException { public boolean revokeACLItemsForPrivateGw(final PrivateGateway gateway) throws ResourceUnavailableException {
List<NetworkACLItemVO> aclItems = _networkACLItemDao.listByACL(gateway.getNetworkACLId()); final List<NetworkACLItemVO> aclItems = _networkACLItemDao.listByACL(gateway.getNetworkACLId());
if (aclItems.isEmpty()) { if (aclItems.isEmpty()) {
s_logger.debug("Found no network ACL Items for private gateway id=" + gateway.getId()); s_logger.debug("Found no network ACL Items for private gateway id=" + gateway.getId());
return true; return true;
@ -345,14 +346,14 @@ public class NetworkACLManagerImpl extends ManagerBase implements NetworkACLMana
s_logger.debug("Releasing " + aclItems.size() + " Network ACL Items for private gateway id=" + gateway.getId()); s_logger.debug("Releasing " + aclItems.size() + " Network ACL Items for private gateway id=" + gateway.getId());
} }
for (NetworkACLItemVO aclItem : aclItems) { for (final NetworkACLItemVO aclItem : aclItems) {
// Mark all Network ACLs rules as Revoke, but don't update in DB // Mark all Network ACLs rules as Revoke, but don't update in DB
if (aclItem.getState() == State.Add || aclItem.getState() == State.Active) { if (aclItem.getState() == State.Add || aclItem.getState() == State.Active) {
aclItem.setState(State.Revoke); aclItem.setState(State.Revoke);
} }
} }
boolean success = applyACLToPrivateGw(gateway, aclItems); final boolean success = applyACLToPrivateGw(gateway, aclItems);
if (s_logger.isDebugEnabled() && success) { if (s_logger.isDebugEnabled() && success) {
s_logger.debug("Successfully released Network ACLs for private gateway id=" + gateway.getId() + " and # of rules now = " + aclItems.size()); s_logger.debug("Successfully released Network ACLs for private gateway id=" + gateway.getId() + " and # of rules now = " + aclItems.size());
@ -362,27 +363,27 @@ public class NetworkACLManagerImpl extends ManagerBase implements NetworkACLMana
} }
@Override @Override
public List<NetworkACLItemVO> listNetworkACLItems(long guestNtwkId) { public List<NetworkACLItemVO> listNetworkACLItems(final long guestNtwkId) {
Network network = _networkMgr.getNetwork(guestNtwkId); final Network network = _networkMgr.getNetwork(guestNtwkId);
if (network.getNetworkACLId() == null) { if (network.getNetworkACLId() == null) {
return null; return null;
} }
return _networkACLItemDao.listByACL(network.getNetworkACLId()); return _networkACLItemDao.listByACL(network.getNetworkACLId());
} }
private void removeRule(NetworkACLItem rule) { private void removeRule(final NetworkACLItem rule) {
//remove the rule //remove the rule
_networkACLItemDao.remove(rule.getId()); _networkACLItemDao.remove(rule.getId());
} }
@Override @Override
public boolean applyACLToPrivateGw(PrivateGateway gateway) throws ResourceUnavailableException { public boolean applyACLToPrivateGw(final PrivateGateway gateway) throws ResourceUnavailableException {
VpcGatewayVO vpcGatewayVO = _vpcGatewayDao.findById(gateway.getId()); final VpcGatewayVO vpcGatewayVO = _vpcGatewayDao.findById(gateway.getId());
List<? extends NetworkACLItem> rules = _networkACLItemDao.listByACL(vpcGatewayVO.getNetworkACLId()); final List<? extends NetworkACLItem> rules = _networkACLItemDao.listByACL(vpcGatewayVO.getNetworkACLId());
return applyACLToPrivateGw(gateway, rules); return applyACLToPrivateGw(gateway, rules);
} }
private boolean applyACLToPrivateGw(PrivateGateway gateway, List<? extends NetworkACLItem> rules) throws ResourceUnavailableException { private boolean applyACLToPrivateGw(final PrivateGateway gateway, final List<? extends NetworkACLItem> rules) throws ResourceUnavailableException {
List<VpcProvider> vpcElements = null; List<VpcProvider> vpcElements = null;
vpcElements = new ArrayList<VpcProvider>(); vpcElements = new ArrayList<VpcProvider>();
vpcElements.add((VpcProvider)_ntwkModel.getElementImplementingProvider(Network.Provider.VPCVirtualRouter.getName())); vpcElements.add((VpcProvider)_ntwkModel.getElementImplementingProvider(Network.Provider.VPCVirtualRouter.getName()));
@ -392,29 +393,29 @@ public class NetworkACLManagerImpl extends ManagerBase implements NetworkACLMana
} }
try{ try{
for (VpcProvider provider : vpcElements) { for (final VpcProvider provider : vpcElements) {
return provider.applyACLItemsToPrivateGw(gateway, rules); return provider.applyACLItemsToPrivateGw(gateway, rules);
} }
} catch(Exception ex) { } catch(final Exception ex) {
s_logger.debug("Failed to apply acl to private gateway " + gateway); s_logger.debug("Failed to apply acl to private gateway " + gateway);
} }
return false; return false;
} }
@Override @Override
public boolean applyACLToNetwork(long networkId) throws ResourceUnavailableException { public boolean applyACLToNetwork(final long networkId) throws ResourceUnavailableException {
Network network = _networkDao.findById(networkId); final Network network = _networkDao.findById(networkId);
if (network.getNetworkACLId() == null) { if (network.getNetworkACLId() == null) {
return true; return true;
} }
List<NetworkACLItemVO> rules = _networkACLItemDao.listByACL(network.getNetworkACLId()); final List<NetworkACLItemVO> rules = _networkACLItemDao.listByACL(network.getNetworkACLId());
return applyACLItemsToNetwork(networkId, rules); return applyACLItemsToNetwork(networkId, rules);
} }
@Override @Override
public NetworkACLItem updateNetworkACLItem(Long id, String protocol, List<String> sourceCidrList, NetworkACLItem.TrafficType trafficType, String action, public NetworkACLItem updateNetworkACLItem(final Long id, final String protocol, final List<String> sourceCidrList, final NetworkACLItem.TrafficType trafficType, final String action,
Integer number, Integer sourcePortStart, Integer sourcePortEnd, Integer icmpCode, Integer icmpType, String customId, Boolean forDisplay) throws ResourceUnavailableException { final Integer number, final Integer sourcePortStart, final Integer sourcePortEnd, final Integer icmpCode, final Integer icmpType, final String customId, final Boolean forDisplay) throws ResourceUnavailableException {
NetworkACLItemVO aclItem = _networkACLItemDao.findById(id); final NetworkACLItemVO aclItem = _networkACLItemDao.findById(id);
aclItem.setState(State.Add); aclItem.setState(State.Add);
if (protocol != null) { if (protocol != null) {
@ -475,13 +476,13 @@ public class NetworkACLManagerImpl extends ManagerBase implements NetworkACLMana
return null; return null;
} }
public boolean applyACLItemsToNetwork(long networkId, List<NetworkACLItemVO> rules) throws ResourceUnavailableException { public boolean applyACLItemsToNetwork(final long networkId, final List<NetworkACLItemVO> rules) throws ResourceUnavailableException {
Network network = _networkDao.findById(networkId); final Network network = _networkDao.findById(networkId);
boolean handled = false; boolean handled = false;
boolean foundProvider = false; boolean foundProvider = false;
for (NetworkACLServiceProvider element : _networkAclElements) { for (final NetworkACLServiceProvider element : _networkAclElements) {
Network.Provider provider = element.getProvider(); final Network.Provider provider = element.getProvider();
boolean isAclProvider = _networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.NetworkACL, provider); final boolean isAclProvider = _networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.NetworkACL, provider);
if (!isAclProvider) { if (!isAclProvider) {
continue; continue;
} }
@ -506,8 +507,8 @@ public class NetworkACLManagerImpl extends ManagerBase implements NetworkACLMana
} }
@Inject @Inject
public void setNetworkAclElements(List<NetworkACLServiceProvider> networkAclElements) { public void setNetworkAclElements(final List<NetworkACLServiceProvider> networkAclElements) {
this._networkAclElements = networkAclElements; _networkAclElements = networkAclElements;
} }
} }

View File

@ -22,16 +22,15 @@ import java.util.Map;
import javax.inject.Inject; import javax.inject.Inject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.command.user.network.CreateNetworkACLCmd; import org.apache.cloudstack.api.command.user.network.CreateNetworkACLCmd;
import org.apache.cloudstack.api.command.user.network.ListNetworkACLListsCmd; import org.apache.cloudstack.api.command.user.network.ListNetworkACLListsCmd;
import org.apache.cloudstack.api.command.user.network.ListNetworkACLsCmd; import org.apache.cloudstack.api.command.user.network.ListNetworkACLsCmd;
import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.context.CallContext;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.cloud.event.ActionEvent; import com.cloud.event.ActionEvent;
import com.cloud.event.EventTypes; import com.cloud.event.EventTypes;
@ -95,9 +94,9 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ
VpcService _vpcSvc; VpcService _vpcSvc;
@Override @Override
public NetworkACL createNetworkACL(String name, String description, long vpcId, Boolean forDisplay) { public NetworkACL createNetworkACL(final String name, final String description, final long vpcId, final Boolean forDisplay) {
Account caller = CallContext.current().getCallingAccount(); final Account caller = CallContext.current().getCallingAccount();
Vpc vpc = _entityMgr.findById(Vpc.class, vpcId); final Vpc vpc = _entityMgr.findById(Vpc.class, vpcId);
if (vpc == null) { if (vpc == null) {
throw new InvalidParameterValueException("Unable to find VPC"); throw new InvalidParameterValueException("Unable to find VPC");
} }
@ -107,37 +106,37 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ
@Override @Override
@ActionEvent(eventType = EventTypes.EVENT_NETWORK_ACL_CREATE, eventDescription = "creating network acl list", async = true) @ActionEvent(eventType = EventTypes.EVENT_NETWORK_ACL_CREATE, eventDescription = "creating network acl list", async = true)
public NetworkACL getNetworkACL(long id) { public NetworkACL getNetworkACL(final long id) {
return _networkAclMgr.getNetworkACL(id); return _networkAclMgr.getNetworkACL(id);
} }
@Override @Override
public Pair<List<? extends NetworkACL>, Integer> listNetworkACLs(ListNetworkACLListsCmd cmd) { public Pair<List<? extends NetworkACL>, Integer> listNetworkACLs(final ListNetworkACLListsCmd cmd) {
Long id = cmd.getId(); final Long id = cmd.getId();
String name = cmd.getName(); final String name = cmd.getName();
Long networkId = cmd.getNetworkId(); final Long networkId = cmd.getNetworkId();
Long vpcId = cmd.getVpcId(); final Long vpcId = cmd.getVpcId();
String keyword = cmd.getKeyword(); final String keyword = cmd.getKeyword();
Boolean display = cmd.getDisplay(); final Boolean display = cmd.getDisplay();
SearchBuilder<NetworkACLVO> sb = _networkACLDao.createSearchBuilder(); final SearchBuilder<NetworkACLVO> sb = _networkACLDao.createSearchBuilder();
sb.and("id", sb.entity().getId(), Op.EQ); sb.and("id", sb.entity().getId(), Op.EQ);
sb.and("name", sb.entity().getName(), Op.EQ); sb.and("name", sb.entity().getName(), Op.EQ);
sb.and("vpcId", sb.entity().getVpcId(), Op.IN); sb.and("vpcId", sb.entity().getVpcId(), Op.IN);
sb.and("display", sb.entity().isDisplay(), Op.EQ); sb.and("display", sb.entity().isDisplay(), Op.EQ);
Account caller = CallContext.current().getCallingAccount(); final Account caller = CallContext.current().getCallingAccount();
if (networkId != null) { if (networkId != null) {
SearchBuilder<NetworkVO> network = _networkDao.createSearchBuilder(); final SearchBuilder<NetworkVO> network = _networkDao.createSearchBuilder();
network.and("networkId", network.entity().getId(), Op.EQ); network.and("networkId", network.entity().getId(), Op.EQ);
sb.join("networkJoin", network, sb.entity().getId(), network.entity().getNetworkACLId(), JoinBuilder.JoinType.INNER); sb.join("networkJoin", network, sb.entity().getId(), network.entity().getNetworkACLId(), JoinBuilder.JoinType.INNER);
} }
SearchCriteria<NetworkACLVO> sc = sb.create(); final SearchCriteria<NetworkACLVO> sc = sb.create();
if (keyword != null) { if (keyword != null) {
SearchCriteria<NetworkACLVO> ssc = _networkACLDao.createSearchCriteria(); final SearchCriteria<NetworkACLVO> ssc = _networkACLDao.createSearchCriteria();
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%"); ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc); sc.addAnd("name", SearchCriteria.Op.SC, ssc);
@ -156,7 +155,7 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ
} }
if (vpcId != null) { if (vpcId != null) {
Vpc vpc = _entityMgr.findById(Vpc.class, vpcId); final Vpc vpc = _entityMgr.findById(Vpc.class, vpcId);
if (vpc == null) { if (vpc == null) {
throw new InvalidParameterValueException("Unable to find VPC"); throw new InvalidParameterValueException("Unable to find VPC");
} }
@ -168,26 +167,26 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ
// VpcId is not specified. Find permitted VPCs for the caller // VpcId is not specified. Find permitted VPCs for the caller
// and list ACLs belonging to the permitted VPCs // and list ACLs belonging to the permitted VPCs
List<Long> permittedAccounts = new ArrayList<Long>(); final List<Long> permittedAccounts = new ArrayList<Long>();
Long domainId = cmd.getDomainId(); Long domainId = cmd.getDomainId();
boolean isRecursive = cmd.isRecursive(); boolean isRecursive = cmd.isRecursive();
String accountName = cmd.getAccountName(); final String accountName = cmd.getAccountName();
Long projectId = cmd.getProjectId(); final Long projectId = cmd.getProjectId();
boolean listAll = cmd.listAll(); final boolean listAll = cmd.listAll();
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, final Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean,
ListProjectResourcesCriteria>(domainId, isRecursive, null); ListProjectResourcesCriteria>(domainId, isRecursive, null);
_accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, domainIdRecursiveListProject, _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, domainIdRecursiveListProject,
listAll, false); listAll, false);
domainId = domainIdRecursiveListProject.first(); domainId = domainIdRecursiveListProject.first();
isRecursive = domainIdRecursiveListProject.second(); isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); final ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
SearchBuilder<VpcVO> sbVpc = _vpcDao.createSearchBuilder(); final SearchBuilder<VpcVO> sbVpc = _vpcDao.createSearchBuilder();
_accountMgr.buildACLSearchBuilder(sbVpc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); _accountMgr.buildACLSearchBuilder(sbVpc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
SearchCriteria<VpcVO> scVpc = sbVpc.create(); final SearchCriteria<VpcVO> scVpc = sbVpc.create();
_accountMgr.buildACLSearchCriteria(scVpc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); _accountMgr.buildACLSearchCriteria(scVpc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
List<VpcVO> vpcs = _vpcDao.search(scVpc, null); final List<VpcVO> vpcs = _vpcDao.search(scVpc, null);
List<Long> vpcIds = new ArrayList<Long>(); final List<Long> vpcIds = new ArrayList<Long>();
for (VpcVO vpc : vpcs) { for (final VpcVO vpc : vpcs) {
vpcIds.add(vpc.getId()); vpcIds.add(vpc.getId());
} }
//Add vpc_id 0 to list default ACLs //Add vpc_id 0 to list default ACLs
@ -199,16 +198,16 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ
sc.setJoinParameters("networkJoin", "networkId", networkId); sc.setJoinParameters("networkJoin", "networkId", networkId);
} }
Filter filter = new Filter(NetworkACLVO.class, "id", false, null, null); final Filter filter = new Filter(NetworkACLVO.class, "id", false, null, null);
Pair<List<NetworkACLVO>, Integer> acls = _networkACLDao.searchAndCount(sc, filter); final Pair<List<NetworkACLVO>, Integer> acls = _networkACLDao.searchAndCount(sc, filter);
return new Pair<List<? extends NetworkACL>, Integer>(acls.first(), acls.second()); return new Pair<List<? extends NetworkACL>, Integer>(acls.first(), acls.second());
} }
@Override @Override
@ActionEvent(eventType = EventTypes.EVENT_NETWORK_ACL_DELETE, eventDescription = "Deleting Network ACL List", async = true) @ActionEvent(eventType = EventTypes.EVENT_NETWORK_ACL_DELETE, eventDescription = "Deleting Network ACL List", async = true)
public boolean deleteNetworkACL(long id) { public boolean deleteNetworkACL(final long id) {
Account caller = CallContext.current().getCallingAccount(); final Account caller = CallContext.current().getCallingAccount();
NetworkACL acl = _networkACLDao.findById(id); final NetworkACL acl = _networkACLDao.findById(id);
if (acl == null) { if (acl == null) {
throw new InvalidParameterValueException("Unable to find specified ACL"); throw new InvalidParameterValueException("Unable to find specified ACL");
} }
@ -218,7 +217,7 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ
throw new InvalidParameterValueException("Default ACL cannot be removed"); throw new InvalidParameterValueException("Default ACL cannot be removed");
} }
Vpc vpc = _entityMgr.findById(Vpc.class, acl.getVpcId()); final Vpc vpc = _entityMgr.findById(Vpc.class, acl.getVpcId());
if (vpc == null) { if (vpc == null) {
throw new InvalidParameterValueException("Unable to find specified VPC associated with the ACL"); throw new InvalidParameterValueException("Unable to find specified VPC associated with the ACL");
} }
@ -227,19 +226,19 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ
} }
@Override @Override
public boolean replaceNetworkACLonPrivateGw(long aclId, long privateGatewayId) throws ResourceUnavailableException { public boolean replaceNetworkACLonPrivateGw(final long aclId, final long privateGatewayId) throws ResourceUnavailableException {
Account caller = CallContext.current().getCallingAccount(); final Account caller = CallContext.current().getCallingAccount();
VpcGateway gateway = _vpcGatewayDao.findById(privateGatewayId); final VpcGateway gateway = _vpcGatewayDao.findById(privateGatewayId);
if (gateway == null) { if (gateway == null) {
throw new InvalidParameterValueException("Unable to find specified private gateway"); throw new InvalidParameterValueException("Unable to find specified private gateway");
} }
VpcGatewayVO vo = _vpcGatewayDao.findById(privateGatewayId); final VpcGatewayVO vo = _vpcGatewayDao.findById(privateGatewayId);
if (vo.getState() != VpcGateway.State.Ready) { if (vo.getState() != VpcGateway.State.Ready) {
throw new InvalidParameterValueException("Gateway is not in Ready state"); throw new InvalidParameterValueException("Gateway is not in Ready state");
} }
NetworkACL acl = _networkACLDao.findById(aclId); final NetworkACL acl = _networkACLDao.findById(aclId);
if (acl == null) { if (acl == null) {
throw new InvalidParameterValueException("Unable to find specified NetworkACL"); throw new InvalidParameterValueException("Unable to find specified NetworkACL");
} }
@ -249,7 +248,7 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ
} }
if (aclId != NetworkACL.DEFAULT_DENY && aclId != NetworkACL.DEFAULT_ALLOW) { if (aclId != NetworkACL.DEFAULT_DENY && aclId != NetworkACL.DEFAULT_ALLOW) {
Vpc vpc = _entityMgr.findById(Vpc.class, acl.getVpcId()); final Vpc vpc = _entityMgr.findById(Vpc.class, acl.getVpcId());
if (vpc == null) { if (vpc == null) {
throw new InvalidParameterValueException("Unable to find Vpc associated with the NetworkACL"); throw new InvalidParameterValueException("Unable to find Vpc associated with the NetworkACL");
} }
@ -259,7 +258,7 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ
} }
} }
PrivateGateway privateGateway = _vpcSvc.getVpcPrivateGateway(gateway.getId()); final PrivateGateway privateGateway = _vpcSvc.getVpcPrivateGateway(gateway.getId());
_accountMgr.checkAccess(caller, null, true, privateGateway); _accountMgr.checkAccess(caller, null, true, privateGateway);
return _networkAclMgr.replaceNetworkACLForPrivateGw(acl, privateGateway); return _networkAclMgr.replaceNetworkACLForPrivateGw(acl, privateGateway);
@ -267,15 +266,15 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ
} }
@Override @Override
public boolean replaceNetworkACL(long aclId, long networkId) throws ResourceUnavailableException { public boolean replaceNetworkACL(final long aclId, final long networkId) throws ResourceUnavailableException {
Account caller = CallContext.current().getCallingAccount(); final Account caller = CallContext.current().getCallingAccount();
NetworkVO network = _networkDao.findById(networkId); final NetworkVO network = _networkDao.findById(networkId);
if (network == null) { if (network == null) {
throw new InvalidParameterValueException("Unable to find specified Network"); throw new InvalidParameterValueException("Unable to find specified Network");
} }
NetworkACL acl = _networkACLDao.findById(aclId); final NetworkACL acl = _networkACLDao.findById(aclId);
if (acl == null) { if (acl == null) {
throw new InvalidParameterValueException("Unable to find specified NetworkACL"); throw new InvalidParameterValueException("Unable to find specified NetworkACL");
} }
@ -291,7 +290,7 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ
if (aclId != NetworkACL.DEFAULT_DENY && aclId != NetworkACL.DEFAULT_ALLOW) { if (aclId != NetworkACL.DEFAULT_DENY && aclId != NetworkACL.DEFAULT_ALLOW) {
//ACL is not default DENY/ALLOW //ACL is not default DENY/ALLOW
// ACL should be associated with a VPC // ACL should be associated with a VPC
Vpc vpc = _entityMgr.findById(Vpc.class, acl.getVpcId()); final Vpc vpc = _entityMgr.findById(Vpc.class, acl.getVpcId());
if (vpc == null) { if (vpc == null) {
throw new InvalidParameterValueException("Unable to find Vpc associated with the NetworkACL"); throw new InvalidParameterValueException("Unable to find Vpc associated with the NetworkACL");
} }
@ -306,15 +305,15 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ
} }
@Override @Override
public NetworkACLItem createNetworkACLItem(CreateNetworkACLCmd aclItemCmd) { public NetworkACLItem createNetworkACLItem(final CreateNetworkACLCmd aclItemCmd) {
Account caller = CallContext.current().getCallingAccount(); final Account caller = CallContext.current().getCallingAccount();
Long aclId = aclItemCmd.getACLId(); Long aclId = aclItemCmd.getACLId();
if (aclId == null) { if (aclId == null) {
//ACL id is not specified. Get the ACL details from network //ACL id is not specified. Get the ACL details from network
if (aclItemCmd.getNetworkId() == null) { if (aclItemCmd.getNetworkId() == null) {
throw new InvalidParameterValueException("Cannot create Network ACL Item. ACL Id or network Id is required"); throw new InvalidParameterValueException("Cannot create Network ACL Item. ACL Id or network Id is required");
} }
Network network = _networkMgr.getNetwork(aclItemCmd.getNetworkId()); final Network network = _networkMgr.getNetwork(aclItemCmd.getNetworkId());
if (network.getVpcId() == null) { if (network.getVpcId() == null) {
throw new InvalidParameterValueException("Network: " + network.getUuid() + " does not belong to VPC"); throw new InvalidParameterValueException("Network: " + network.getUuid() + " does not belong to VPC");
} }
@ -329,15 +328,15 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ
throw new InvalidParameterValueException("Network Offering does not support NetworkACL service"); throw new InvalidParameterValueException("Network Offering does not support NetworkACL service");
} }
Vpc vpc = _entityMgr.findById(Vpc.class, network.getVpcId()); final Vpc vpc = _entityMgr.findById(Vpc.class, network.getVpcId());
if (vpc == null) { if (vpc == null) {
throw new InvalidParameterValueException("Unable to find Vpc associated with the Network"); throw new InvalidParameterValueException("Unable to find Vpc associated with the Network");
} }
//Create new ACL //Create new ACL
String aclName = "VPC_" + vpc.getName() + "_Tier_" + network.getName() + "_ACL_" + network.getUuid(); final String aclName = "VPC_" + vpc.getName() + "_Tier_" + network.getName() + "_ACL_" + network.getUuid();
String description = "ACL for " + aclName; final String description = "ACL for " + aclName;
NetworkACL acl = _networkAclMgr.createNetworkACL(aclName, description, network.getVpcId(), aclItemCmd.getDisplay()); final NetworkACL acl = _networkAclMgr.createNetworkACL(aclName, description, network.getVpcId(), aclItemCmd.getDisplay());
if (acl == null) { if (acl == null) {
throw new CloudRuntimeException("Error while create ACL before adding ACL Item for network " + network.getId()); throw new CloudRuntimeException("Error while create ACL before adding ACL Item for network " + network.getId());
} }
@ -349,22 +348,22 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ
throw new CloudRuntimeException("Unable to apply auto created ACL to network " + network.getId()); throw new CloudRuntimeException("Unable to apply auto created ACL to network " + network.getId());
} }
s_logger.debug("Created ACL is applied to network " + network.getId()); s_logger.debug("Created ACL is applied to network " + network.getId());
} catch (ResourceUnavailableException e) { } catch (final ResourceUnavailableException e) {
throw new CloudRuntimeException("Unable to apply auto created ACL to network " + network.getId(), e); throw new CloudRuntimeException("Unable to apply auto created ACL to network " + network.getId(), e);
} }
} }
} }
NetworkACL acl = _networkAclMgr.getNetworkACL(aclId); final NetworkACL acl = _networkAclMgr.getNetworkACL(aclId);
if (acl == null) { if (acl == null) {
throw new InvalidParameterValueException("Unable to find specified ACL"); throw new InvalidParameterValueException("Unable to find specified ACL");
} }
if ((aclId == NetworkACL.DEFAULT_DENY) || (aclId == NetworkACL.DEFAULT_ALLOW)) { if (aclId == NetworkACL.DEFAULT_DENY || aclId == NetworkACL.DEFAULT_ALLOW) {
throw new InvalidParameterValueException("Default ACL cannot be modified"); throw new InvalidParameterValueException("Default ACL cannot be modified");
} }
Vpc vpc = _entityMgr.findById(Vpc.class, acl.getVpcId()); final Vpc vpc = _entityMgr.findById(Vpc.class, acl.getVpcId());
if (vpc == null) { if (vpc == null) {
throw new InvalidParameterValueException("Unable to find Vpc associated with the NetworkACL"); throw new InvalidParameterValueException("Unable to find Vpc associated with the NetworkACL");
} }
@ -378,15 +377,15 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ
} }
validateNetworkACLItem(aclItemCmd.getSourcePortStart(), aclItemCmd.getSourcePortEnd(), aclItemCmd.getSourceCidrList(), aclItemCmd.getProtocol(), validateNetworkACLItem(aclItemCmd.getSourcePortStart(), aclItemCmd.getSourcePortEnd(), aclItemCmd.getSourceCidrList(), aclItemCmd.getProtocol(),
aclItemCmd.getIcmpCode(), aclItemCmd.getIcmpType(), aclItemCmd.getAction(), aclItemCmd.getNumber()); aclItemCmd.getIcmpCode(), aclItemCmd.getIcmpType(), aclItemCmd.getAction(), aclItemCmd.getNumber());
return _networkAclMgr.createNetworkACLItem(aclItemCmd.getSourcePortStart(), aclItemCmd.getSourcePortEnd(), aclItemCmd.getProtocol(), return _networkAclMgr.createNetworkACLItem(aclItemCmd.getSourcePortStart(), aclItemCmd.getSourcePortEnd(), aclItemCmd.getProtocol(),
aclItemCmd.getSourceCidrList(), aclItemCmd.getIcmpCode(), aclItemCmd.getIcmpType(), aclItemCmd.getTrafficType(), aclId, aclItemCmd.getAction(), aclItemCmd.getSourceCidrList(), aclItemCmd.getIcmpCode(), aclItemCmd.getIcmpType(), aclItemCmd.getTrafficType(), aclId, aclItemCmd.getAction(),
aclItemCmd.getNumber(), aclItemCmd.getDisplay()); aclItemCmd.getNumber(), aclItemCmd.getDisplay());
} }
private void validateNetworkACLItem(Integer portStart, Integer portEnd, List<String> sourceCidrList, String protocol, Integer icmpCode, Integer icmpType, private void validateNetworkACLItem(final Integer portStart, final Integer portEnd, final List<String> sourceCidrList, final String protocol, final Integer icmpCode, final Integer icmpType,
String action, Integer number) { final String action, final Integer number) {
if (portStart != null && !NetUtils.isValidPort(portStart)) { if (portStart != null && !NetUtils.isValidPort(portStart)) {
throw new InvalidParameterValueException("publicPort is an invalid value: " + portStart); throw new InvalidParameterValueException("publicPort is an invalid value: " + portStart);
@ -401,11 +400,12 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ
} }
// start port and end port must be null for protocol = 'all' // start port and end port must be null for protocol = 'all'
if ((portStart != null || portEnd != null) && protocol != null && protocol.equalsIgnoreCase("all")) if ((portStart != null || portEnd != null) && protocol != null && protocol.equalsIgnoreCase("all")) {
throw new InvalidParameterValueException("start port and end port must be null if protocol = 'all'"); throw new InvalidParameterValueException("start port and end port must be null if protocol = 'all'");
}
if (sourceCidrList != null) { if (sourceCidrList != null) {
for (String cidr : sourceCidrList) { for (final String cidr : sourceCidrList) {
if (!NetUtils.isValidCIDR(cidr)) { if (!NetUtils.isValidCIDR(cidr)) {
throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Source cidrs formatting error " + cidr); throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Source cidrs formatting error " + cidr);
} }
@ -416,14 +416,14 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ
if (protocol != null) { if (protocol != null) {
//Check if protocol is a number //Check if protocol is a number
if (StringUtils.isNumeric(protocol)) { if (StringUtils.isNumeric(protocol)) {
int protoNumber = Integer.parseInt(protocol); final int protoNumber = Integer.parseInt(protocol);
if (protoNumber < 0 || protoNumber > 255) { if (protoNumber < 0 || protoNumber > 255) {
throw new InvalidParameterValueException("Invalid protocol number: " + protoNumber); throw new InvalidParameterValueException("Invalid protocol number: " + protoNumber);
} }
} else { } else {
//Protocol is not number //Protocol is not number
//Check for valid protocol strings //Check for valid protocol strings
String supportedProtocols = "tcp,udp,icmp,all"; final String supportedProtocols = "tcp,udp,icmp,all";
if (!supportedProtocols.contains(protocol.toLowerCase())) { if (!supportedProtocols.contains(protocol.toLowerCase())) {
throw new InvalidParameterValueException("Invalid protocol: " + protocol); throw new InvalidParameterValueException("Invalid protocol: " + protocol);
} }
@ -447,7 +447,7 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ
if (icmpCode != null) { if (icmpCode != null) {
if (icmpCode.longValue() != -1 && !NetUtils.validateIcmpCode(icmpCode.longValue())) { if (icmpCode.longValue() != -1 && !NetUtils.validateIcmpCode(icmpCode.longValue())) {
throw new InvalidParameterValueException("Invalid icmp code; should belong to [0-15] range and can" throw new InvalidParameterValueException("Invalid icmp code; should belong to [0-15] range and can"
+ " be defined when icmpType belongs to [0-40] range"); + " be defined when icmpType belongs to [0-40] range");
} }
} }
} }
@ -466,29 +466,29 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ
} }
@Override @Override
public NetworkACLItem getNetworkACLItem(long ruleId) { public NetworkACLItem getNetworkACLItem(final long ruleId) {
return _networkAclMgr.getNetworkACLItem(ruleId); return _networkAclMgr.getNetworkACLItem(ruleId);
} }
@Override @Override
@ActionEvent(eventType = EventTypes.EVENT_NETWORK_ACL_ITEM_CREATE, eventDescription = "Applying Network ACL Item", async = true) @ActionEvent(eventType = EventTypes.EVENT_NETWORK_ACL_ITEM_CREATE, eventDescription = "Applying Network ACL Item", async = true)
public boolean applyNetworkACL(long aclId) throws ResourceUnavailableException { public boolean applyNetworkACL(final long aclId) throws ResourceUnavailableException {
return _networkAclMgr.applyNetworkACL(aclId); return _networkAclMgr.applyNetworkACL(aclId);
} }
@Override @Override
public Pair<List<? extends NetworkACLItem>, Integer> listNetworkACLItems(ListNetworkACLsCmd cmd) { public Pair<List<? extends NetworkACLItem>, Integer> listNetworkACLItems(final ListNetworkACLsCmd cmd) {
Long networkId = cmd.getNetworkId(); final Long networkId = cmd.getNetworkId();
Long id = cmd.getId(); final Long id = cmd.getId();
Long aclId = cmd.getAclId(); Long aclId = cmd.getAclId();
String trafficType = cmd.getTrafficType(); final String trafficType = cmd.getTrafficType();
String protocol = cmd.getProtocol(); final String protocol = cmd.getProtocol();
String action = cmd.getAction(); final String action = cmd.getAction();
Map<String, String> tags = cmd.getTags(); final Map<String, String> tags = cmd.getTags();
Account caller = CallContext.current().getCallingAccount(); final Account caller = CallContext.current().getCallingAccount();
Filter filter = new Filter(NetworkACLItemVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal()); final Filter filter = new Filter(NetworkACLItemVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal());
SearchBuilder<NetworkACLItemVO> sb = _networkACLItemDao.createSearchBuilder(); final SearchBuilder<NetworkACLItemVO> sb = _networkACLItemDao.createSearchBuilder();
sb.and("id", sb.entity().getId(), Op.EQ); sb.and("id", sb.entity().getId(), Op.EQ);
sb.and("aclId", sb.entity().getAclId(), Op.EQ); sb.and("aclId", sb.entity().getAclId(), Op.EQ);
@ -497,7 +497,7 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ
sb.and("action", sb.entity().getAction(), Op.EQ); sb.and("action", sb.entity().getAction(), Op.EQ);
if (tags != null && !tags.isEmpty()) { if (tags != null && !tags.isEmpty()) {
SearchBuilder<ResourceTagVO> tagSearch = _resourceTagDao.createSearchBuilder(); final SearchBuilder<ResourceTagVO> tagSearch = _resourceTagDao.createSearchBuilder();
for (int count = 0; count < tags.size(); count++) { for (int count = 0; count < tags.size(); count++) {
tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), Op.EQ); tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), Op.EQ);
tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), Op.EQ); tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), Op.EQ);
@ -510,19 +510,19 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ
if (aclId == null) { if (aclId == null) {
//Join with network_acl table when aclId is not specified to list acl_items within permitted VPCs //Join with network_acl table when aclId is not specified to list acl_items within permitted VPCs
SearchBuilder<NetworkACLVO> vpcSearch = _networkACLDao.createSearchBuilder(); final SearchBuilder<NetworkACLVO> vpcSearch = _networkACLDao.createSearchBuilder();
vpcSearch.and("vpcId", vpcSearch.entity().getVpcId(), Op.IN); vpcSearch.and("vpcId", vpcSearch.entity().getVpcId(), Op.IN);
sb.join("vpcSearch", vpcSearch, sb.entity().getAclId(), vpcSearch.entity().getId(), JoinBuilder.JoinType.INNER); sb.join("vpcSearch", vpcSearch, sb.entity().getAclId(), vpcSearch.entity().getId(), JoinBuilder.JoinType.INNER);
} }
SearchCriteria<NetworkACLItemVO> sc = sb.create(); final SearchCriteria<NetworkACLItemVO> sc = sb.create();
if (id != null) { if (id != null) {
sc.setParameters("id", id); sc.setParameters("id", id);
} }
if (networkId != null) { if (networkId != null) {
Network network = _networkDao.findById(networkId); final Network network = _networkDao.findById(networkId);
aclId = network.getNetworkACLId(); aclId = network.getNetworkACLId();
if( aclId == null){ if( aclId == null){
// No aclId associated with the network. // No aclId associated with the network.
@ -537,9 +537,9 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ
if (aclId != null) { if (aclId != null) {
// Get VPC and check access // Get VPC and check access
NetworkACL acl = _networkACLDao.findById(aclId); final NetworkACL acl = _networkACLDao.findById(aclId);
if (acl.getVpcId() != 0) { if (acl.getVpcId() != 0) {
Vpc vpc = _vpcDao.findById(acl.getVpcId()); final Vpc vpc = _vpcDao.findById(acl.getVpcId());
if (vpc == null) { if (vpc == null) {
throw new InvalidParameterValueException("Unable to find VPC associated with acl"); throw new InvalidParameterValueException("Unable to find VPC associated with acl");
} }
@ -552,26 +552,26 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ
// aclId is not specified // aclId is not specified
// List permitted VPCs and filter aclItems // List permitted VPCs and filter aclItems
List<Long> permittedAccounts = new ArrayList<Long>(); final List<Long> permittedAccounts = new ArrayList<Long>();
Long domainId = cmd.getDomainId(); Long domainId = cmd.getDomainId();
boolean isRecursive = cmd.isRecursive(); boolean isRecursive = cmd.isRecursive();
String accountName = cmd.getAccountName(); final String accountName = cmd.getAccountName();
Long projectId = cmd.getProjectId(); final Long projectId = cmd.getProjectId();
boolean listAll = cmd.listAll(); final boolean listAll = cmd.listAll();
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, final Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean,
ListProjectResourcesCriteria>(domainId, isRecursive, null); ListProjectResourcesCriteria>(domainId, isRecursive, null);
_accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, domainIdRecursiveListProject, _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, domainIdRecursiveListProject,
listAll, false); listAll, false);
domainId = domainIdRecursiveListProject.first(); domainId = domainIdRecursiveListProject.first();
isRecursive = domainIdRecursiveListProject.second(); isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); final ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
SearchBuilder<VpcVO> sbVpc = _vpcDao.createSearchBuilder(); final SearchBuilder<VpcVO> sbVpc = _vpcDao.createSearchBuilder();
_accountMgr.buildACLSearchBuilder(sbVpc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); _accountMgr.buildACLSearchBuilder(sbVpc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
SearchCriteria<VpcVO> scVpc = sbVpc.create(); final SearchCriteria<VpcVO> scVpc = sbVpc.create();
_accountMgr.buildACLSearchCriteria(scVpc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); _accountMgr.buildACLSearchCriteria(scVpc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
List<VpcVO> vpcs = _vpcDao.search(scVpc, null); final List<VpcVO> vpcs = _vpcDao.search(scVpc, null);
List<Long> vpcIds = new ArrayList<Long>(); final List<Long> vpcIds = new ArrayList<Long>();
for (VpcVO vpc : vpcs) { for (final VpcVO vpc : vpcs) {
vpcIds.add(vpc.getId()); vpcIds.add(vpc.getId());
} }
//Add vpc_id 0 to list acl_items in default ACL //Add vpc_id 0 to list acl_items in default ACL
@ -590,16 +590,16 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ
if (tags != null && !tags.isEmpty()) { if (tags != null && !tags.isEmpty()) {
int count = 0; int count = 0;
sc.setJoinParameters("tagSearch", "resourceType", ResourceObjectType.NetworkACL.toString()); sc.setJoinParameters("tagSearch", "resourceType", ResourceObjectType.NetworkACL.toString());
for (String key : tags.keySet()) { for (final String key : tags.keySet()) {
sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), key); sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), key);
sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), tags.get(key)); sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), tags.get(key));
count++; count++;
} }
} }
Pair<List<NetworkACLItemVO>, Integer> result = _networkACLItemDao.searchAndCount(sc, filter); final Pair<List<NetworkACLItemVO>, Integer> result = _networkACLItemDao.searchAndCount(sc, filter);
List<NetworkACLItemVO> aclItemVOs = result.first(); final List<NetworkACLItemVO> aclItemVOs = result.first();
for (NetworkACLItemVO item: aclItemVOs) { for (final NetworkACLItemVO item: aclItemVOs) {
_networkACLItemDao.loadCidrs(item); _networkACLItemDao.loadCidrs(item);
} }
return new Pair<List<? extends NetworkACLItem>, Integer>(aclItemVOs, result.second()); return new Pair<List<? extends NetworkACLItem>, Integer>(aclItemVOs, result.second());
@ -607,18 +607,18 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ
@Override @Override
@ActionEvent(eventType = EventTypes.EVENT_NETWORK_ACL_ITEM_DELETE, eventDescription = "Deleting Network ACL Item", async = true) @ActionEvent(eventType = EventTypes.EVENT_NETWORK_ACL_ITEM_DELETE, eventDescription = "Deleting Network ACL Item", async = true)
public boolean revokeNetworkACLItem(long ruleId) { public boolean revokeNetworkACLItem(final long ruleId) {
NetworkACLItemVO aclItem = _networkACLItemDao.findById(ruleId); final NetworkACLItemVO aclItem = _networkACLItemDao.findById(ruleId);
if(aclItem != null){ if(aclItem != null){
NetworkACL acl = _networkAclMgr.getNetworkACL(aclItem.getAclId()); final NetworkACL acl = _networkAclMgr.getNetworkACL(aclItem.getAclId());
Vpc vpc = _entityMgr.findById(Vpc.class, acl.getVpcId()); final Vpc vpc = _entityMgr.findById(Vpc.class, acl.getVpcId());
if((aclItem.getAclId() == NetworkACL.DEFAULT_ALLOW) || (aclItem.getAclId() == NetworkACL.DEFAULT_DENY)){ if(aclItem.getAclId() == NetworkACL.DEFAULT_ALLOW || aclItem.getAclId() == NetworkACL.DEFAULT_DENY){
throw new InvalidParameterValueException("ACL Items in default ACL cannot be deleted"); throw new InvalidParameterValueException("ACL Items in default ACL cannot be deleted");
} }
Account caller = CallContext.current().getCallingAccount(); final Account caller = CallContext.current().getCallingAccount();
_accountMgr.checkAccess(caller, null, true, vpc); _accountMgr.checkAccess(caller, null, true, vpc);
@ -627,10 +627,9 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ
} }
@Override @Override
@ActionEvent(eventType = EventTypes.EVENT_NETWORK_ACL_ITEM_UPDATE, eventDescription = "Updating Network ACL Item", async = true) public NetworkACLItem updateNetworkACLItem(final Long id, final String protocol, final List<String> sourceCidrList, final NetworkACLItem.TrafficType trafficType, final String action,
public NetworkACLItem updateNetworkACLItem(Long id, String protocol, List<String> sourceCidrList, NetworkACLItem.TrafficType trafficType, String action, final Integer number, final Integer sourcePortStart, final Integer sourcePortEnd, final Integer icmpCode, final Integer icmpType, final String newUUID, final Boolean forDisplay) throws ResourceUnavailableException {
Integer number, Integer sourcePortStart, Integer sourcePortEnd, Integer icmpCode, Integer icmpType, String newUUID, Boolean forDisplay) throws ResourceUnavailableException { final NetworkACLItemVO aclItem = _networkACLItemDao.findById(id);
NetworkACLItemVO aclItem = _networkACLItemDao.findById(id);
if (aclItem == null) { if (aclItem == null) {
throw new InvalidParameterValueException("Unable to find ACL Item cannot be found"); throw new InvalidParameterValueException("Unable to find ACL Item cannot be found");
} }
@ -639,34 +638,34 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ
throw new InvalidParameterValueException("Default ACL Items cannot be updated"); throw new InvalidParameterValueException("Default ACL Items cannot be updated");
} }
NetworkACL acl = _networkAclMgr.getNetworkACL(aclItem.getAclId()); final NetworkACL acl = _networkAclMgr.getNetworkACL(aclItem.getAclId());
Vpc vpc = _entityMgr.findById(Vpc.class, acl.getVpcId()); final Vpc vpc = _entityMgr.findById(Vpc.class, acl.getVpcId());
Account caller = CallContext.current().getCallingAccount(); final Account caller = CallContext.current().getCallingAccount();
_accountMgr.checkAccess(caller, null, true, vpc); _accountMgr.checkAccess(caller, null, true, vpc);
if (number != null) { if (number != null) {
//Check if ACL Item with specified number already exists //Check if ACL Item with specified number already exists
NetworkACLItemVO aclNumber = _networkACLItemDao.findByAclAndNumber(acl.getId(), number); final NetworkACLItemVO aclNumber = _networkACLItemDao.findByAclAndNumber(acl.getId(), number);
if ((aclNumber != null) && (aclNumber.getId() != id)) { if (aclNumber != null && aclNumber.getId() != id) {
throw new InvalidParameterValueException("ACL item with number " + number + " already exists in ACL: " + acl.getUuid()); throw new InvalidParameterValueException("ACL item with number " + number + " already exists in ACL: " + acl.getUuid());
} }
} }
validateNetworkACLItem((sourcePortStart == null) ? aclItem.getSourcePortStart() : sourcePortStart, (sourcePortEnd == null) ? aclItem.getSourcePortEnd() validateNetworkACLItem(sourcePortStart == null ? aclItem.getSourcePortStart() : sourcePortStart, sourcePortEnd == null ? aclItem.getSourcePortEnd()
: sourcePortEnd, sourceCidrList, protocol, icmpCode, (icmpType == null) ? aclItem.getIcmpType() : icmpType, action, number); : sourcePortEnd, sourceCidrList, protocol, icmpCode, icmpType == null ? aclItem.getIcmpType() : icmpType, action, number);
return _networkAclMgr.updateNetworkACLItem(id, protocol, sourceCidrList, trafficType, action, number, sourcePortStart, sourcePortEnd, icmpCode, icmpType, newUUID, forDisplay); return _networkAclMgr.updateNetworkACLItem(id, protocol, sourceCidrList, trafficType, action, number, sourcePortStart, sourcePortEnd, icmpCode, icmpType, newUUID, forDisplay);
} }
@Override @Override
@ActionEvent(eventType = EventTypes.EVENT_NETWORK_ACL_UPDATE, eventDescription = "updating network acl", async = true) @ActionEvent(eventType = EventTypes.EVENT_NETWORK_ACL_UPDATE, eventDescription = "updating network acl", async = true)
public NetworkACL updateNetworkACL(Long id, String customId, Boolean forDisplay) { public NetworkACL updateNetworkACL(final Long id, final String customId, final Boolean forDisplay) {
NetworkACLVO acl = _networkACLDao.findById(id); final NetworkACLVO acl = _networkACLDao.findById(id);
Vpc vpc = _entityMgr.findById(Vpc.class, acl.getVpcId()); final Vpc vpc = _entityMgr.findById(Vpc.class, acl.getVpcId());
Account caller = CallContext.current().getCallingAccount(); final Account caller = CallContext.current().getCallingAccount();
_accountMgr.checkAccess(caller, null, true, vpc); _accountMgr.checkAccess(caller, null, true, vpc);
if (customId != null) { if (customId != null) {

View File

@ -16,7 +16,6 @@
// under the License. // under the License.
package com.cloud.network.vpc; package com.cloud.network.vpc;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
@ -210,6 +209,10 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
@Inject @Inject
NetworkACLDao _networkAclDao; NetworkACLDao _networkAclDao;
@Inject @Inject
NetworkACLItemDao _networkACLItemDao;
@Inject
NetworkACLManager _networkAclMgr;
@Inject
IpAddressManager _ipAddrMgr; IpAddressManager _ipAddrMgr;
@Inject @Inject
ConfigDepot _configDepot; ConfigDepot _configDepot;
@ -220,9 +223,8 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
private final ScheduledExecutorService _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("VpcChecker")); private final ScheduledExecutorService _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("VpcChecker"));
private List<VpcProvider> vpcElements = null; private List<VpcProvider> vpcElements = null;
private final List<Service> nonSupportedServices = Arrays.asList(Service.SecurityGroup, Service.Firewall); private final List<Service> nonSupportedServices = Arrays.asList(Service.SecurityGroup, Service.Firewall);
private final List<Provider> supportedProviders = Arrays.asList(Provider.VPCVirtualRouter, private final List<Provider> supportedProviders = Arrays.asList(Provider.VPCVirtualRouter, Provider.NiciraNvp, Provider.InternalLbVm, Provider.Netscaler,
Provider.NiciraNvp, Provider.InternalLbVm, Provider.Netscaler, Provider.JuniperContrailVpcRouter, Provider.JuniperContrailVpcRouter, Provider.Ovs, Provider.NuageVsp, Provider.BigSwitchBcf);
Provider.Ovs, Provider.NuageVsp, Provider.BigSwitchBcf);
int _cleanupInterval; int _cleanupInterval;
int _maxNetworks; int _maxNetworks;
@ -244,7 +246,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
@Override @Override
@DB @DB
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException { public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
//configure default vpc offering // configure default vpc offering
Transaction.execute(new TransactionCallbackNoReturn() { Transaction.execute(new TransactionCallbackNoReturn() {
@Override @Override
public void doInTransactionWithoutResult(final TransactionStatus status) { public void doInTransactionWithoutResult(final TransactionStatus status) {
@ -265,11 +267,10 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
svcProviderMap.put(svc, defaultProviders); svcProviderMap.put(svc, defaultProviders);
} }
} }
createVpcOffering(VpcOffering.defaultVPCOfferingName, VpcOffering.defaultVPCOfferingName, createVpcOffering(VpcOffering.defaultVPCOfferingName, VpcOffering.defaultVPCOfferingName, svcProviderMap, true, State.Enabled, null, false, false, false);
svcProviderMap, true, State.Enabled, null, false, false, false);
} }
//configure default vpc offering with Netscaler as LB Provider // configure default vpc offering with Netscaler as LB Provider
if (_vpcOffDao.findByUniqueName(VpcOffering.defaultVPCNSOfferingName) == null) { if (_vpcOffDao.findByUniqueName(VpcOffering.defaultVPCNSOfferingName) == null) {
s_logger.debug("Creating default VPC offering with Netscaler as LB Provider" + VpcOffering.defaultVPCNSOfferingName); s_logger.debug("Creating default VPC offering with Netscaler as LB Provider" + VpcOffering.defaultVPCNSOfferingName);
final Map<Service, Set<Provider>> svcProviderMap = new HashMap<Service, Set<Provider>>(); final Map<Service, Set<Provider>> svcProviderMap = new HashMap<Service, Set<Provider>>();
@ -285,8 +286,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
svcProviderMap.put(svc, defaultProviders); svcProviderMap.put(svc, defaultProviders);
} }
} }
createVpcOffering(VpcOffering.defaultVPCNSOfferingName, VpcOffering.defaultVPCNSOfferingName, createVpcOffering(VpcOffering.defaultVPCNSOfferingName, VpcOffering.defaultVPCNSOfferingName, svcProviderMap, false, State.Enabled, null, false, false, false);
svcProviderMap, false, State.Enabled, null, false, false, false);
} }
@ -306,8 +306,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
svcProviderMap.put(svc, defaultProviders); svcProviderMap.put(svc, defaultProviders);
} }
} }
createVpcOffering(VpcOffering.redundantVPCOfferingName, VpcOffering.redundantVPCOfferingName, createVpcOffering(VpcOffering.redundantVPCOfferingName, VpcOffering.redundantVPCOfferingName, svcProviderMap, true, State.Enabled, null, false, false, true);
svcProviderMap, true, State.Enabled, null, false, false, true);
} }
} }
}); });
@ -326,8 +325,8 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
IpAddressSearch.and("associatedWithNetworkId", IpAddressSearch.entity().getAssociatedWithNetworkId(), Op.EQ); IpAddressSearch.and("associatedWithNetworkId", IpAddressSearch.entity().getAssociatedWithNetworkId(), Op.EQ);
final SearchBuilder<VlanVO> virtualNetworkVlanSB = _vlanDao.createSearchBuilder(); final SearchBuilder<VlanVO> virtualNetworkVlanSB = _vlanDao.createSearchBuilder();
virtualNetworkVlanSB.and("vlanType", virtualNetworkVlanSB.entity().getVlanType(), Op.EQ); virtualNetworkVlanSB.and("vlanType", virtualNetworkVlanSB.entity().getVlanType(), Op.EQ);
IpAddressSearch.join("virtualNetworkVlanSB", virtualNetworkVlanSB, IpAddressSearch.entity().getVlanId(), virtualNetworkVlanSB.entity().getId(), IpAddressSearch
JoinBuilder.JoinType.INNER); .join("virtualNetworkVlanSB", virtualNetworkVlanSB, IpAddressSearch.entity().getVlanId(), virtualNetworkVlanSB.entity().getId(), JoinBuilder.JoinType.INNER);
IpAddressSearch.done(); IpAddressSearch.done();
return true; return true;
@ -356,10 +355,8 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
@Override @Override
@ActionEvent(eventType = EventTypes.EVENT_VPC_OFFERING_CREATE, eventDescription = "creating vpc offering", create = true) @ActionEvent(eventType = EventTypes.EVENT_VPC_OFFERING_CREATE, eventDescription = "creating vpc offering", create = true)
public VpcOffering createVpcOffering(final String name, final String displayText, final List<String> supportedServices, public VpcOffering createVpcOffering(final String name, final String displayText, final List<String> supportedServices, final Map<String, List<String>> serviceProviders,
final Map<String, List<String>> serviceProviders, final Map serviceCapabilitystList, final Long serviceOfferingId) {
final Map serviceCapabilitystList,
final Long serviceOfferingId) {
final Map<Network.Service, Set<Network.Provider>> svcProviderMap = new HashMap<Network.Service, Set<Network.Provider>>(); final Map<Network.Service, Set<Network.Provider>> svcProviderMap = new HashMap<Network.Service, Set<Network.Provider>>();
final Set<Network.Provider> defaultProviders = new HashSet<Network.Provider>(); final Set<Network.Provider> defaultProviders = new HashSet<Network.Provider>();
@ -423,8 +420,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
} }
svcProviderMap.put(service, providers); svcProviderMap.put(service, providers);
} else { } else {
throw new InvalidParameterValueException("Service " + serviceEntry.getKey() + " is not enabled for the network " + throw new InvalidParameterValueException("Service " + serviceEntry.getKey() + " is not enabled for the network " + "offering, can't add a provider to it");
"offering, can't add a provider to it");
} }
} }
} }
@ -434,26 +430,23 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
final boolean supportsDistributedRouter = isVpcOfferingSupportsDistributedRouter(serviceCapabilitystList); final boolean supportsDistributedRouter = isVpcOfferingSupportsDistributedRouter(serviceCapabilitystList);
final boolean offersRegionLevelVPC = isVpcOfferingForRegionLevelVpc(serviceCapabilitystList); final boolean offersRegionLevelVPC = isVpcOfferingForRegionLevelVpc(serviceCapabilitystList);
final boolean redundantRouter = isVpcOfferingRedundantRouter(serviceCapabilitystList); final boolean redundantRouter = isVpcOfferingRedundantRouter(serviceCapabilitystList);
final VpcOffering offering = createVpcOffering(name, displayText, svcProviderMap, false, null, final VpcOffering offering = createVpcOffering(name, displayText, svcProviderMap, false, null, serviceOfferingId, supportsDistributedRouter, offersRegionLevelVPC,
serviceOfferingId, supportsDistributedRouter, offersRegionLevelVPC, redundantRouter); redundantRouter);
CallContext.current().setEventDetails(" Id: " + offering.getId() + " Name: " + name); CallContext.current().setEventDetails(" Id: " + offering.getId() + " Name: " + name);
return offering; return offering;
} }
@DB @DB
protected VpcOffering createVpcOffering(final String name, final String displayText, protected VpcOffering createVpcOffering(final String name, final String displayText, final Map<Network.Service, Set<Network.Provider>> svcProviderMap,
final Map<Network.Service, Set<Network.Provider>> svcProviderMap, final boolean isDefault, final State state, final Long serviceOfferingId, final boolean supportsDistributedRouter, final boolean offersRegionLevelVPC,
final boolean isDefault, final State state, final Long serviceOfferingId,
final boolean supportsDistributedRouter, final boolean offersRegionLevelVPC,
final boolean redundantRouter) { final boolean redundantRouter) {
return Transaction.execute(new TransactionCallback<VpcOffering>() { return Transaction.execute(new TransactionCallback<VpcOffering>() {
@Override @Override
public VpcOffering doInTransaction(final TransactionStatus status) { public VpcOffering doInTransaction(final TransactionStatus status) {
// create vpc offering object // create vpc offering object
VpcOfferingVO offering = new VpcOfferingVO(name, displayText, isDefault, serviceOfferingId, VpcOfferingVO offering = new VpcOfferingVO(name, displayText, isDefault, serviceOfferingId, supportsDistributedRouter, offersRegionLevelVPC, redundantRouter);
supportsDistributedRouter, offersRegionLevelVPC, redundantRouter);
if (state != null) { if (state != null) {
offering.setState(state); offering.setState(state);
@ -481,20 +474,16 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
}); });
} }
protected void checkCapabilityPerServiceProvider(final Set<Provider> providers, final Capability capability, protected void checkCapabilityPerServiceProvider(final Set<Provider> providers, final Capability capability, final Service service) {
final Service service) {
// TODO Shouldn't it fail it there are no providers? // TODO Shouldn't it fail it there are no providers?
if (providers != null) { if (providers != null) {
for (final Provider provider: providers) { for (final Provider provider : providers) {
final NetworkElement element = _ntwkModel.getElementImplementingProvider(provider.getName()); final NetworkElement element = _ntwkModel.getElementImplementingProvider(provider.getName());
final Map<Service, Map<Capability, String>> capabilities = element.getCapabilities(); final Map<Service, Map<Capability, String>> capabilities = element.getCapabilities();
if (capabilities != null && !capabilities.isEmpty()) { if (capabilities != null && !capabilities.isEmpty()) {
final Map<Capability, String> connectivityCapabilities = capabilities.get(service); final Map<Capability, String> connectivityCapabilities = capabilities.get(service);
if (connectivityCapabilities == null || connectivityCapabilities != null && if (connectivityCapabilities == null || connectivityCapabilities != null && !connectivityCapabilities.keySet().contains(capability)) {
!connectivityCapabilities.keySet().contains(capability)) { throw new InvalidParameterValueException(String.format("Provider %s does not support %s capability.", provider.getName(), capability.getName()));
throw new InvalidParameterValueException(String.format(
"Provider %s does not support %s capability.",
provider.getName(), capability.getName()));
} }
} }
} }
@ -507,7 +496,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
final Iterator iter = serviceCapabilityCollection.iterator(); final Iterator iter = serviceCapabilityCollection.iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
final HashMap<String, String> svcCapabilityMap = (HashMap<String, String>)iter.next(); final HashMap<String, String> svcCapabilityMap = (HashMap<String, String>) iter.next();
Capability capability = null; Capability capability = null;
final String svc = svcCapabilityMap.get(SERVICE); final String svc = svcCapabilityMap.get(SERVICE);
final String capabilityName = svcCapabilityMap.get(CAPABILITYTYPE); final String capabilityName = svcCapabilityMap.get(CAPABILITYTYPE);
@ -535,22 +524,21 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
if (serviceCapabilitystList != null && !serviceCapabilitystList.isEmpty()) { if (serviceCapabilitystList != null && !serviceCapabilitystList.isEmpty()) {
final Iterator iter = serviceCapabilitystList.values().iterator(); final Iterator iter = serviceCapabilitystList.values().iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
final HashMap<String, String> currentCapabilityMap = (HashMap<String, String>)iter.next(); final HashMap<String, String> currentCapabilityMap = (HashMap<String, String>) iter.next();
final String currentCapabilityService = currentCapabilityMap.get(SERVICE); final String currentCapabilityService = currentCapabilityMap.get(SERVICE);
final String currentCapabilityName = currentCapabilityMap.get(CAPABILITYTYPE); final String currentCapabilityName = currentCapabilityMap.get(CAPABILITYTYPE);
final String currentCapabilityValue = currentCapabilityMap.get(CAPABILITYVALUE); final String currentCapabilityValue = currentCapabilityMap.get(CAPABILITYVALUE);
if (currentCapabilityName == null || currentCapabilityService == null || currentCapabilityValue == null) { if (currentCapabilityName == null || currentCapabilityService == null || currentCapabilityValue == null) {
throw new InvalidParameterValueException(String.format("Invalid capability with name %s, value %s and service %s", throw new InvalidParameterValueException(String.format("Invalid capability with name %s, value %s and service %s", currentCapabilityName,
currentCapabilityName, currentCapabilityValue, currentCapabilityService)); currentCapabilityValue, currentCapabilityService));
} }
if (currentCapabilityName.equalsIgnoreCase(capability.getName())) { if (currentCapabilityName.equalsIgnoreCase(capability.getName())) {
foundCapability = currentCapabilityValue.equalsIgnoreCase(TRUE_VALUE); foundCapability = currentCapabilityValue.equalsIgnoreCase(TRUE_VALUE);
if (!currentCapabilityService.equalsIgnoreCase(service.getName())) { if (!currentCapabilityService.equalsIgnoreCase(service.getName())) {
throw new InvalidParameterValueException(String.format( throw new InvalidParameterValueException(String.format("Invalid Service: %s specified. Capability %s can be specified only for service %s",
"Invalid Service: %s specified. Capability %s can be specified only for service %s",
currentCapabilityService, service.getName(), currentCapabilityName)); currentCapabilityService, service.getName(), currentCapabilityName));
} }
@ -562,18 +550,15 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
} }
private boolean isVpcOfferingForRegionLevelVpc(final Map serviceCapabilitystList) { private boolean isVpcOfferingForRegionLevelVpc(final Map serviceCapabilitystList) {
return findCapabilityForService(serviceCapabilitystList, Capability.RegionLevelVpc, return findCapabilityForService(serviceCapabilitystList, Capability.RegionLevelVpc, Service.Connectivity);
Service.Connectivity);
} }
private boolean isVpcOfferingSupportsDistributedRouter(final Map serviceCapabilitystList) { private boolean isVpcOfferingSupportsDistributedRouter(final Map serviceCapabilitystList) {
return findCapabilityForService(serviceCapabilitystList, Capability.DistributedRouter, return findCapabilityForService(serviceCapabilitystList, Capability.DistributedRouter, Service.Connectivity);
Service.Connectivity);
} }
private boolean isVpcOfferingRedundantRouter(final Map serviceCapabilitystList) { private boolean isVpcOfferingRedundantRouter(final Map serviceCapabilitystList) {
return findCapabilityForService(serviceCapabilitystList, Capability.RedundantRouter, return findCapabilityForService(serviceCapabilitystList, Capability.RedundantRouter, Service.SourceNat);
Service.SourceNat);
} }
@Override @Override
@ -601,8 +586,8 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
} }
@Override @Override
public Pair<List<? extends VpcOffering>,Integer> listVpcOfferings(final Long id, final String name, final String displayText, final List<String> supportedServicesStr, final Boolean isDefault, final String keyword, public Pair<List<? extends VpcOffering>, Integer> listVpcOfferings(final Long id, final String name, final String displayText, final List<String> supportedServicesStr,
final String state, final Long startIndex, final Long pageSizeVal) { final Boolean isDefault, final String keyword, final String state, final Long startIndex, final Long pageSizeVal) {
final Filter searchFilter = new Filter(VpcOfferingVO.class, "created", false, null, null); final Filter searchFilter = new Filter(VpcOfferingVO.class, "created", false, null, null);
final SearchCriteria<VpcOfferingVO> sc = _vpcOffDao.createSearchCriteria(); final SearchCriteria<VpcOfferingVO> sc = _vpcOffDao.createSearchCriteria();
@ -699,11 +684,12 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
throw new InvalidParameterValueException("Default network offering can't be deleted"); throw new InvalidParameterValueException("Default network offering can't be deleted");
} }
// don't allow to delete vpc offering if it's in use by existing vpcs (the offering can be disabled though) // don't allow to delete vpc offering if it's in use by existing vpcs
// (the offering can be disabled though)
final int vpcCount = _vpcDao.getVpcCountByOfferingId(offId); final int vpcCount = _vpcDao.getVpcCountByOfferingId(offId);
if (vpcCount > 0) { if (vpcCount > 0) {
throw new InvalidParameterValueException("Can't delete vpc offering " + offId + " as its used by " + vpcCount + " vpcs. " + throw new InvalidParameterValueException("Can't delete vpc offering " + offId + " as its used by " + vpcCount + " vpcs. "
"To make the network offering unavaiable, disable it"); + "To make the network offering unavaiable, disable it");
} }
if (_vpcOffDao.remove(offId)) { if (_vpcOffDao.remove(offId)) {
@ -757,15 +743,15 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
@Override @Override
@ActionEvent(eventType = EventTypes.EVENT_VPC_CREATE, eventDescription = "creating vpc", create = true) @ActionEvent(eventType = EventTypes.EVENT_VPC_CREATE, eventDescription = "creating vpc", create = true)
public Vpc createVpc(final long zoneId, final long vpcOffId, final long vpcOwnerId, final String vpcName, final String displayText, final String cidr, String networkDomain, final Boolean displayVpc) public Vpc createVpc(final long zoneId, final long vpcOffId, final long vpcOwnerId, final String vpcName, final String displayText, final String cidr, String networkDomain,
throws ResourceAllocationException { final Boolean displayVpc) throws ResourceAllocationException {
final Account caller = CallContext.current().getCallingAccount(); final Account caller = CallContext.current().getCallingAccount();
final Account owner = _accountMgr.getAccount(vpcOwnerId); final Account owner = _accountMgr.getAccount(vpcOwnerId);
//Verify that caller can perform actions in behalf of vpc owner // Verify that caller can perform actions in behalf of vpc owner
_accountMgr.checkAccess(caller, null, false, owner); _accountMgr.checkAccess(caller, null, false, owner);
//check resource limit // check resource limit
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.vpc); _resourceLimitMgr.checkResourceLimit(owner, ResourceType.vpc);
// Validate vpc offering // Validate vpc offering
@ -785,7 +771,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
throw new InvalidParameterValueException("Network domain must be specified for region level VPC"); throw new InvalidParameterValueException("Network domain must be specified for region level VPC");
} }
//Validate zone // Validate zone
final DataCenter zone = _entityMgr.findById(DataCenter.class, zoneId); final DataCenter zone = _entityMgr.findById(DataCenter.class, zoneId);
if (zone == null) { if (zone == null) {
throw new InvalidParameterValueException("Can't find zone by id specified"); throw new InvalidParameterValueException("Can't find zone by id specified");
@ -802,15 +788,16 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
// 1) Get networkDomain from the corresponding account // 1) Get networkDomain from the corresponding account
networkDomain = _ntwkModel.getAccountNetworkDomain(owner.getId(), zoneId); networkDomain = _ntwkModel.getAccountNetworkDomain(owner.getId(), zoneId);
// 2) If null, generate networkDomain using domain suffix from the global config variables // 2) If null, generate networkDomain using domain suffix from the
// global config variables
if (networkDomain == null) { if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + NetworkOrchestrationService.GuestDomainSuffix.valueIn(zoneId); networkDomain = "cs" + Long.toHexString(owner.getId()) + NetworkOrchestrationService.GuestDomainSuffix.valueIn(zoneId);
} }
} }
final boolean useDistributedRouter = vpcOff.supportsDistributedRouter(); final boolean useDistributedRouter = vpcOff.supportsDistributedRouter();
final VpcVO vpc = new VpcVO(zoneId, vpcName, displayText, owner.getId(), owner.getDomainId(), vpcOffId, final VpcVO vpc = new VpcVO(zoneId, vpcName, displayText, owner.getId(), owner.getDomainId(), vpcOffId, cidr, networkDomain, useDistributedRouter, isRegionLevelVpcOff,
cidr, networkDomain, useDistributedRouter, isRegionLevelVpcOff, vpcOff.getRedundantRouter()); vpcOff.getRedundantRouter());
return createVpc(displayVpc, vpc); return createVpc(displayVpc, vpc);
} }
@ -818,12 +805,12 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
@DB @DB
protected Vpc createVpc(final Boolean displayVpc, final VpcVO vpc) { protected Vpc createVpc(final Boolean displayVpc, final VpcVO vpc) {
final String cidr = vpc.getCidr(); final String cidr = vpc.getCidr();
//Validate CIDR // Validate CIDR
if (!NetUtils.isValidCIDR(cidr)) { if (!NetUtils.isValidCIDR(cidr)) {
throw new InvalidParameterValueException("Invalid CIDR specified " + cidr); throw new InvalidParameterValueException("Invalid CIDR specified " + cidr);
} }
//cidr has to be RFC 1918 complient // cidr has to be RFC 1918 complient
if (!NetUtils.validateGuestCidr(cidr)) { if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Guest Cidr " + cidr + " is not RFC1918 compliant"); throw new InvalidParameterValueException("Guest Cidr " + cidr + " is not RFC1918 compliant");
} }
@ -893,7 +880,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
throw new InvalidParameterValueException("unable to find VPC id=" + vpcId); throw new InvalidParameterValueException("unable to find VPC id=" + vpcId);
} }
//verify permissions // verify permissions
_accountMgr.checkAccess(ctx.getCallingAccount(), null, false, vpc); _accountMgr.checkAccess(ctx.getCallingAccount(), null, false, vpc);
return destroyVpc(vpc, ctx.getCallingAccount(), ctx.getCallingUserId()); return destroyVpc(vpc, ctx.getCallingAccount(), ctx.getCallingUserId());
@ -904,14 +891,16 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
public boolean destroyVpc(final Vpc vpc, final Account caller, final Long callerUserId) throws ConcurrentOperationException, ResourceUnavailableException { public boolean destroyVpc(final Vpc vpc, final Account caller, final Long callerUserId) throws ConcurrentOperationException, ResourceUnavailableException {
s_logger.debug("Destroying vpc " + vpc); s_logger.debug("Destroying vpc " + vpc);
//don't allow to delete vpc if it's in use by existing non system networks (system networks are networks of a private gateway of the VPC, // don't allow to delete vpc if it's in use by existing non system
//and they will get removed as a part of VPC cleanup // networks (system networks are networks of a private gateway of the
// VPC,
// and they will get removed as a part of VPC cleanup
final int networksCount = _ntwkDao.getNonSystemNetworkCountByVpcId(vpc.getId()); final int networksCount = _ntwkDao.getNonSystemNetworkCountByVpcId(vpc.getId());
if (networksCount > 0) { if (networksCount > 0) {
throw new InvalidParameterValueException("Can't delete VPC " + vpc + " as its used by " + networksCount + " networks"); throw new InvalidParameterValueException("Can't delete VPC " + vpc + " as its used by " + networksCount + " networks");
} }
//mark VPC as inactive // mark VPC as inactive
if (vpc.getState() != Vpc.State.Inactive) { if (vpc.getState() != Vpc.State.Inactive) {
s_logger.debug("Updating VPC " + vpc + " with state " + Vpc.State.Inactive + " as a part of vpc delete"); s_logger.debug("Updating VPC " + vpc + " with state " + Vpc.State.Inactive + " as a part of vpc delete");
final VpcVO vpcVO = _vpcDao.findById(vpc.getId()); final VpcVO vpcVO = _vpcDao.findById(vpc.getId());
@ -922,25 +911,26 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
public void doInTransactionWithoutResult(final TransactionStatus status) { public void doInTransactionWithoutResult(final TransactionStatus status) {
_vpcDao.update(vpc.getId(), vpcVO); _vpcDao.update(vpc.getId(), vpcVO);
//decrement resource count // decrement resource count
_resourceLimitMgr.decrementResourceCount(vpc.getAccountId(), ResourceType.vpc); _resourceLimitMgr.decrementResourceCount(vpc.getAccountId(), ResourceType.vpc);
} }
}); });
} }
//shutdown VPC // shutdown VPC
if (!shutdownVpc(vpc.getId())) { if (!shutdownVpc(vpc.getId())) {
s_logger.warn("Failed to shutdown vpc " + vpc + " as a part of vpc destroy process"); s_logger.warn("Failed to shutdown vpc " + vpc + " as a part of vpc destroy process");
return false; return false;
} }
//cleanup vpc resources // cleanup vpc resources
if (!cleanupVpcResources(vpc.getId(), caller, callerUserId)) { if (!cleanupVpcResources(vpc.getId(), caller, callerUserId)) {
s_logger.warn("Failed to cleanup resources for vpc " + vpc); s_logger.warn("Failed to cleanup resources for vpc " + vpc);
return false; return false;
} }
//update the instance with removed flag only when the cleanup is executed successfully // update the instance with removed flag only when the cleanup is
// executed successfully
if (_vpcDao.remove(vpc.getId())) { if (_vpcDao.remove(vpc.getId())) {
s_logger.debug("Vpc " + vpc + " is destroyed succesfully"); s_logger.debug("Vpc " + vpc + " is destroyed succesfully");
return true; return true;
@ -991,15 +981,15 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
} }
@Override @Override
public Pair<List<? extends Vpc>, Integer> listVpcs(final Long id, final String vpcName, final String displayText, final List<String> supportedServicesStr, final String cidr, final Long vpcOffId, final String state, public Pair<List<? extends Vpc>, Integer> listVpcs(final Long id, final String vpcName, final String displayText, final List<String> supportedServicesStr, final String cidr,
final String accountName, Long domainId, final String keyword, final Long startIndex, final Long pageSizeVal, final Long zoneId, Boolean isRecursive, final Boolean listAll, final Boolean restartRequired, final Long vpcOffId, final String state, final String accountName, Long domainId, final String keyword, final Long startIndex, final Long pageSizeVal,
final Map<String, String> tags, final Long projectId, final Boolean display) { final Long zoneId, Boolean isRecursive, final Boolean listAll, final Boolean restartRequired, final Map<String, String> tags, final Long projectId,
final Boolean display) {
final Account caller = CallContext.current().getCallingAccount(); final Account caller = CallContext.current().getCallingAccount();
final List<Long> permittedAccounts = new ArrayList<Long>(); final List<Long> permittedAccounts = new ArrayList<Long>();
final Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, final Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(domainId, isRecursive,
ListProjectResourcesCriteria>(domainId, isRecursive, null); null);
_accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, domainIdRecursiveListProject, _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, domainIdRecursiveListProject, listAll, false);
listAll, false);
domainId = domainIdRecursiveListProject.first(); domainId = domainIdRecursiveListProject.first();
isRecursive = domainIdRecursiveListProject.second(); isRecursive = domainIdRecursiveListProject.second();
final ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); final ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
@ -1052,7 +1042,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
if (tags != null && !tags.isEmpty()) { if (tags != null && !tags.isEmpty()) {
int count = 0; int count = 0;
sc.setJoinParameters("tagSearch", "resourceType", ResourceObjectType.Vpc.toString()); sc.setJoinParameters("tagSearch", "resourceType", ResourceObjectType.Vpc.toString());
for (final Map.Entry<String,String>entry : tags.entrySet()) { for (final Map.Entry<String, String> entry : tags.entrySet()) {
sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), entry.getKey()); sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), entry.getKey());
sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), entry.getValue()); sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), entry.getValue());
count++; count++;
@ -1153,7 +1143,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
final Account caller = ctx.getCallingAccount(); final Account caller = ctx.getCallingAccount();
final User callerUser = _accountMgr.getActiveUser(ctx.getCallingUserId()); final User callerUser = _accountMgr.getActiveUser(ctx.getCallingUserId());
//check if vpc exists // check if vpc exists
final Vpc vpc = getActiveVpc(vpcId); final Vpc vpc = getActiveVpc(vpcId);
if (vpc == null) { if (vpc == null) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find Enabled VPC by id specified"); final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find Enabled VPC by id specified");
@ -1161,7 +1151,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
throw ex; throw ex;
} }
//permission check // permission check
_accountMgr.checkAccess(caller, null, false, vpc); _accountMgr.checkAccess(caller, null, false, vpc);
final DataCenter dc = _entityMgr.findById(DataCenter.class, vpc.getZoneId()); final DataCenter dc = _entityMgr.findById(DataCenter.class, vpc.getZoneId());
@ -1179,7 +1169,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
s_logger.warn("Failed to start vpc " + vpc + " due to ", ex); s_logger.warn("Failed to start vpc " + vpc + " due to ", ex);
result = false; result = false;
} finally { } finally {
//do cleanup // do cleanup
if (!result && destroyOnFailure) { if (!result && destroyOnFailure) {
s_logger.debug("Destroying vpc " + vpc + " that failed to start"); s_logger.debug("Destroying vpc " + vpc + " that failed to start");
if (destroyVpc(vpc, caller, callerUser.getId())) { if (destroyVpc(vpc, caller, callerUser.getId())) {
@ -1194,7 +1184,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
protected boolean startVpc(final Vpc vpc, final DeployDestination dest, final ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, protected boolean startVpc(final Vpc vpc, final DeployDestination dest, final ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException,
InsufficientCapacityException { InsufficientCapacityException {
//deploy provider // deploy provider
boolean success = true; boolean success = true;
final List<Provider> providersToImplement = getVpcProviders(vpc.getId()); final List<Provider> providersToImplement = getVpcProviders(vpc.getId());
for (final VpcProvider element : getVpcElements()) { for (final VpcProvider element : getVpcElements()) {
@ -1215,18 +1205,18 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
final CallContext ctx = CallContext.current(); final CallContext ctx = CallContext.current();
final Account caller = ctx.getCallingAccount(); final Account caller = ctx.getCallingAccount();
//check if vpc exists // check if vpc exists
final Vpc vpc = _vpcDao.findById(vpcId); final Vpc vpc = _vpcDao.findById(vpcId);
if (vpc == null) { if (vpc == null) {
throw new InvalidParameterValueException("Unable to find vpc by id " + vpcId); throw new InvalidParameterValueException("Unable to find vpc by id " + vpcId);
} }
//permission check // permission check
_accountMgr.checkAccess(caller, null, false, vpc); _accountMgr.checkAccess(caller, null, false, vpc);
//shutdown provider // shutdown provider
s_logger.debug("Shutting down vpc " + vpc); s_logger.debug("Shutting down vpc " + vpc);
//TODO - shutdown all vpc resources here (ACLs, gateways, etc) // TODO - shutdown all vpc resources here (ACLs, gateways, etc)
boolean success = true; boolean success = true;
final List<Provider> providersToImplement = getVpcProviders(vpc.getId()); final List<Provider> providersToImplement = getVpcProviders(vpc.getId());
@ -1247,8 +1237,8 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
@DB @DB
@Override @Override
public void validateNtwkOffForNtwkInVpc(final Long networkId, final long newNtwkOffId, final String newCidr, final String newNetworkDomain, final Vpc vpc, final String gateway, final Account networkOwner, public void validateNtwkOffForNtwkInVpc(final Long networkId, final long newNtwkOffId, final String newCidr, final String newNetworkDomain, final Vpc vpc,
final Long aclId) { final String gateway, final Account networkOwner, final Long aclId) {
final NetworkOffering guestNtwkOff = _entityMgr.findById(NetworkOffering.class, newNtwkOffId); final NetworkOffering guestNtwkOff = _entityMgr.findById(NetworkOffering.class, newNtwkOffId);
@ -1257,15 +1247,16 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
} }
if (networkId == null) { if (networkId == null) {
//1) Validate attributes that has to be passed in when create new guest network // 1) Validate attributes that has to be passed in when create new
// guest network
validateNewVpcGuestNetwork(newCidr, gateway, networkOwner, vpc, newNetworkDomain); validateNewVpcGuestNetwork(newCidr, gateway, networkOwner, vpc, newNetworkDomain);
} }
//2) validate network offering attributes // 2) validate network offering attributes
final List<Service> svcs = _ntwkModel.listNetworkOfferingServices(guestNtwkOff.getId()); final List<Service> svcs = _ntwkModel.listNetworkOfferingServices(guestNtwkOff.getId());
validateNtwkOffForVpc(guestNtwkOff, svcs); validateNtwkOffForVpc(guestNtwkOff, svcs);
//3) Check services/providers against VPC providers // 3) Check services/providers against VPC providers
final List<NetworkOfferingServiceMapVO> networkProviders = _ntwkOffServiceDao.listByNetworkOfferingId(guestNtwkOff.getId()); final List<NetworkOfferingServiceMapVO> networkProviders = _ntwkOffServiceDao.listByNetworkOfferingId(guestNtwkOff.getId());
for (final NetworkOfferingServiceMapVO nSvcVO : networkProviders) { for (final NetworkOfferingServiceMapVO nSvcVO : networkProviders) {
@ -1276,25 +1267,27 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
} }
} }
//4) Only one network in the VPC can support public LB inside the VPC. Internal LB can be supported on multiple VPC tiers // 4) Only one network in the VPC can support public LB inside the VPC.
// Internal LB can be supported on multiple VPC tiers
if (_ntwkModel.areServicesSupportedByNetworkOffering(guestNtwkOff.getId(), Service.Lb) && guestNtwkOff.getPublicLb()) { if (_ntwkModel.areServicesSupportedByNetworkOffering(guestNtwkOff.getId(), Service.Lb) && guestNtwkOff.getPublicLb()) {
final List<? extends Network> networks = getVpcNetworks(vpc.getId()); final List<? extends Network> networks = getVpcNetworks(vpc.getId());
for (final Network network : networks) { for (final Network network : networks) {
if (networkId != null && network.getId() == networkId.longValue()) { if (networkId != null && network.getId() == networkId.longValue()) {
//skip my own network // skip my own network
continue; continue;
} else { } else {
final NetworkOffering otherOff = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId()); final NetworkOffering otherOff = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId());
//throw only if networks have different offerings with public lb support // throw only if networks have different offerings with
if (_ntwkModel.areServicesSupportedInNetwork(network.getId(), Service.Lb) && otherOff.getPublicLb() && // public lb support
guestNtwkOff.getId() != otherOff.getId()) { if (_ntwkModel.areServicesSupportedInNetwork(network.getId(), Service.Lb) && otherOff.getPublicLb() && guestNtwkOff.getId() != otherOff.getId()) {
throw new InvalidParameterValueException("Public LB service is already supported " + "by network " + network + " in VPC " + vpc); throw new InvalidParameterValueException("Public LB service is already supported " + "by network " + network + " in VPC " + vpc);
} }
} }
} }
} }
//5) When aclId is provided, verify that ACLProvider is supported by network offering // 5) When aclId is provided, verify that ACLProvider is supported by
// network offering
if (aclId != null && !_ntwkModel.areServicesSupportedByNetworkOffering(guestNtwkOff.getId(), Service.NetworkACL)) { if (aclId != null && !_ntwkModel.areServicesSupportedByNetworkOffering(guestNtwkOff.getId(), Service.NetworkACL)) {
throw new InvalidParameterValueException("Cannot apply NetworkACL. Network Offering does not support NetworkACL service"); throw new InvalidParameterValueException("Cannot apply NetworkACL. Network Offering does not support NetworkACL service");
} }
@ -1303,7 +1296,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
@Override @Override
public void validateNtwkOffForVpc(final NetworkOffering guestNtwkOff, final List<Service> supportedSvcs) { public void validateNtwkOffForVpc(final NetworkOffering guestNtwkOff, final List<Service> supportedSvcs) {
//1) in current release, only vpc provider is supported by Vpc offering // 1) in current release, only vpc provider is supported by Vpc offering
final List<Provider> providers = _ntwkModel.getNtwkOffDistinctProviders(guestNtwkOff.getId()); final List<Provider> providers = _ntwkModel.getNtwkOffDistinctProviders(guestNtwkOff.getId());
for (final Provider provider : providers) { for (final Provider provider : providers) {
if (!supportedProviders.contains(provider)) { if (!supportedProviders.contains(provider)) {
@ -1311,26 +1304,28 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
} }
} }
//2) Only Isolated networks with Source nat service enabled can be added to vpc // 2) Only Isolated networks with Source nat service enabled can be
// added to vpc
if (!(guestNtwkOff.getGuestType() == GuestType.Isolated && supportedSvcs.contains(Service.SourceNat))) { if (!(guestNtwkOff.getGuestType() == GuestType.Isolated && supportedSvcs.contains(Service.SourceNat))) {
throw new InvalidParameterValueException("Only network offerings of type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + throw new InvalidParameterValueException("Only network offerings of type " + GuestType.Isolated + " with service " + Service.SourceNat.getName()
" are valid for vpc "); + " are valid for vpc ");
} }
//3) No redundant router support // 3) No redundant router support
/* TODO This should have never been hardcoded like this in the first place /*
if (guestNtwkOff.getRedundantRouter()) { * TODO This should have never been hardcoded like this in the first
throw new InvalidParameterValueException("No redunant router support when network belnogs to VPC"); * place if (guestNtwkOff.getRedundantRouter()) { throw new
} * InvalidParameterValueException
* ("No redunant router support when network belnogs to VPC"); }
*/ */
//4) Conserve mode should be off // 4) Conserve mode should be off
if (guestNtwkOff.isConserveMode()) { if (guestNtwkOff.isConserveMode()) {
throw new InvalidParameterValueException("Only networks with conserve mode Off can belong to VPC"); throw new InvalidParameterValueException("Only networks with conserve mode Off can belong to VPC");
} }
//5) If Netscaler is LB provider make sure it is in dedicated mode // 5) If Netscaler is LB provider make sure it is in dedicated mode
if (providers.contains(Provider.Netscaler) && !guestNtwkOff.getDedicatedLB()) { if (providers.contains(Provider.Netscaler) && !guestNtwkOff.getDedicatedLB()) {
throw new InvalidParameterValueException("Netscaler only with Dedicated LB can belong to VPC"); throw new InvalidParameterValueException("Netscaler only with Dedicated LB can belong to VPC");
} }
@ -1349,23 +1344,23 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
} }
try { try {
//check number of active networks in vpc // check number of active networks in vpc
if (_ntwkDao.countVpcNetworks(vpc.getId()) >= _maxNetworks) { if (_ntwkDao.countVpcNetworks(vpc.getId()) >= _maxNetworks) {
throw new CloudRuntimeException("Number of networks per VPC can't extend " + _maxNetworks + "; increase it using global config " + throw new CloudRuntimeException("Number of networks per VPC can't extend " + _maxNetworks + "; increase it using global config " + Config.VpcMaxNetworks);
Config.VpcMaxNetworks);
} }
//1) CIDR is required // 1) CIDR is required
if (cidr == null) { if (cidr == null) {
throw new InvalidParameterValueException("Gateway/netmask are required when create network for VPC"); throw new InvalidParameterValueException("Gateway/netmask are required when create network for VPC");
} }
//2) Network cidr should be within vpcCidr // 2) Network cidr should be within vpcCidr
if (!NetUtils.isNetworkAWithinNetworkB(cidr, vpc.getCidr())) { if (!NetUtils.isNetworkAWithinNetworkB(cidr, vpc.getCidr())) {
throw new InvalidParameterValueException("Network cidr " + cidr + " is not within vpc " + vpc + " cidr"); throw new InvalidParameterValueException("Network cidr " + cidr + " is not within vpc " + vpc + " cidr");
} }
//3) Network cidr shouldn't cross the cidr of other vpc network cidrs // 3) Network cidr shouldn't cross the cidr of other vpc
// network cidrs
final List<? extends Network> ntwks = _ntwkDao.listByVpc(vpc.getId()); final List<? extends Network> ntwks = _ntwkDao.listByVpc(vpc.getId());
for (final Network ntwk : ntwks) { for (final Network ntwk : ntwks) {
assert cidr != null : "Why the network cidr is null when it belongs to vpc?"; assert cidr != null : "Why the network cidr is null when it belongs to vpc?";
@ -1375,17 +1370,17 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
} }
} }
//4) vpc and network should belong to the same owner // 4) vpc and network should belong to the same owner
if (vpc.getAccountId() != networkOwner.getId()) { if (vpc.getAccountId() != networkOwner.getId()) {
throw new InvalidParameterValueException("Vpc " + vpc + " owner is different from the network owner " + networkOwner); throw new InvalidParameterValueException("Vpc " + vpc + " owner is different from the network owner " + networkOwner);
} }
//5) network domain should be the same as VPC's // 5) network domain should be the same as VPC's
if (!networkDomain.equalsIgnoreCase(vpc.getNetworkDomain())) { if (!networkDomain.equalsIgnoreCase(vpc.getNetworkDomain())) {
throw new InvalidParameterValueException("Network domain of the new network should match network" + " domain of vpc " + vpc); throw new InvalidParameterValueException("Network domain of the new network should match network" + " domain of vpc " + vpc);
} }
//6) gateway should never be equal to the cidr subnet // 6) gateway should never be equal to the cidr subnet
if (NetUtils.getCidrSubNet(cidr).equalsIgnoreCase(gateway)) { if (NetUtils.getCidrSubNet(cidr).equalsIgnoreCase(gateway)) {
throw new InvalidParameterValueException("Invalid gateway specified. It should never be equal to the cidr subnet value"); throw new InvalidParameterValueException("Invalid gateway specified. It should never be equal to the cidr subnet value");
} }
@ -1400,8 +1395,8 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
public List<VpcProvider> getVpcElements() { public List<VpcProvider> getVpcElements() {
if (vpcElements == null) { if (vpcElements == null) {
vpcElements = new ArrayList<VpcProvider>(); vpcElements = new ArrayList<VpcProvider>();
vpcElements.add((VpcProvider)_ntwkModel.getElementImplementingProvider(Provider.VPCVirtualRouter.getName())); vpcElements.add((VpcProvider) _ntwkModel.getElementImplementingProvider(Provider.VPCVirtualRouter.getName()));
vpcElements.add((VpcProvider)_ntwkModel.getElementImplementingProvider(Provider.JuniperContrailVpcRouter.getName())); vpcElements.add((VpcProvider) _ntwkModel.getElementImplementingProvider(Provider.JuniperContrailVpcRouter.getName()));
} }
if (vpcElements == null) { if (vpcElements == null) {
@ -1422,18 +1417,19 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
s_logger.debug("Cleaning up resources for vpc id=" + vpcId); s_logger.debug("Cleaning up resources for vpc id=" + vpcId);
boolean success = true; boolean success = true;
//1) Remove VPN connections and VPN gateway // 1) Remove VPN connections and VPN gateway
s_logger.debug("Cleaning up existed site to site VPN connections"); s_logger.debug("Cleaning up existed site to site VPN connections");
_s2sVpnMgr.cleanupVpnConnectionByVpc(vpcId); _s2sVpnMgr.cleanupVpnConnectionByVpc(vpcId);
s_logger.debug("Cleaning up existed site to site VPN gateways"); s_logger.debug("Cleaning up existed site to site VPN gateways");
_s2sVpnMgr.cleanupVpnGatewayByVpc(vpcId); _s2sVpnMgr.cleanupVpnGatewayByVpc(vpcId);
//2) release all ip addresses // 2) release all ip addresses
final List<IPAddressVO> ipsToRelease = _ipAddressDao.listByAssociatedVpc(vpcId, null); final List<IPAddressVO> ipsToRelease = _ipAddressDao.listByAssociatedVpc(vpcId, null);
s_logger.debug("Releasing ips for vpc id=" + vpcId + " as a part of vpc cleanup"); s_logger.debug("Releasing ips for vpc id=" + vpcId + " as a part of vpc cleanup");
for (final IPAddressVO ipToRelease : ipsToRelease) { for (final IPAddressVO ipToRelease : ipsToRelease) {
if (ipToRelease.isPortable()) { if (ipToRelease.isPortable()) {
// portable IP address are associated with owner, until explicitly requested to be disassociated. // portable IP address are associated with owner, until
// explicitly requested to be disassociated.
// so as part of VPC clean up just break IP association with VPC // so as part of VPC clean up just break IP association with VPC
ipToRelease.setVpcId(null); ipToRelease.setVpcId(null);
ipToRelease.setAssociatedWithNetworkId(null); ipToRelease.setAssociatedWithNetworkId(null);
@ -1451,16 +1447,17 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
s_logger.debug("Released ip addresses for vpc id=" + vpcId + " as a part of cleanup vpc process"); s_logger.debug("Released ip addresses for vpc id=" + vpcId + " as a part of cleanup vpc process");
} else { } else {
s_logger.warn("Failed to release ip addresses for vpc id=" + vpcId + " as a part of cleanup vpc process"); s_logger.warn("Failed to release ip addresses for vpc id=" + vpcId + " as a part of cleanup vpc process");
//although it failed, proceed to the next cleanup step as it doesn't depend on the public ip release // although it failed, proceed to the next cleanup step as it
// doesn't depend on the public ip release
} }
//3) Delete all static route rules // 3) Delete all static route rules
if (!revokeStaticRoutesForVpc(vpcId, caller)) { if (!revokeStaticRoutesForVpc(vpcId, caller)) {
s_logger.warn("Failed to revoke static routes for vpc " + vpcId + " as a part of cleanup vpc process"); s_logger.warn("Failed to revoke static routes for vpc " + vpcId + " as a part of cleanup vpc process");
return false; return false;
} }
//4) Delete private gateways // 4) Delete private gateways
final List<PrivateGateway> gateways = getVpcPrivateGateways(vpcId); final List<PrivateGateway> gateways = getVpcPrivateGateways(vpcId);
if (gateways != null) { if (gateways != null) {
for (final PrivateGateway gateway : gateways) { for (final PrivateGateway gateway : gateways) {
@ -1476,13 +1473,29 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
} }
} }
//5) Delete ACLs
final SearchBuilder<NetworkACLVO> searchBuilder = _networkAclDao.createSearchBuilder();
searchBuilder.and("vpcId", searchBuilder.entity().getVpcId(), Op.IN);
final SearchCriteria<NetworkACLVO> searchCriteria = searchBuilder.create();
searchCriteria.setParameters("vpcId", vpcId, 0);
final Filter filter = new Filter(NetworkACLVO.class, "id", false, null, null);
final Pair<List<NetworkACLVO>, Integer> aclsCountPair = _networkAclDao.searchAndCount(searchCriteria, filter);
final List<NetworkACLVO> acls = aclsCountPair.first();
for (final NetworkACLVO networkAcl : acls) {
if (networkAcl.getId() != NetworkACL.DEFAULT_ALLOW && networkAcl.getId() != NetworkACL.DEFAULT_DENY) {
_networkAclMgr.deleteNetworkACL(networkAcl);
}
}
return success; return success;
} }
@Override @Override
@ActionEvent(eventType = EventTypes.EVENT_VPC_RESTART, eventDescription = "restarting vpc") @ActionEvent(eventType = EventTypes.EVENT_VPC_RESTART, eventDescription = "restarting vpc")
public boolean restartVpc(final long vpcId, final boolean cleanUp, final boolean makeRedundant) throws ConcurrentOperationException, public boolean restartVpc(final long vpcId, final boolean cleanUp, final boolean makeRedundant) throws ConcurrentOperationException, ResourceUnavailableException,
ResourceUnavailableException, InsufficientCapacityException { InsufficientCapacityException {
final Account caller = CallContext.current().getCallingAccount(); final Account caller = CallContext.current().getCallingAccount();
@ -1508,10 +1521,12 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
entity.setRedundant(makeRedundant); entity.setRedundant(makeRedundant);
entity.setVpcOfferingId(redundantOffering.getId()); entity.setVpcOfferingId(redundantOffering.getId());
// Change the VPC in order to get it updated after the end of the restart procedure. // Change the VPC in order to get it updated after the end of
// the restart procedure.
_vpcDao.update(vpc.getId(), entity); _vpcDao.update(vpc.getId(), entity);
//If the offering and redundant column are changing, force the clean up. // If the offering and redundant column are changing, force the
// clean up.
forceCleanup = true; forceCleanup = true;
} }
@ -1579,7 +1594,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
final String netmask, final long gatewayOwnerId, final Long networkOfferingId, final Boolean isSourceNat, final Long aclId) throws ResourceAllocationException, final String netmask, final long gatewayOwnerId, final Long networkOfferingId, final Boolean isSourceNat, final Long aclId) throws ResourceAllocationException,
ConcurrentOperationException, InsufficientCapacityException { ConcurrentOperationException, InsufficientCapacityException {
//Validate parameters // Validate parameters
final Vpc vpc = getActiveVpc(vpcId); final Vpc vpc = getActiveVpc(vpcId);
if (vpc == null) { if (vpc == null) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find Enabled VPC by id specified"); final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find Enabled VPC by id specified");
@ -1588,7 +1603,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
} }
PhysicalNetwork physNet = null; PhysicalNetwork physNet = null;
//Validate physical network // Validate physical network
if (physicalNetworkId == null) { if (physicalNetworkId == null) {
final List<? extends PhysicalNetwork> pNtwks = _ntwkModel.getPhysicalNtwksSupportingTrafficType(vpc.getZoneId(), TrafficType.Guest); final List<? extends PhysicalNetwork> pNtwks = _ntwkModel.getPhysicalNtwksSupportingTrafficType(vpc.getZoneId(), TrafficType.Guest);
if (pNtwks.isEmpty() || pNtwks.size() != 1) { if (pNtwks.isEmpty() || pNtwks.size() != 1) {
@ -1612,28 +1627,30 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
public VpcGatewayVO doInTransaction(final TransactionStatus status) throws ResourceAllocationException, ConcurrentOperationException, public VpcGatewayVO doInTransaction(final TransactionStatus status) throws ResourceAllocationException, ConcurrentOperationException,
InsufficientCapacityException { InsufficientCapacityException {
s_logger.debug("Creating Private gateway for VPC " + vpc); s_logger.debug("Creating Private gateway for VPC " + vpc);
//1) create private network unless it is existing and lswitch'd // 1) create private network unless it is existing and
// lswitch'd
Network privateNtwk = null; Network privateNtwk = null;
if (BroadcastDomainType.getSchemeValue(BroadcastDomainType.fromString(broadcastUri)) == BroadcastDomainType.Lswitch) { if (BroadcastDomainType.getSchemeValue(BroadcastDomainType.fromString(broadcastUri)) == BroadcastDomainType.Lswitch) {
final String cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask); final String cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask);
privateNtwk = _ntwkDao.getPrivateNetwork(broadcastUri, cidr, gatewayOwnerId, dcId, networkOfferingId); privateNtwk = _ntwkDao.getPrivateNetwork(broadcastUri, cidr, gatewayOwnerId, dcId, networkOfferingId);
// if the dcid is different we get no network so next we try to create it // if the dcid is different we get no network so next we
// try to create it
} }
if (privateNtwk == null) { if (privateNtwk == null) {
s_logger.info("creating new network for vpc " + vpc + " using broadcast uri: " + broadcastUri); s_logger.info("creating new network for vpc " + vpc + " using broadcast uri: " + broadcastUri);
final String networkName = "vpc-" + vpc.getName() + "-privateNetwork"; final String networkName = "vpc-" + vpc.getName() + "-privateNetwork";
privateNtwk = privateNtwk = _ntwkSvc.createPrivateNetwork(networkName, networkName, physicalNetworkIdFinal, broadcastUri, ipAddress, null, gateway, netmask,
_ntwkSvc.createPrivateNetwork(networkName, networkName, physicalNetworkIdFinal, broadcastUri, ipAddress, null, gateway, netmask, gatewayOwnerId, vpcId, isSourceNat, networkOfferingId);
gatewayOwnerId, vpcId, isSourceNat, networkOfferingId); } else { // create the nic/ip as createPrivateNetwork
} else { // create the nic/ip as createPrivateNetwork doesn''t do that work for us now // doesn''t do that work for us now
s_logger.info("found and using existing network for vpc " + vpc + ": " + broadcastUri); s_logger.info("found and using existing network for vpc " + vpc + ": " + broadcastUri);
final DataCenterVO dc = _dcDao.lockRow(physNetFinal.getDataCenterId(), true); final DataCenterVO dc = _dcDao.lockRow(physNetFinal.getDataCenterId(), true);
//add entry to private_ip_address table // add entry to private_ip_address table
PrivateIpVO privateIp = _privateIpDao.findByIpAndSourceNetworkId(privateNtwk.getId(), ipAddress); PrivateIpVO privateIp = _privateIpDao.findByIpAndSourceNetworkId(privateNtwk.getId(), ipAddress);
if (privateIp != null) { if (privateIp != null) {
throw new InvalidParameterValueException("Private ip address " + ipAddress + " already used for private gateway" + " in zone " + throw new InvalidParameterValueException("Private ip address " + ipAddress + " already used for private gateway" + " in zone "
_entityMgr.findById(DataCenter.class, dcId).getName()); + _entityMgr.findById(DataCenter.class, dcId).getName());
} }
final Long mac = dc.getMacAddress(); final Long mac = dc.getMacAddress();
@ -1660,22 +1677,23 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
networkAclId = aclId; networkAclId = aclId;
} }
{ // experimental block, this is a hack { // experimental block, this is a hack
// set vpc id in network to null // set vpc id in network to null
// might be needed for all types of broadcast domains // might be needed for all types of broadcast domains
// the ugly hack is that vpc gateway nets are created as guest network // the ugly hack is that vpc gateway nets are created as
// guest network
// while they are not. // while they are not.
// A more permanent solution would be to define a type of 'gatewaynetwork' // A more permanent solution would be to define a type of
// 'gatewaynetwork'
// so that handling code is not mixed between the two // so that handling code is not mixed between the two
final NetworkVO gatewaynet = _ntwkDao.findById(privateNtwk.getId()); final NetworkVO gatewaynet = _ntwkDao.findById(privateNtwk.getId());
gatewaynet.setVpcId(null); gatewaynet.setVpcId(null);
_ntwkDao.persist(gatewaynet); _ntwkDao.persist(gatewaynet);
} }
//2) create gateway entry // 2) create gateway entry
final VpcGatewayVO gatewayVO = final VpcGatewayVO gatewayVO = new VpcGatewayVO(ipAddress, VpcGateway.Type.Private, vpcId, privateNtwk.getDataCenterId(), privateNtwk.getId(), broadcastUri,
new VpcGatewayVO(ipAddress, VpcGateway.Type.Private, vpcId, privateNtwk.getDataCenterId(), privateNtwk.getId(), broadcastUri, gateway, netmask, gateway, netmask, vpc.getAccountId(), vpc.getDomainId(), isSourceNat, networkAclId);
vpc.getAccountId(), vpc.getDomainId(), isSourceNat, networkAclId);
_vpcGatewayDao.persist(gatewayVO); _vpcGatewayDao.persist(gatewayVO);
s_logger.debug("Created vpc gateway entry " + gatewayVO); s_logger.debug("Created vpc gateway entry " + gatewayVO);
@ -1725,11 +1743,12 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
return null; return null;
} }
} finally { } finally {
//do cleanup // do cleanup
if (!success) { if (!success) {
if (destroyOnFailure) { if (destroyOnFailure) {
s_logger.debug("Destroying private gateway " + vo + " that failed to start"); s_logger.debug("Destroying private gateway " + vo + " that failed to start");
// calling deleting from db because on createprivategateway fail, destroyPrivateGateway is already called // calling deleting from db because on createprivategateway
// fail, destroyPrivateGateway is already called
if (deletePrivateGatewayFromTheDB(getVpcPrivateGateway(gatewayId))) { if (deletePrivateGatewayFromTheDB(getVpcPrivateGateway(gatewayId))) {
s_logger.warn("Successfully destroyed vpc " + vo + " that failed to start"); s_logger.warn("Successfully destroyed vpc " + vo + " that failed to start");
} else { } else {
@ -1754,11 +1773,12 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
Transaction.execute(new TransactionCallbackNoReturn() { Transaction.execute(new TransactionCallbackNoReturn() {
@Override @Override
public void doInTransactionWithoutResult(final TransactionStatus status) { public void doInTransactionWithoutResult(final TransactionStatus status) {
//don't allow to remove gateway when there are static routes associated with it // don't allow to remove gateway when there are static
// routes associated with it
final long routeCount = _staticRouteDao.countRoutesByGateway(gatewayVO.getId()); final long routeCount = _staticRouteDao.countRoutesByGateway(gatewayVO.getId());
if (routeCount > 0) { if (routeCount > 0) {
throw new CloudRuntimeException("Can't delete private gateway " + gatewayVO + " as it has " + routeCount + throw new CloudRuntimeException("Can't delete private gateway " + gatewayVO + " as it has " + routeCount
" static routes applied. Remove the routes first"); + " static routes applied. Remove the routes first");
} }
gatewayVO.setState(VpcGateway.State.Deleting); gatewayVO.setState(VpcGateway.State.Deleting);
@ -1767,7 +1787,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
} }
}); });
//1) delete the gateway on the backend // 1) delete the gateway on the backend
final List<Provider> providersToImplement = getVpcProviders(gatewayVO.getVpcId()); final List<Provider> providersToImplement = getVpcProviders(gatewayVO.getVpcId());
final PrivateGateway gateway = getVpcPrivateGateway(gatewayId); final PrivateGateway gateway = getVpcPrivateGateway(gatewayId);
for (final VpcProvider provider : getVpcElements()) { for (final VpcProvider provider : getVpcElements()) {
@ -1785,7 +1805,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
} }
} }
//2) Delete private gateway from the DB // 2) Delete private gateway from the DB
return deletePrivateGatewayFromTheDB(gateway); return deletePrivateGatewayFromTheDB(gateway);
} finally { } finally {
@ -1797,7 +1817,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
@DB @DB
protected boolean deletePrivateGatewayFromTheDB(final PrivateGateway gateway) { protected boolean deletePrivateGatewayFromTheDB(final PrivateGateway gateway) {
//check if there are ips allocted in the network // check if there are ips allocted in the network
final long networkId = gateway.getNetworkId(); final long networkId = gateway.getNetworkId();
vpcTxCallable.setGateway(gateway); vpcTxCallable.setGateway(gateway);
@ -1840,10 +1860,9 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
final Long projectId = cmd.getProjectId(); final Long projectId = cmd.getProjectId();
final Filter searchFilter = new Filter(VpcGatewayVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal()); final Filter searchFilter = new Filter(VpcGatewayVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal());
final Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, final Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(domainId, isRecursive,
ListProjectResourcesCriteria>(domainId, isRecursive, null); null);
_accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, domainIdRecursiveListProject, _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, domainIdRecursiveListProject, listAll, false);
listAll, false);
domainId = domainIdRecursiveListProject.first(); domainId = domainIdRecursiveListProject.first();
isRecursive = domainIdRecursiveListProject.second(); isRecursive = domainIdRecursiveListProject.second();
final ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); final ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
@ -1978,11 +1997,11 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
@DB @DB
protected boolean revokeStaticRoutesForVpc(final long vpcId, final Account caller) throws ResourceUnavailableException { protected boolean revokeStaticRoutesForVpc(final long vpcId, final Account caller) throws ResourceUnavailableException {
//get all static routes for the vpc // get all static routes for the vpc
final List<StaticRouteVO> routes = _staticRouteDao.listByVpcId(vpcId); final List<StaticRouteVO> routes = _staticRouteDao.listByVpcId(vpcId);
s_logger.debug("Found " + routes.size() + " to revoke for the vpc " + vpcId); s_logger.debug("Found " + routes.size() + " to revoke for the vpc " + vpcId);
if (!routes.isEmpty()) { if (!routes.isEmpty()) {
//mark all of them as revoke // mark all of them as revoke
Transaction.execute(new TransactionCallbackNoReturn() { Transaction.execute(new TransactionCallbackNoReturn() {
@Override @Override
public void doInTransactionWithoutResult(final TransactionStatus status) { public void doInTransactionWithoutResult(final TransactionStatus status) {
@ -2003,7 +2022,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
public StaticRoute createStaticRoute(final long gatewayId, final String cidr) throws NetworkRuleConflictException { public StaticRoute createStaticRoute(final long gatewayId, final String cidr) throws NetworkRuleConflictException {
final Account caller = CallContext.current().getCallingAccount(); final Account caller = CallContext.current().getCallingAccount();
//parameters validation // parameters validation
final VpcGateway gateway = _vpcGatewayDao.findById(gatewayId); final VpcGateway gateway = _vpcGatewayDao.findById(gatewayId);
if (gateway == null) { if (gateway == null) {
throw new InvalidParameterValueException("Invalid gateway id is given"); throw new InvalidParameterValueException("Invalid gateway id is given");
@ -2023,18 +2042,18 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
throw new InvalidParameterValueException("Invalid format for cidr " + cidr); throw new InvalidParameterValueException("Invalid format for cidr " + cidr);
} }
//validate the cidr // validate the cidr
//1) CIDR should be outside of VPC cidr for guest networks // 1) CIDR should be outside of VPC cidr for guest networks
if (NetUtils.isNetworksOverlap(vpc.getCidr(), cidr)) { if (NetUtils.isNetworksOverlap(vpc.getCidr(), cidr)) {
throw new InvalidParameterValueException("CIDR should be outside of VPC cidr " + vpc.getCidr()); throw new InvalidParameterValueException("CIDR should be outside of VPC cidr " + vpc.getCidr());
} }
//2) CIDR should be outside of link-local cidr // 2) CIDR should be outside of link-local cidr
if (NetUtils.isNetworksOverlap(vpc.getCidr(), NetUtils.getLinkLocalCIDR())) { if (NetUtils.isNetworksOverlap(vpc.getCidr(), NetUtils.getLinkLocalCIDR())) {
throw new InvalidParameterValueException("CIDR should be outside of link local cidr " + NetUtils.getLinkLocalCIDR()); throw new InvalidParameterValueException("CIDR should be outside of link local cidr " + NetUtils.getLinkLocalCIDR());
} }
//3) Verify against blacklisted routes // 3) Verify against blacklisted routes
if (isCidrBlacklisted(cidr, vpc.getZoneId())) { if (isCidrBlacklisted(cidr, vpc.getZoneId())) {
throw new InvalidParameterValueException("The static gateway cidr overlaps with one of the blacklisted routes of the zone the VPC belongs to"); throw new InvalidParameterValueException("The static gateway cidr overlaps with one of the blacklisted routes of the zone the VPC belongs to");
} }
@ -2089,10 +2108,9 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
final Map<String, String> tags = cmd.getTags(); final Map<String, String> tags = cmd.getTags();
final Long projectId = cmd.getProjectId(); final Long projectId = cmd.getProjectId();
final Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, final Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(domainId, isRecursive,
ListProjectResourcesCriteria>(domainId, isRecursive, null); null);
_accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, domainIdRecursiveListProject, _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, domainIdRecursiveListProject, listAll, false);
listAll, false);
domainId = domainIdRecursiveListProject.first(); domainId = domainIdRecursiveListProject.first();
isRecursive = domainIdRecursiveListProject.second(); isRecursive = domainIdRecursiveListProject.second();
final ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); final ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
@ -2146,8 +2164,9 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
} }
protected void detectRoutesConflict(final StaticRoute newRoute) throws NetworkRuleConflictException { protected void detectRoutesConflict(final StaticRoute newRoute) throws NetworkRuleConflictException {
//Multiple private gateways can exist within Vpc. Check for conflicts for all static routes in Vpc // Multiple private gateways can exist within Vpc. Check for conflicts
//and not just the gateway // for all static routes in Vpc
// and not just the gateway
final List<? extends StaticRoute> routes = _staticRouteDao.listByVpcIdAndNotRevoked(newRoute.getVpcId()); final List<? extends StaticRoute> routes = _staticRouteDao.listByVpcIdAndNotRevoked(newRoute.getVpcId());
assert routes.size() >= 1 : "For static routes, we now always first persist the route and then check for " assert routes.size() >= 1 : "For static routes, we now always first persist the route and then check for "
+ "network conflicts so we should at least have one rule at this point."; + "network conflicts so we should at least have one rule at this point.";
@ -2220,8 +2239,8 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
@DB @DB
@Override @Override
@ActionEvent(eventType = EventTypes.EVENT_NET_IP_ASSIGN, eventDescription = "associating Ip", async = true) @ActionEvent(eventType = EventTypes.EVENT_NET_IP_ASSIGN, eventDescription = "associating Ip", async = true)
public IpAddress associateIPToVpc(final long ipId, final long vpcId) throws ResourceAllocationException, ResourceUnavailableException, public IpAddress associateIPToVpc(final long ipId, final long vpcId) throws ResourceAllocationException, ResourceUnavailableException, InsufficientAddressCapacityException,
InsufficientAddressCapacityException, ConcurrentOperationException { ConcurrentOperationException {
final Account caller = CallContext.current().getCallingAccount(); final Account caller = CallContext.current().getCallingAccount();
Account owner = null; Account owner = null;
@ -2254,13 +2273,13 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
@Override @Override
public void doInTransactionWithoutResult(final TransactionStatus status) { public void doInTransactionWithoutResult(final TransactionStatus status) {
final IPAddressVO ip = _ipAddressDao.findById(ipId); final IPAddressVO ip = _ipAddressDao.findById(ipId);
//update ip address with networkId // update ip address with networkId
ip.setVpcId(vpcId); ip.setVpcId(vpcId);
ip.setSourceNat(isSourceNatFinal); ip.setSourceNat(isSourceNatFinal);
_ipAddressDao.update(ipId, ip); _ipAddressDao.update(ipId, ip);
//mark ip as allocated // mark ip as allocated
_ipAddrMgr.markPublicIpAsAllocated(ip); _ipAddrMgr.markPublicIpAsAllocated(ip);
} }
}); });
@ -2283,10 +2302,10 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
s_logger.debug("Releasing VPC ip address " + ip + " from vpc network id=" + networkId); s_logger.debug("Releasing VPC ip address " + ip + " from vpc network id=" + networkId);
final long vpcId = ip.getVpcId(); final long vpcId = ip.getVpcId();
boolean success = false; boolean success = false;
try { try {
//unassign ip from the VPC router // unassign ip from the VPC router
success = _ipAddrMgr.applyIpAssociations(_ntwkModel.getNetwork(networkId), true); success = _ipAddrMgr.applyIpAssociations(_ntwkModel.getNetwork(networkId), true);
} catch (final ResourceUnavailableException ex) { } catch (final ResourceUnavailableException ex) {
throw new CloudRuntimeException("Failed to apply ip associations for network id=" + networkId + " as a part of unassigning ip " + ipId + " from vpc", ex); throw new CloudRuntimeException("Failed to apply ip associations for network id=" + networkId + " as a part of unassigning ip " + ipId + " from vpc", ex);
@ -2309,9 +2328,10 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
@DB @DB
@Override @Override
public Network createVpcGuestNetwork(final long ntwkOffId, final String name, final String displayText, final String gateway, final String cidr, final String vlanId, String networkDomain, public Network createVpcGuestNetwork(final long ntwkOffId, final String name, final String displayText, final String gateway, final String cidr, final String vlanId,
final Account owner, final Long domainId, final PhysicalNetwork pNtwk, final long zoneId, final ACLType aclType, final Boolean subdomainAccess, final long vpcId, final Long aclId, final Account caller, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk, final long zoneId, final ACLType aclType, final Boolean subdomainAccess,
final Boolean isDisplayNetworkEnabled) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException { final long vpcId, final Long aclId, final Account caller, final Boolean isDisplayNetworkEnabled) throws ConcurrentOperationException, InsufficientCapacityException,
ResourceAllocationException {
final Vpc vpc = getActiveVpc(vpcId); final Vpc vpc = getActiveVpc(vpcId);
@ -2330,17 +2350,16 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
throw new InvalidParameterValueException("New network doesn't belong to vpc zone"); throw new InvalidParameterValueException("New network doesn't belong to vpc zone");
} }
//1) Validate if network can be created for VPC // 1) Validate if network can be created for VPC
validateNtwkOffForNtwkInVpc(null, ntwkOffId, cidr, networkDomain, vpc, gateway, owner, aclId); validateNtwkOffForNtwkInVpc(null, ntwkOffId, cidr, networkDomain, vpc, gateway, owner, aclId);
//2) Create network // 2) Create network
final Network guestNetwork = final Network guestNetwork = _ntwkMgr.createGuestNetwork(ntwkOffId, name, displayText, gateway, cidr, vlanId, networkDomain, owner, domainId, pNtwk, zoneId, aclType,
_ntwkMgr.createGuestNetwork(ntwkOffId, name, displayText, gateway, cidr, vlanId, networkDomain, owner, domainId, pNtwk, zoneId, aclType, subdomainAccess, subdomainAccess, vpcId, null, null, isDisplayNetworkEnabled, null);
vpcId, null, null, isDisplayNetworkEnabled, null);
if (guestNetwork != null) { if (guestNetwork != null) {
guestNetwork.setNetworkACLId(aclId); guestNetwork.setNetworkACLId(aclId);
_ntwkDao.update(guestNetwork.getId(), (NetworkVO)guestNetwork); _ntwkDao.update(guestNetwork.getId(), (NetworkVO) guestNetwork);
} }
return guestNetwork; return guestNetwork;
} }

View File

@ -22,7 +22,6 @@ import java.util.UUID;
import javax.inject.Inject; import javax.inject.Inject;
import com.cloud.user.User;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.context.CallContext;
@ -53,6 +52,7 @@ import com.cloud.network.dao.NetworkDao;
import com.cloud.network.dao.NetworkVO; import com.cloud.network.dao.NetworkVO;
import com.cloud.network.element.NetworkACLServiceProvider; import com.cloud.network.element.NetworkACLServiceProvider;
import com.cloud.network.vpc.NetworkACLItem; import com.cloud.network.vpc.NetworkACLItem;
import com.cloud.network.vpc.NetworkACLItem.State;
import com.cloud.network.vpc.NetworkACLItemDao; import com.cloud.network.vpc.NetworkACLItemDao;
import com.cloud.network.vpc.NetworkACLItemVO; import com.cloud.network.vpc.NetworkACLItemVO;
import com.cloud.network.vpc.NetworkACLManager; import com.cloud.network.vpc.NetworkACLManager;
@ -69,10 +69,10 @@ import com.cloud.tags.dao.ResourceTagDao;
import com.cloud.user.Account; import com.cloud.user.Account;
import com.cloud.user.AccountManager; import com.cloud.user.AccountManager;
import com.cloud.user.AccountVO; import com.cloud.user.AccountVO;
import com.cloud.user.User;
import com.cloud.user.UserVO; import com.cloud.user.UserVO;
import com.cloud.utils.component.ComponentContext; import com.cloud.utils.component.ComponentContext;
import com.cloud.utils.db.EntityManager; import com.cloud.utils.db.EntityManager;
import com.cloud.utils.exception.CloudRuntimeException;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class) @ContextConfiguration(loader = AnnotationConfigContextLoader.class)
@ -110,8 +110,8 @@ public class NetworkACLManagerTest extends TestCase {
@Before @Before
public void setUp() { public void setUp() {
ComponentContext.initComponentsLifeCycle(); ComponentContext.initComponentsLifeCycle();
Account account = new AccountVO("testaccount", 1, "testdomain", (short)0, UUID.randomUUID().toString()); final Account account = new AccountVO("testaccount", 1, "testdomain", (short)0, UUID.randomUUID().toString());
UserVO user = new UserVO(1, "testuser", "password", "firstname", "lastName", "email", "timezone", UUID.randomUUID().toString(), User.Source.UNKNOWN); final UserVO user = new UserVO(1, "testuser", "password", "firstname", "lastName", "email", "timezone", UUID.randomUUID().toString(), User.Source.UNKNOWN);
CallContext.register(user, account); CallContext.register(user, account);
acl = Mockito.mock(NetworkACLVO.class); acl = Mockito.mock(NetworkACLVO.class);
@ -133,10 +133,10 @@ public class NetworkACLManagerTest extends TestCase {
@Test @Test
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void testApplyACL() throws Exception { public void testApplyACL() throws Exception {
NetworkVO network = Mockito.mock(NetworkVO.class); final NetworkVO network = Mockito.mock(NetworkVO.class);
Mockito.when(_networkDao.findById(Matchers.anyLong())).thenReturn(network); Mockito.when(_networkDao.findById(Matchers.anyLong())).thenReturn(network);
Mockito.when(_networkModel.isProviderSupportServiceInNetwork(Matchers.anyLong(), Matchers.any(Network.Service.class), Matchers.any(Network.Provider.class))) Mockito.when(_networkModel.isProviderSupportServiceInNetwork(Matchers.anyLong(), Matchers.any(Network.Service.class), Matchers.any(Network.Provider.class)))
.thenReturn(true); .thenReturn(true);
Mockito.when(_networkAclElements.get(0).applyNetworkACLs(Matchers.any(Network.class), Matchers.anyList())).thenReturn(true); Mockito.when(_networkAclElements.get(0).applyNetworkACLs(Matchers.any(Network.class), Matchers.anyList())).thenReturn(true);
assertTrue(_aclMgr.applyACLToNetwork(1L)); assertTrue(_aclMgr.applyACLToNetwork(1L));
} }
@ -149,21 +149,21 @@ public class NetworkACLManagerTest extends TestCase {
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void driveTestApplyNetworkACL(boolean result, boolean applyNetworkACLs, boolean applyACLToPrivateGw) throws Exception { public void driveTestApplyNetworkACL(final boolean result, final boolean applyNetworkACLs, final boolean applyACLToPrivateGw) throws Exception {
// In order to test ONLY our scope method, we mock the others // In order to test ONLY our scope method, we mock the others
NetworkACLManager aclManager = Mockito.spy(_aclMgr); final NetworkACLManager aclManager = Mockito.spy(_aclMgr);
// Prepare // Prepare
// Reset mocked objects to reuse // Reset mocked objects to reuse
Mockito.reset(_networkACLItemDao); Mockito.reset(_networkACLItemDao);
// Make sure it is handled // Make sure it is handled
long aclId = 1L; final long aclId = 1L;
NetworkVO network = Mockito.mock(NetworkVO.class); final NetworkVO network = Mockito.mock(NetworkVO.class);
List<NetworkVO> networks = new ArrayList<NetworkVO>(); final List<NetworkVO> networks = new ArrayList<NetworkVO>();
networks.add(network); networks.add(network);
Mockito.when(_networkDao.listByAclId(Matchers.anyLong())) Mockito.when(_networkDao.listByAclId(Matchers.anyLong()))
.thenReturn(networks); .thenReturn(networks);
Mockito.when(_networkDao.findById(Matchers.anyLong())).thenReturn(network); Mockito.when(_networkDao.findById(Matchers.anyLong())).thenReturn(network);
Mockito.when(_networkModel.isProviderSupportServiceInNetwork(Matchers.anyLong(), Mockito.when(_networkModel.isProviderSupportServiceInNetwork(Matchers.anyLong(),
Matchers.any(Network.Service.class), Matchers.any(Network.Provider.class))) Matchers.any(Network.Service.class), Matchers.any(Network.Provider.class)))
@ -172,21 +172,21 @@ public class NetworkACLManagerTest extends TestCase {
Matchers.anyList())).thenReturn(applyNetworkACLs); Matchers.anyList())).thenReturn(applyNetworkACLs);
// Make sure it applies ACL to private gateway // Make sure it applies ACL to private gateway
List<VpcGatewayVO> vpcGateways = new ArrayList<VpcGatewayVO>(); final List<VpcGatewayVO> vpcGateways = new ArrayList<VpcGatewayVO>();
VpcGatewayVO vpcGateway = Mockito.mock(VpcGatewayVO.class); final VpcGatewayVO vpcGateway = Mockito.mock(VpcGatewayVO.class);
PrivateGateway privateGateway = Mockito.mock(PrivateGateway.class); final PrivateGateway privateGateway = Mockito.mock(PrivateGateway.class);
Mockito.when(_vpcSvc.getVpcPrivateGateway(Mockito.anyLong())).thenReturn(privateGateway); Mockito.when(_vpcSvc.getVpcPrivateGateway(Mockito.anyLong())).thenReturn(privateGateway);
vpcGateways.add(vpcGateway); vpcGateways.add(vpcGateway);
Mockito.when(_vpcGatewayDao.listByAclIdAndType(aclId, VpcGateway.Type.Private)) Mockito.when(_vpcGatewayDao.listByAclIdAndType(aclId, VpcGateway.Type.Private))
.thenReturn(vpcGateways); .thenReturn(vpcGateways);
// Create 4 rules to test all 4 scenarios: only revoke should // Create 4 rules to test all 4 scenarios: only revoke should
// be deleted, only add should update // be deleted, only add should update
List<NetworkACLItemVO> rules = new ArrayList<NetworkACLItemVO>(); final List<NetworkACLItemVO> rules = new ArrayList<NetworkACLItemVO>();
NetworkACLItemVO ruleActive = Mockito.mock(NetworkACLItemVO.class); final NetworkACLItemVO ruleActive = Mockito.mock(NetworkACLItemVO.class);
NetworkACLItemVO ruleStaged = Mockito.mock(NetworkACLItemVO.class); final NetworkACLItemVO ruleStaged = Mockito.mock(NetworkACLItemVO.class);
NetworkACLItemVO rule2Revoke = Mockito.mock(NetworkACLItemVO.class); final NetworkACLItemVO rule2Revoke = Mockito.mock(NetworkACLItemVO.class);
NetworkACLItemVO rule2Add = Mockito.mock(NetworkACLItemVO.class); final NetworkACLItemVO rule2Add = Mockito.mock(NetworkACLItemVO.class);
Mockito.when(ruleActive.getState()).thenReturn(NetworkACLItem.State.Active); Mockito.when(ruleActive.getState()).thenReturn(NetworkACLItem.State.Active);
Mockito.when(ruleStaged.getState()).thenReturn(NetworkACLItem.State.Staged); Mockito.when(ruleStaged.getState()).thenReturn(NetworkACLItem.State.Staged);
Mockito.when(rule2Add.getState()).thenReturn(NetworkACLItem.State.Add); Mockito.when(rule2Add.getState()).thenReturn(NetworkACLItem.State.Add);
@ -196,15 +196,15 @@ public class NetworkACLManagerTest extends TestCase {
rules.add(rule2Add); rules.add(rule2Add);
rules.add(rule2Revoke); rules.add(rule2Revoke);
long revokeId = 8; final long revokeId = 8;
Mockito.when(rule2Revoke.getId()).thenReturn(revokeId); Mockito.when(rule2Revoke.getId()).thenReturn(revokeId);
long addId = 9; final long addId = 9;
Mockito.when(rule2Add.getId()).thenReturn(addId); Mockito.when(rule2Add.getId()).thenReturn(addId);
Mockito.when(_networkACLItemDao.findById(addId)).thenReturn(rule2Add); Mockito.when(_networkACLItemDao.findById(addId)).thenReturn(rule2Add);
Mockito.when(_networkACLItemDao.listByACL(aclId)) Mockito.when(_networkACLItemDao.listByACL(aclId))
.thenReturn(rules); .thenReturn(rules);
// Mock methods to avoid // Mock methods to avoid
Mockito.doReturn(applyACLToPrivateGw).when(aclManager).applyACLToPrivateGw(privateGateway); Mockito.doReturn(applyACLToPrivateGw).when(aclManager).applyACLToPrivateGw(privateGateway);
@ -212,7 +212,7 @@ public class NetworkACLManagerTest extends TestCase {
assertEquals("Result was not congruent with applyNetworkACLs and applyACLToPrivateGw", result, aclManager.applyNetworkACL(aclId)); assertEquals("Result was not congruent with applyNetworkACLs and applyACLToPrivateGw", result, aclManager.applyNetworkACL(aclId));
// Assert if conditions met, network ACL was applied // Assert if conditions met, network ACL was applied
int timesProcessingDone = (applyNetworkACLs && applyACLToPrivateGw) ? 1 : 0; final int timesProcessingDone = applyNetworkACLs && applyACLToPrivateGw ? 1 : 0;
Mockito.verify(_networkACLItemDao, Mockito.times(timesProcessingDone)).remove(revokeId); Mockito.verify(_networkACLItemDao, Mockito.times(timesProcessingDone)).remove(revokeId);
Mockito.verify(rule2Add, Mockito.times(timesProcessingDone)).setState(NetworkACLItem.State.Active); Mockito.verify(rule2Add, Mockito.times(timesProcessingDone)).setState(NetworkACLItem.State.Active);
Mockito.verify(_networkACLItemDao, Mockito.times(timesProcessingDone)).update(addId, rule2Add); Mockito.verify(_networkACLItemDao, Mockito.times(timesProcessingDone)).update(addId, rule2Add);
@ -232,17 +232,27 @@ public class NetworkACLManagerTest extends TestCase {
assertNotNull(_aclMgr.updateNetworkACLItem(1L, "UDP", null, NetworkACLItem.TrafficType.Ingress, "Deny", 10, 22, 32, null, null, null, true)); assertNotNull(_aclMgr.updateNetworkACLItem(1L, "UDP", null, NetworkACLItem.TrafficType.Ingress, "Deny", 10, 22, 32, null, null, null, true));
} }
@Test(expected = CloudRuntimeException.class) @Test
public void deleteNonEmptyACL() throws Exception { public void deleteNonEmptyACL() throws Exception {
List<NetworkACLItemVO> aclItems = new ArrayList<NetworkACLItemVO>(); final List<NetworkACLItemVO> aclItems = new ArrayList<NetworkACLItemVO>();
aclItems.add(aclItem); aclItems.add(aclItem);
Mockito.when(_networkACLItemDao.listByACL(Matchers.anyLong())).thenReturn(aclItems); Mockito.when(_networkACLItemDao.listByACL(Matchers.anyLong())).thenReturn(aclItems);
_aclMgr.deleteNetworkACL(acl); Mockito.when(acl.getId()).thenReturn(3l);
Mockito.when(_networkACLItemDao.findById(Matchers.anyLong())).thenReturn(aclItem);
Mockito.when(aclItem.getState()).thenReturn(State.Add);
Mockito.when(aclItem.getId()).thenReturn(3l);
Mockito.when(_networkACLDao.remove(Matchers.anyLong())).thenReturn(true);
final boolean result = _aclMgr.deleteNetworkACL(acl);
Mockito.verify(aclItem, Mockito.times(4)).getState();
assertTrue("Operation should be successfull!", result);
} }
@Configuration @Configuration
@ComponentScan(basePackageClasses = {NetworkACLManagerImpl.class}, includeFilters = {@ComponentScan.Filter(value = NetworkACLTestConfiguration.Library.class, @ComponentScan(basePackageClasses = {NetworkACLManagerImpl.class}, includeFilters = {@ComponentScan.Filter(value = NetworkACLTestConfiguration.Library.class,
type = FilterType.CUSTOM)}, useDefaultFilters = false) type = FilterType.CUSTOM)}, useDefaultFilters = false)
public static class NetworkACLTestConfiguration extends SpringUtils.CloudStackTestConfiguration { public static class NetworkACLTestConfiguration extends SpringUtils.CloudStackTestConfiguration {
@Bean @Bean
@ -317,9 +327,9 @@ public class NetworkACLManagerTest extends TestCase {
public static class Library implements TypeFilter { public static class Library implements TypeFilter {
@Override @Override
public boolean match(MetadataReader mdr, MetadataReaderFactory arg1) throws IOException { public boolean match(final MetadataReader mdr, final MetadataReaderFactory arg1) throws IOException {
mdr.getClassMetadata().getClassName(); mdr.getClassMetadata().getClassName();
ComponentScan cs = NetworkACLTestConfiguration.class.getAnnotation(ComponentScan.class); final ComponentScan cs = NetworkACLTestConfiguration.class.getAnnotation(ComponentScan.class);
return SpringUtils.includedInBasePackageClasses(mdr.getClassMetadata().getClassName(), cs); return SpringUtils.includedInBasePackageClasses(mdr.getClassMetadata().getClassName(), cs);
} }
} }

View File

@ -939,26 +939,6 @@ def main(argv):
metadata = CsVmMetadata('vmdata', config) metadata = CsVmMetadata('vmdata', config)
metadata.process() metadata.process()
# Always run both CsAcl().process() methods
# They fill the base rules in config.fw[]
acls = CsAcl('networkacl', config)
acls.process()
acls = CsAcl('firewallrules', config)
acls.process()
fwd = CsForwardingRules("forwardingrules", config)
fwd.process()
vpns = CsSite2SiteVpn("site2sitevpn", config)
vpns.process()
rvpn = CsRemoteAccessVpn("remoteaccessvpn", config)
rvpn.process()
lb = CsLoadBalancer("loadbalancer", config)
lb.process()
if process_file in ["cmd_line.json", "network_acl.json"]: if process_file in ["cmd_line.json", "network_acl.json"]:
logging.debug("Configuring networkacl") logging.debug("Configuring networkacl")
iptables_change = True iptables_change = True
@ -1000,10 +980,34 @@ def main(argv):
# If iptable rules have changed, apply them. # If iptable rules have changed, apply them.
if iptables_change: if iptables_change:
acls = CsAcl('networkacl', config)
acls.process()
acls = CsAcl('firewallrules', config)
acls.process()
fwd = CsForwardingRules("forwardingrules", config)
fwd.process()
vpns = CsSite2SiteVpn("site2sitevpn", config)
vpns.process()
rvpn = CsRemoteAccessVpn("remoteaccessvpn", config)
rvpn.process()
lb = CsLoadBalancer("loadbalancer", config)
lb.process()
logging.debug("Configuring iptables rules") logging.debug("Configuring iptables rules")
nf = CsNetfilters() nf = CsNetfilters()
nf.compare(config.get_fw()) nf.compare(config.get_fw())
logging.debug("Configuring iptables rules done ...saving rules")
# Save iptables configuration - will be loaded on reboot by the iptables-restore that is configured on /etc/rc.local
CsHelper.save_iptables("iptables-save", "/etc/iptables/router_rules.v4")
CsHelper.save_iptables("ip6tables-save", "/etc/iptables/router_rules.v6")
red = CsRedundant(config) red = CsRedundant(config)
red.set() red.set()
@ -1012,12 +1016,5 @@ def main(argv):
static_routes = CsStaticRoutes("staticroutes", config) static_routes = CsStaticRoutes("staticroutes", config)
static_routes.process() static_routes.process()
if iptables_change:
logging.debug("Configuring iptables rules done ...saving rules")
# Save iptables configuration - will be loaded on reboot by the iptables-restore that is configured on /etc/rc.local
CsHelper.save_iptables("iptables-save", "/etc/iptables/router_rules.v4")
CsHelper.save_iptables("ip6tables-save", "/etc/iptables/router_rules.v6")
if __name__ == "__main__": if __name__ == "__main__":
main(sys.argv) main(sys.argv)

View File

@ -2489,7 +2489,7 @@ div.detail-group.actions td {
padding: 1px 0 0; padding: 1px 0 0;
/*+placement:shift -174px -57px;*/ /*+placement:shift -174px -57px;*/
position: relative; position: relative;
left: -174px; left: -239px;
top: -57px; top: -57px;
} }
@ -2555,7 +2555,7 @@ div.detail-group.actions td {
margin: 0; margin: 0;
position: absolute; position: absolute;
top: -47px; top: -47px;
left: 1090px; left: 1025px;
cursor: default !important; cursor: default !important;
display: inline-block; display: inline-block;
float: left; float: left;
@ -2568,8 +2568,8 @@ div.detail-group.actions td {
padding: 9px 18px 7px 12px; padding: 9px 18px 7px 12px;
border-right: none; border-right: none;
/*[empty]border-top:;*/ /*[empty]border-top:;*/
min-width: 75px; min-width: 110px;
max-width: 120px; max-width: 220px;
text-align: center; text-align: center;
height: 12px; height: 12px;
overflow: hidden; overflow: hidden;
@ -4310,7 +4310,7 @@ textarea {
#user-options { #user-options {
background: #FFFFFF; background: #FFFFFF;
z-index: 10000; z-index: 10000;
width: 104px; width: 150px;
position: absolute; position: absolute;
padding: 15px; padding: 15px;
top: 30px; top: 30px;

View File

@ -225,7 +225,7 @@
.append( .append(
$('<div>').addClass('name').text( $('<div>').addClass('name').text(
args.context && args.context.users ? args.context && args.context.users ?
cloudStack.concat(userLabel, 14) : 'Invalid User' cloudStack.concat(userLabel, 21) : 'Invalid User'
) )
) )
.append( .append(