You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by mc...@apache.org on 2014/01/17 23:40:41 UTC

[39/50] [abbrv] Merge branch 'master' into rbac.

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/server/src/com/cloud/network/vpc/NetworkACLServiceImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/network/vpc/NetworkACLServiceImpl.java
index d2b1b4a,e5a59ff..2ab34c5
--- a/server/src/com/cloud/network/vpc/NetworkACLServiceImpl.java
+++ b/server/src/com/cloud/network/vpc/NetworkACLServiceImpl.java
@@@ -29,6 -32,6 +30,7 @@@ import org.springframework.stereotype.C
  import org.apache.cloudstack.api.ApiErrorCode;
  import org.apache.cloudstack.api.ServerApiException;
  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.ListNetworkACLsCmd;
  import org.apache.cloudstack.context.CallContext;
  
@@@ -40,7 -43,8 +42,9 @@@ import com.cloud.network.Networks
  import com.cloud.network.dao.NetworkDao;
  import com.cloud.network.dao.NetworkVO;
  import com.cloud.network.vpc.dao.NetworkACLDao;
++import com.cloud.network.vpc.dao.VpcDao;
  import com.cloud.network.vpc.dao.VpcGatewayDao;
+ import com.cloud.projects.Project.ListProjectResourcesCriteria;
  import com.cloud.server.ResourceTag.ResourceObjectType;
  import com.cloud.tags.ResourceTagVO;
  import com.cloud.tags.dao.ResourceTagDao;
@@@ -124,12 -147,47 +147,50 @@@ public class NetworkACLServiceImpl exte
              sc.setParameters("name", name);
          }
  
-         if(vpcId != null){
+         if (vpcId != null) {
+             Vpc vpc = _entityMgr.findById(Vpc.class, vpcId);
+             if (vpc == null) {
+                 throw new InvalidParameterValueException("Unable to find VPC");
+             }
+             _accountMgr.checkAccess(caller, null, true, vpc);
              //Include vpcId 0 to list default ACLs
              sc.setParameters("vpcId", vpcId, 0);
+         } else {
+             //ToDo: Add accountId to network_acl table for permission check
+ 
+             // VpcId is not specified. Find permitted VPCs for the caller
+             // and list ACLs belonging to the permitted VPCs
++            List<Long> permittedDomains = new ArrayList<Long>();
+             List<Long> permittedAccounts = new ArrayList<Long>();
++            List<Long> permittedResources = new ArrayList<Long>();
++
+             Long domainId = cmd.getDomainId();
+             boolean isRecursive = cmd.isRecursive();
+             String accountName = cmd.getAccountName();
+             Long projectId = cmd.getProjectId();
+             boolean listAll = cmd.listAll();
+             Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean,
+                 ListProjectResourcesCriteria>(domainId, isRecursive, null);
 -            _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, domainIdRecursiveListProject,
 -                listAll, false);
 -            domainId = domainIdRecursiveListProject.first();
++            _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedDomains, permittedAccounts, permittedResources, domainIdRecursiveListProject,
++                    listAll, false, "listNetworkACLLists");
++            //domainId = domainIdRecursiveListProject.first();
+             isRecursive = domainIdRecursiveListProject.second();
+             ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
+             SearchBuilder<VpcVO> sbVpc = _vpcDao.createSearchBuilder();
 -            _accountMgr.buildACLSearchBuilder(sbVpc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
++            _accountMgr.buildACLSearchBuilder(sbVpc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria);
+             SearchCriteria<VpcVO> scVpc = sbVpc.create();
 -            _accountMgr.buildACLSearchCriteria(scVpc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
++            _accountMgr.buildACLSearchCriteria(scVpc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria);
+             List<VpcVO> vpcs = _vpcDao.search(scVpc, null);
+             List<Long> vpcIds = new ArrayList<Long>();
+             for (VpcVO vpc : vpcs) {
+                 vpcIds.add(vpc.getId());
+             }
+             //Add vpc_id 0 to list default ACLs
+             vpcIds.add(0L);
+             sc.setParameters("vpcId", vpcIds.toArray());
          }
  
-         if(networkId != null){
+         if (networkId != null) {
              sc.setJoinParameters("networkJoin", "networkId", networkId);
          }
  
@@@ -192,10 -250,10 +253,10 @@@
              }
          }
  
-         PrivateGateway privateGateway = _entityMgr.findById(PrivateGateway.class, privateGatewayId);
+         PrivateGateway privateGateway = _vpcSvc.getVpcPrivateGateway(gateway.getId());
          _accountMgr.checkAccess(caller, null, true, privateGateway);
  
 -        return _networkAclMgr.replaceNetworkACLForPrivateGw(acl, privateGateway);
 +        return  _networkAclMgr.replaceNetworkACLForPrivateGw(acl, privateGateway);
  
      }
  
@@@ -469,11 -520,50 +523,52 @@@
              sc.setParameters("trafficType", trafficType);
          }
  
-         if(aclId != null){
+         if (aclId != null) {
+             // Get VPC and check access
+             NetworkACL acl = _networkACLDao.findById(aclId);
+             if (acl.getVpcId() != 0) {
+                 Vpc vpc = _vpcDao.findById(acl.getVpcId());
+                 if (vpc == null) {
+                     throw new InvalidParameterValueException("Unable to find VPC associated with acl");
+                 }
+                 _accountMgr.checkAccess(caller, null, true, vpc);
+             }
              sc.setParameters("aclId", aclId);
+         } else {
+             //ToDo: Add accountId to network_acl_item table for permission check
+ 
+             // aclId is not specified
+             // List permitted VPCs and filter aclItems
++            List<Long> permittedDomains = new ArrayList<Long>();
+             List<Long> permittedAccounts = new ArrayList<Long>();
++            List<Long> permittedResources = new ArrayList<Long>();
+             Long domainId = cmd.getDomainId();
+             boolean isRecursive = cmd.isRecursive();
+             String accountName = cmd.getAccountName();
+             Long projectId = cmd.getProjectId();
+             boolean listAll = cmd.listAll();
+             Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean,
+                 ListProjectResourcesCriteria>(domainId, isRecursive, null);
 -            _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, domainIdRecursiveListProject,
 -                listAll, false);
++            _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedDomains, permittedAccounts, permittedResources, domainIdRecursiveListProject,
++                    listAll, false, "listNetworkACLs");
+             domainId = domainIdRecursiveListProject.first();
+             isRecursive = domainIdRecursiveListProject.second();
+             ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
+             SearchBuilder<VpcVO> sbVpc = _vpcDao.createSearchBuilder();
 -            _accountMgr.buildACLSearchBuilder(sbVpc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
++            _accountMgr.buildACLSearchBuilder(sbVpc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria);
+             SearchCriteria<VpcVO> scVpc = sbVpc.create();
 -            _accountMgr.buildACLSearchCriteria(scVpc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
++            _accountMgr.buildACLSearchCriteria(scVpc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria);
+             List<VpcVO> vpcs = _vpcDao.search(scVpc, null);
+             List<Long> vpcIds = new ArrayList<Long>();
+             for (VpcVO vpc : vpcs) {
+                 vpcIds.add(vpc.getId());
+             }
+             //Add vpc_id 0 to list acl_items in default ACL
+             vpcIds.add(0L);
+             sc.setJoinParameters("vpcSearch", "vpcId", vpcIds.toArray());
          }
  
-         if(protocol != null){
+         if (protocol != null) {
              sc.setParameters("protocol", protocol);
          }
  

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/server/src/com/cloud/network/vpc/PrivateGatewayProfile.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/network/vpc/PrivateGatewayProfile.java
index 807a9d0,e183cdb..9ca5482
--- a/server/src/com/cloud/network/vpc/PrivateGatewayProfile.java
+++ b/server/src/com/cloud/network/vpc/PrivateGatewayProfile.java
@@@ -16,9 -16,6 +16,8 @@@
  // under the License.
  package com.cloud.network.vpc;
  
 +import org.apache.cloudstack.acl.AclEntityType;
 +
- 
  public class PrivateGatewayProfile implements PrivateGateway {
      VpcGateway vpcGateway;
      long physicalNetworkId;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/server/src/com/cloud/network/vpc/VpcManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/network/vpc/VpcManagerImpl.java
index 471e53b,2face90..2ffe510
--- a/server/src/com/cloud/network/vpc/VpcManagerImpl.java
+++ b/server/src/com/cloud/network/vpc/VpcManagerImpl.java
@@@ -216,48 -216,46 +216,46 @@@ public class VpcManagerImpl extends Man
          Transaction.execute(new TransactionCallbackNoReturn() {
              @Override
              public void doInTransactionWithoutResult(TransactionStatus status) {
 -                if (_vpcOffDao.findByUniqueName(VpcOffering.defaultVPCOfferingName) == null) {
 -                    s_logger.debug("Creating default VPC offering " + VpcOffering.defaultVPCOfferingName);
 -
 -                    Map<Service, Set<Provider>> svcProviderMap = new HashMap<Service, Set<Provider>>();
 -                    Set<Provider> defaultProviders = new HashSet<Provider>();
 -                    defaultProviders.add(Provider.VPCVirtualRouter);
 -                    for (Service svc : getSupportedServices()) {
 -                        if (svc == Service.Lb) {
 -                            Set<Provider> lbProviders = new HashSet<Provider>();
 -                            lbProviders.add(Provider.VPCVirtualRouter);
 -                            lbProviders.add(Provider.InternalLbVm);
 -                            svcProviderMap.put(svc, lbProviders);
 -                        } else {
 -                            svcProviderMap.put(svc, defaultProviders);
 -                        }
 -                    }
 -                    createVpcOffering(VpcOffering.defaultVPCOfferingName, VpcOffering.defaultVPCOfferingName, svcProviderMap, true, State.Enabled, null);
 +        if (_vpcOffDao.findByUniqueName(VpcOffering.defaultVPCOfferingName) == null) {
 +            s_logger.debug("Creating default VPC offering " + VpcOffering.defaultVPCOfferingName);
-             
++
 +            Map<Service, Set<Provider>> svcProviderMap = new HashMap<Service, Set<Provider>>();
 +            Set<Provider> defaultProviders = new HashSet<Provider>();
 +            defaultProviders.add(Provider.VPCVirtualRouter);
 +            for (Service svc : getSupportedServices()) {
 +                if (svc == Service.Lb) {
 +                    Set<Provider> lbProviders = new HashSet<Provider>();
 +                    lbProviders.add(Provider.VPCVirtualRouter);
 +                    lbProviders.add(Provider.InternalLbVm);
 +                    svcProviderMap.put(svc, lbProviders);
 +                } else {
 +                    svcProviderMap.put(svc, defaultProviders);
                  }
 +            }
-             createVpcOffering(VpcOffering.defaultVPCOfferingName, VpcOffering.defaultVPCOfferingName, svcProviderMap,
-                     true, State.Enabled);
++                    createVpcOffering(VpcOffering.defaultVPCOfferingName, VpcOffering.defaultVPCOfferingName, svcProviderMap, true, State.Enabled, null);
 +        }
  
 -                //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);
 -                    Map<Service, Set<Provider>> svcProviderMap = new HashMap<Service, Set<Provider>>();
 -                    Set<Provider> defaultProviders = new HashSet<Provider>();
 -                    defaultProviders.add(Provider.VPCVirtualRouter);
 -                    for (Service svc : getSupportedServices()) {
 -                        if (svc == Service.Lb) {
 -                            Set<Provider> lbProviders = new HashSet<Provider>();
 -                            lbProviders.add(Provider.Netscaler);
 -                            lbProviders.add(Provider.InternalLbVm);
 -                            svcProviderMap.put(svc, lbProviders);
 -                        } else {
 -                            svcProviderMap.put(svc, defaultProviders);
 -                        }
 -                    }
 -                    createVpcOffering(VpcOffering.defaultVPCNSOfferingName, VpcOffering.defaultVPCNSOfferingName, svcProviderMap, false, State.Enabled, null);
 +            s_logger.debug("Creating default VPC offering with Netscaler as LB Provider" + VpcOffering.defaultVPCNSOfferingName);
 +            Map<Service, Set<Provider>> svcProviderMap = new HashMap<Service, Set<Provider>>();
 +            Set<Provider> defaultProviders = new HashSet<Provider>();
 +            defaultProviders.add(Provider.VPCVirtualRouter);
 +            for (Service svc : getSupportedServices()) {
 +                if (svc == Service.Lb) {
 +                    Set<Provider> lbProviders = new HashSet<Provider>();
 +                    lbProviders.add(Provider.Netscaler);
 +                    lbProviders.add(Provider.InternalLbVm);
 +                    svcProviderMap.put(svc, lbProviders);
 +                } else {
 +                    svcProviderMap.put(svc, defaultProviders);
                  }
              }
-             createVpcOffering(VpcOffering.defaultVPCNSOfferingName, VpcOffering.defaultVPCNSOfferingName,
-                     svcProviderMap, false, State.Enabled);
++                    createVpcOffering(VpcOffering.defaultVPCNSOfferingName, VpcOffering.defaultVPCNSOfferingName, svcProviderMap, false, State.Enabled, null);
 +        }
 +            }
          });
-         
+ 
          Map<String, String> configs = _configDao.getConfiguration(params);
          String value = configs.get(Config.VpcCleanupInterval.key());
          _cleanupInterval = NumbersUtil.parseInt(value, 60 * 60); // 1 hour
@@@ -368,8 -366,8 +366,8 @@@
                      }
                      svcProviderMap.put(service, providers);
                  } else {
-                     throw new InvalidParameterValueException("Service " + serviceStr + " 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");
                  }
              }
          }
@@@ -387,35 -384,35 +384,35 @@@
          return Transaction.execute(new TransactionCallback<VpcOffering>() {
              @Override
              public VpcOffering doInTransaction(TransactionStatus status) {
 -                // create vpc offering object
 +        // create vpc offering object
-         VpcOfferingVO offering  = new VpcOfferingVO(name, displayText, isDefault, null);
-         
+                 VpcOfferingVO offering = new VpcOfferingVO(name, displayText, isDefault, serviceOfferingId);
+ 
 -                if (state != null) {
 -                    offering.setState(state);
 -                }
 -                s_logger.debug("Adding vpc offering " + offering);
 -                offering = _vpcOffDao.persist(offering);
 -                // populate services and providers
 -                if (svcProviderMap != null) {
 -                    for (Network.Service service : svcProviderMap.keySet()) {
 -                        Set<Provider> providers = svcProviderMap.get(service);
 -                        if (providers != null && !providers.isEmpty()) {
 -                            for (Network.Provider provider : providers) {
 -                                VpcOfferingServiceMapVO offService = new VpcOfferingServiceMapVO(offering.getId(), service, provider);
 -                                _vpcOffSvcMapDao.persist(offService);
 -                                s_logger.trace("Added service for the vpc offering: " + offService + " with provider " + provider.getName());
 -                            }
 -                        } else {
 -                            throw new InvalidParameterValueException("Provider is missing for the VPC offering service " + service.getName());
 -                        }
 +        if (state != null) {
 +            offering.setState(state);
 +        }
 +        s_logger.debug("Adding vpc offering " + offering);
 +        offering = _vpcOffDao.persist(offering);
 +        // populate services and providers
 +        if (svcProviderMap != null) {
 +            for (Network.Service service : svcProviderMap.keySet()) {
 +                Set<Provider> providers = svcProviderMap.get(service);
 +                if (providers != null && !providers.isEmpty()) {
 +                    for (Network.Provider provider : providers) {
 +                        VpcOfferingServiceMapVO offService = new VpcOfferingServiceMapVO(offering.getId(), service, provider);
 +                        _vpcOffSvcMapDao.persist(offService);
 +                        s_logger.trace("Added service for the vpc offering: " + offService + " with provider " + provider.getName());
                      }
 +                } else {
 +                    throw new InvalidParameterValueException("Provider is missing for the VPC offering service " + service.getName());
                  }
 -
 -                return offering;
              }
 +        }
 +
 +        return offering;
 +    }
          });
      }
-     
+ 
      @Override
      public Vpc getActiveVpc(long vpcId) {
          return _vpcDao.getActiveVpcById(vpcId);
@@@ -620,8 -612,8 +612,8 @@@
          if (zone == null) {
              throw new InvalidParameterValueException("Can't find zone by id specified");
          }
-         
+ 
 -        if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getType())) {
 +        if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
              // See DataCenterVO.java
              PermissionDeniedException ex = new PermissionDeniedException("Cannot perform this operation since specified Zone is currently disabled");
              ex.addProxyObject(zone.getUuid(), "zoneId");
@@@ -642,11 -633,10 +633,10 @@@
          return createVpc(zoneId, vpcOffId, owner, vpcName, displayText, cidr, networkDomain);
      }
  
-     
      @DB
      protected Vpc createVpc(final long zoneId, final long vpcOffId, final Account vpcOwner, final String vpcName, final String displayText, final String cidr,
 -        final String networkDomain) {
 +            final String networkDomain) {
-         
+ 
          //Validate CIDR
          if (!NetUtils.isValidCIDR(cidr)) {
              throw new InvalidParameterValueException("Invalid CIDR specified " + cidr);
@@@ -659,25 -649,22 +649,22 @@@
  
          // validate network domain
          if (!NetUtils.verifyDomainName(networkDomain)) {
-             throw new InvalidParameterValueException(
-                     "Invalid network domain. Total length shouldn't exceed 190 chars. Each domain " +
-                     "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', " +
-                     "the digits '0' through '9', "
+             throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+                 + "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', " + "the digits '0' through '9', "
 -                + "and the hyphen ('-'); can't start or end with \"-\"");
 +                            + "and the hyphen ('-'); can't start or end with \"-\"");
          }
  
          return Transaction.execute(new TransactionCallback<VpcVO>() {
              @Override
              public VpcVO doInTransaction(TransactionStatus status) {
-         VpcVO vpc = new VpcVO (zoneId, vpcName, displayText, vpcOwner.getId(), vpcOwner.getDomainId(), vpcOffId, cidr,
-                 networkDomain);
+                 VpcVO vpc = new VpcVO(zoneId, vpcName, displayText, vpcOwner.getId(), vpcOwner.getDomainId(), vpcOffId, cidr, networkDomain);
 -                vpc = _vpcDao.persist(vpc, finalizeServicesAndProvidersForVpc(zoneId, vpcOffId));
 -                _resourceLimitMgr.incrementResourceCount(vpcOwner.getId(), ResourceType.vpc);
 +        vpc = _vpcDao.persist(vpc, finalizeServicesAndProvidersForVpc(zoneId, vpcOffId));
 +        _resourceLimitMgr.incrementResourceCount(vpcOwner.getId(), ResourceType.vpc);
  
 -                s_logger.debug("Created VPC " + vpc);
 +        s_logger.debug("Created VPC " + vpc);
  
 -                return vpc;
 -            }
 +        return vpc;
 +    }
          });
      }
  
@@@ -752,10 -737,10 +737,10 @@@
              Transaction.execute(new TransactionCallbackNoReturn() {
                  @Override
                  public void doInTransactionWithoutResult(TransactionStatus status) {
 -                    _vpcDao.update(vpc.getId(), vpcVO);
 +            _vpcDao.update(vpc.getId(), vpcVO);
-             
+ 
 -                    //decrement resource count
 -                    _resourceLimitMgr.decrementResourceCount(vpc.getAccountId(), ResourceType.vpc);
 +            //decrement resource count
 +            _resourceLimitMgr.decrementResourceCount(vpc.getAccountId(), ResourceType.vpc);
                  }
              });
          }
@@@ -814,20 -799,17 +799,19 @@@
          }
      }
  
- 
      @Override
-     public List<? extends Vpc> listVpcs(Long id, String vpcName, String displayText, List<String> supportedServicesStr,
-             String cidr, Long vpcOffId, String state, String accountName, Long domainId, String keyword,
-             Long startIndex, Long pageSizeVal, Long zoneId, Boolean isRecursive, Boolean listAll, Boolean restartRequired, Map<String, String> tags, Long projectId) {
+     public List<? extends Vpc> listVpcs(Long id, String vpcName, String displayText, List<String> supportedServicesStr, String cidr, Long vpcOffId, String state,
+         String accountName, Long domainId, String keyword, Long startIndex, Long pageSizeVal, Long zoneId, Boolean isRecursive, Boolean listAll, Boolean restartRequired,
+         Map<String, String> tags, Long projectId) {
          Account caller = CallContext.current().getCallingAccount();
 +        List<Long> permittedDomains = new ArrayList<Long>();
          List<Long> permittedAccounts = new ArrayList<Long>();
 +        List<Long> permittedResources = new ArrayList<Long>();
-         
+ 
 -        Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject =
 -            new Ternary<Long, Boolean, ListProjectResourcesCriteria>(domainId, isRecursive, null);
 -        _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, domainIdRecursiveListProject, listAll, false);
 -        domainId = domainIdRecursiveListProject.first();
 +        Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean,
 +                ListProjectResourcesCriteria>(domainId, isRecursive, null);
 +        _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedDomains, permittedAccounts, permittedResources, domainIdRecursiveListProject, listAll,
 +                false, "listVPCs");
          isRecursive = domainIdRecursiveListProject.second();
          ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
          Filter searchFilter = new Filter(VpcVO.class, "created", false, startIndex, pageSizeVal);
@@@ -855,10 -837,10 +839,10 @@@
              sb.groupBy(sb.entity().getId());
              sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER);
          }
-         
+ 
          // now set the SC criteria...
          SearchCriteria<VpcVO> sc = sb.create();
 -        _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
 +        _accountMgr.buildACLSearchCriteria(sc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria);
  
          if (keyword != null) {
              SearchCriteria<VpcVO> ssc = _vpcDao.createSearchCriteria();
@@@ -1121,19 -1098,16 +1100,16 @@@
          //1) in current release, only vpc provider is supported by Vpc offering
          List<Provider> providers = _ntwkModel.getNtwkOffDistinctProviders(guestNtwkOff.getId());
          for (Provider provider : providers) {
-             if (!supportedProviders.contains(provider) ) {
-                 throw new InvalidParameterValueException("Provider of type " + provider.getName()
-                         + " is not supported for network offerings that can be used in VPC");
+             if (!supportedProviders.contains(provider)) {
+                 throw new InvalidParameterValueException("Provider of type " + provider.getName() + " is not supported for network offerings that can be used in 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
@@@ -1146,11 -1120,11 +1122,11 @@@
              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");
          }
-         return ;
+         return;
      }
  
      @DB
@@@ -1159,62 -1133,57 +1135,57 @@@
          Transaction.execute(new TransactionCallbackNoReturn() {
              @Override
              public void doInTransactionWithoutResult(TransactionStatus status) {
 -                Vpc locked = _vpcDao.acquireInLockTable(vpc.getId());
 -                if (locked == null) {
 -                    throw new CloudRuntimeException("Unable to acquire lock on " + vpc);
 -                }
 +        Vpc locked = _vpcDao.acquireInLockTable(vpc.getId());
 +        if (locked == null) {
 +            throw new CloudRuntimeException("Unable to acquire lock on " + vpc);
 +        }
-         
+ 
 -                try {
 -                    //check number of active networks in vpc
 -                    if (_ntwkDao.countVpcNetworks(vpc.getId()) >= _maxNetworks) {
 +        try {
 +            //check number of active networks in vpc
 +            if (_ntwkDao.countVpcNetworks(vpc.getId()) >= _maxNetworks) {
-                 throw new CloudRuntimeException("Number of networks per VPC can't extend "
-                         + _maxNetworks + "; increase it using global config " + Config.VpcMaxNetworks);
+                         throw new CloudRuntimeException("Number of networks per VPC can't extend " + _maxNetworks + "; increase it using global config " +
+                             Config.VpcMaxNetworks);
 -                    }
 +            }
-             
-             
+ 
 -                    //1) CIDR is required
 -                    if (cidr == null) {
 -                        throw new InvalidParameterValueException("Gateway/netmask are required when create network for VPC");
 -                    }
 +            //1) CIDR is required
 +            if (cidr == null) {
 +                throw new InvalidParameterValueException("Gateway/netmask are required when create network for VPC");
 +            }
-             
+ 
 -                    //2) Network cidr should be within vpcCidr
 -                    if (!NetUtils.isNetworkAWithinNetworkB(cidr, vpc.getCidr())) {
 -                        throw new InvalidParameterValueException("Network cidr " + cidr + " is not within vpc " + vpc + " cidr");
 -                    }
 +            //2) Network cidr should be within vpcCidr
 +            if (!NetUtils.isNetworkAWithinNetworkB(cidr, vpc.getCidr())) {
 +                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
 -                    List<? extends Network> ntwks = _ntwkDao.listByVpc(vpc.getId());
 -                    for (Network ntwk : ntwks) {
 -                        assert (cidr != null) : "Why the network cidr is null when it belongs to vpc?";
 +            //3) Network cidr shouldn't cross the cidr of other vpc network cidrs
 +            List<? extends Network> ntwks = _ntwkDao.listByVpc(vpc.getId());
 +            for (Network ntwk : ntwks) {
 +                assert (cidr != null) : "Why the network cidr is null when it belongs to vpc?";
-                 
-                 if (NetUtils.isNetworkAWithinNetworkB(ntwk.getCidr(), cidr)
-                         || NetUtils.isNetworkAWithinNetworkB(cidr, ntwk.getCidr())) {
-                     throw new InvalidParameterValueException("Network cidr " + cidr + " crosses other network cidr " + ntwk +
-                             " belonging to the same vpc " + vpc);
+ 
+                         if (NetUtils.isNetworkAWithinNetworkB(ntwk.getCidr(), cidr) || NetUtils.isNetworkAWithinNetworkB(cidr, ntwk.getCidr())) {
+                             throw new InvalidParameterValueException("Network cidr " + cidr + " crosses other network cidr " + ntwk + " belonging to the same vpc " + vpc);
 -                        }
 -                    }
 +                }
 +            }
-             
+ 
 -                    //4) vpc and network should belong to the same owner
 -                    if (vpc.getAccountId() != networkOwner.getId()) {
 +            //4) vpc and network should belong to the same owner
 +            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
 -                    if (!networkDomain.equalsIgnoreCase(vpc.getNetworkDomain())) {
 +            //5) network domain should be the same as VPC's
 +            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
 -                    if (NetUtils.getCidrSubNet(cidr).equalsIgnoreCase(gateway)) {
 -                        throw new InvalidParameterValueException("Invalid gateway specified. It should never be equal to the cidr subnet value");
 -                    }
 -                } finally {
 -                    s_logger.debug("Releasing lock for " + locked);
 -                    _vpcDao.releaseFromLockTable(locked.getId());
 -                }
 +            //6) gateway should never be equal to the cidr subnet
 +            if (NetUtils.getCidrSubNet(cidr).equalsIgnoreCase(gateway)) {
 +                throw new InvalidParameterValueException("Invalid gateway specified. It should never be equal to the cidr subnet value");
              }
 +        } finally {
 +            s_logger.debug("Releasing lock for " + locked);
 +            _vpcDao.releaseFromLockTable(locked.getId());
 +        }
 +    }
          });
      }
  
@@@ -1375,11 -1339,11 +1341,11 @@@
  
      @Override
      @DB
-     @ActionEvent(eventType = EventTypes.EVENT_PRIVATE_GATEWAY_CREATE, eventDescription = "creating vpc private gateway", create=true)
-     public PrivateGateway createVpcPrivateGateway(final long vpcId, Long physicalNetworkId, final String broadcastUri, final String ipAddress,
-             final String gateway, final String netmask, final long gatewayOwnerId, final Long networkOfferingId, final Boolean isSourceNat, final Long aclId) throws ResourceAllocationException,
+     @ActionEvent(eventType = EventTypes.EVENT_PRIVATE_GATEWAY_CREATE, eventDescription = "creating vpc private gateway", create = true)
+     public PrivateGateway createVpcPrivateGateway(final long vpcId, Long physicalNetworkId, final String broadcastUri, final String ipAddress, final String gateway,
+         final String netmask, final long gatewayOwnerId, final Long networkOfferingId, final Boolean isSourceNat, final Long aclId) throws ResourceAllocationException,
 -        ConcurrentOperationException, InsufficientCapacityException {
 +            ConcurrentOperationException, InsufficientCapacityException {
-         
+ 
          //Validate parameters
          final Vpc vpc = getActiveVpc(vpcId);
          if (vpc == null) {
@@@ -1408,64 -1372,66 +1374,66 @@@
          final PhysicalNetwork physNetFinal = physNet;
          VpcGatewayVO gatewayVO = null;
          try {
-             gatewayVO = Transaction.execute(new TransactionCallbackWithException<VpcGatewayVO,Exception>() {
+             gatewayVO = Transaction.execute(new TransactionCallbackWithException<VpcGatewayVO, Exception>() {
                  @Override
-                 public VpcGatewayVO doInTransaction(TransactionStatus status) throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException {
+                 public VpcGatewayVO doInTransaction(TransactionStatus status) throws ResourceAllocationException, ConcurrentOperationException,
+                     InsufficientCapacityException {
 -                    s_logger.debug("Creating Private gateway for VPC " + vpc);
 -                    //1) create private network unless it is existing and lswitch'd
 -                    Network privateNtwk = null;
 -                    if (BroadcastDomainType.getSchemeValue(BroadcastDomainType.fromString(broadcastUri)) == BroadcastDomainType.Lswitch) {
 -                        String cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask);
 +        s_logger.debug("Creating Private gateway for VPC " + vpc);
 +        //1) create private network unless it is existing and lswitch'd
 +        Network privateNtwk = null;
 +        if (BroadcastDomainType.getSchemeValue(BroadcastDomainType.fromString(broadcastUri)) == BroadcastDomainType.Lswitch) {
 +            String cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask);
- 
-             privateNtwk = _ntwkDao.getPrivateNetwork(broadcastUri, cidr,
-                     gatewayOwnerId, dcId, networkOfferingId);
-             s_logger.info("found and using existing network for vpc " + vpc + ": " + broadcastUri);
+                         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 (privateNtwk == null) {
 -                        s_logger.info("creating new network for vpc " + vpc + " using broadcast uri: " + broadcastUri);
 -                        String networkName = "vpc-" + vpc.getName() + "-privateNetwork";
 +        }
 +        if (privateNtwk == null) {
 +            s_logger.info("creating new network for vpc " + vpc + " using broadcast uri: " + broadcastUri);
 +            String networkName = "vpc-" + vpc.getName() + "-privateNetwork";
-                         privateNtwk = _ntwkSvc.createPrivateNetwork(networkName, networkName, physicalNetworkIdFinal,
-                 broadcastUri, ipAddress, null, gateway, netmask, gatewayOwnerId, vpcId, isSourceNat, networkOfferingId);
+                         privateNtwk =
+                             _ntwkSvc.createPrivateNetwork(networkName, networkName, physicalNetworkIdFinal, broadcastUri, ipAddress, null, gateway, netmask,
+                                 gatewayOwnerId, vpcId, isSourceNat, networkOfferingId);
 -                    } else { // create the nic/ip as createPrivateNetwork doesn''t do that work for us now
 +        } else { // create the nic/ip as createPrivateNetwork doesn''t do that work for us now
+                         s_logger.info("found and using existing network for vpc " + vpc + ": " + broadcastUri);
                          DataCenterVO dc = _dcDao.lockRow(physNetFinal.getDataCenterId(), true);
  
 -                        //add entry to private_ip_address table
 -                        PrivateIpVO privateIp = _privateIpDao.findByIpAndSourceNetworkId(privateNtwk.getId(), ipAddress);
 -                        if (privateIp != null) {
 +            //add entry to private_ip_address table
 +            PrivateIpVO privateIp = _privateIpDao.findByIpAndSourceNetworkId(privateNtwk.getId(), ipAddress);
 +            if (privateIp != null) {
-                 throw new InvalidParameterValueException("Private ip address " + ipAddress + " already used for private gateway" +
-                         " in zone " + _entityMgr.findById(DataCenter.class,dcId).getName());
+                             throw new InvalidParameterValueException("Private ip address " + ipAddress + " already used for private gateway" + " in zone " +
+                                 _entityMgr.findById(DataCenter.class, dcId).getName());
 -                        }
 +            }
  
 -                        Long mac = dc.getMacAddress();
 -                        Long nextMac = mac + 1;
 -                        dc.setMacAddress(nextMac);
 +            Long mac = dc.getMacAddress();
 +            Long nextMac = mac + 1;
 +            dc.setMacAddress(nextMac);
  
 -                        privateIp = new PrivateIpVO(ipAddress, privateNtwk.getId(), nextMac, vpcId, true);
 -                        _privateIpDao.persist(privateIp);
 +            privateIp = new PrivateIpVO(ipAddress, privateNtwk.getId(), nextMac, vpcId, true);
 +            _privateIpDao.persist(privateIp);
  
 -                        _dcDao.update(dc.getId(), dc);
 -                    }
 +            _dcDao.update(dc.getId(), dc);
 +        }
  
 -                    long networkAclId = NetworkACL.DEFAULT_DENY;
 -                    if (aclId != null) {
 -                        NetworkACLVO aclVO = _networkAclDao.findById(aclId);
 +        long networkAclId = NetworkACL.DEFAULT_DENY;
 +        if (aclId != null) {
 +            NetworkACLVO aclVO = _networkAclDao.findById(aclId);
-             if ( aclVO == null) {
+                         if (aclVO == null) {
 -                            throw new InvalidParameterValueException("Invalid network acl id passed ");
 -                        }
 -                        if ((aclVO.getVpcId() != vpcId) && !(aclId == NetworkACL.DEFAULT_DENY || aclId == NetworkACL.DEFAULT_ALLOW)) {
 -                            throw new InvalidParameterValueException("Private gateway and network acl are not in the same vpc");
 -                        }
 +                throw new InvalidParameterValueException("Invalid network acl id passed ");
 +            }
 +            if ((aclVO.getVpcId() != vpcId) && !(aclId == NetworkACL.DEFAULT_DENY || aclId == NetworkACL.DEFAULT_ALLOW)) {
 +                throw new InvalidParameterValueException("Private gateway and network acl are not in the same vpc");
 +            }
  
 -                        networkAclId = aclId;
 -                    }
 +            networkAclId = aclId;
 +        }
  
 -                    //2) create gateway entry
 +        //2) create gateway entry
-         VpcGatewayVO gatewayVO = new VpcGatewayVO(ipAddress, VpcGateway.Type.Private, vpcId, privateNtwk.getDataCenterId(),
-                 privateNtwk.getId(), broadcastUri, gateway, netmask, vpc.getAccountId(), vpc.getDomainId(), isSourceNat, networkAclId);
+                     VpcGatewayVO gatewayVO =
+                         new VpcGatewayVO(ipAddress, VpcGateway.Type.Private, vpcId, privateNtwk.getDataCenterId(), privateNtwk.getId(), broadcastUri, gateway, netmask,
+                             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);
-         
+ 
                      return gatewayVO;
                  }
              });
@@@ -1533,19 -1499,18 +1501,18 @@@
              Transaction.execute(new TransactionCallbackNoReturn() {
                  @Override
                  public void doInTransactionWithoutResult(TransactionStatus status) {
 -                    //don't allow to remove gateway when there are static routes associated with it
 -                    long routeCount = _staticRouteDao.countRoutesByGateway(gatewayVO.getId());
 -                    if (routeCount > 0) {
 -                        throw new CloudRuntimeException("Can't delete private gateway " + gatewayVO + " as it has " + routeCount +
 -                            " static routes applied. Remove the routes first");
 -                    }
 +            //don't allow to remove gateway when there are static routes associated with it
 +            long routeCount = _staticRouteDao.countRoutesByGateway(gatewayVO.getId());
 +            if (routeCount > 0) {
 +                throw new CloudRuntimeException("Can't delete private gateway " + gatewayVO + " as it has " + routeCount +
 +                        " static routes applied. Remove the routes first");
 +            }
-             
+ 
 -                    gatewayVO.setState(VpcGateway.State.Deleting);
 -                    _vpcGatewayDao.update(gatewayVO.getId(), gatewayVO);
 -                    s_logger.debug("Marked gateway " + gatewayVO + " with state " + VpcGateway.State.Deleting);
 +            gatewayVO.setState(VpcGateway.State.Deleting);
 +            _vpcGatewayDao.update(gatewayVO.getId(), gatewayVO);
 +            s_logger.debug("Marked gateway " + gatewayVO + " with state " + VpcGateway.State.Deleting);
                  }
              });
-             
  
              //1) delete the gateway on the backend
              PrivateGateway gateway = getVpcPrivateGateway(gatewayId);
@@@ -1586,25 -1555,25 +1557,25 @@@
          Transaction.execute(new TransactionCallbackNoReturn() {
              @Override
              public void doInTransactionWithoutResult(TransactionStatus status) {
 -                PrivateIpVO ip = _privateIpDao.findByIpAndVpcId(gateway.getVpcId(), gateway.getIp4Address());
 -                if (ip != null) {
 -                    _privateIpDao.remove(ip.getId());
 -                    s_logger.debug("Deleted private ip " + ip);
 -                }
 +        PrivateIpVO ip = _privateIpDao.findByIpAndVpcId(gateway.getVpcId(), gateway.getIp4Address());
 +        if (ip != null) {
 +            _privateIpDao.remove(ip.getId());
 +            s_logger.debug("Deleted private ip " + ip);
 +        }
-         
+ 
                  if (deleteNetworkFinal) {
 -                    User callerUser = _accountMgr.getActiveUser(CallContext.current().getCallingUserId());
 -                    Account owner = _accountMgr.getAccount(Account.ACCOUNT_ID_SYSTEM);
 -                    ReservationContext context = new ReservationContextImpl(null, null, callerUser, owner);
 +            User callerUser = _accountMgr.getActiveUser(CallContext.current().getCallingUserId());
 +            Account owner = _accountMgr.getAccount(Account.ACCOUNT_ID_SYSTEM);
 +            ReservationContext context = new ReservationContextImpl(null, null, callerUser, owner);
-             _ntwkMgr.destroyNetwork(networkId, context);
+                     _ntwkMgr.destroyNetwork(networkId, context, false);
 -                    s_logger.debug("Deleted private network id=" + networkId);
 -                }
 +            s_logger.debug("Deleted private network id=" + networkId);
 +        }
-         
+ 
 -                _vpcGatewayDao.remove(gateway.getId());
 -                s_logger.debug("Deleted private gateway " + gateway);
 +        _vpcGatewayDao.remove(gateway.getId());
 +        s_logger.debug("Deleted private gateway " + gateway);
              }
          });
-         
+ 
          return true;
      }
  
@@@ -1634,17 -1601,17 +1605,17 @@@
          ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
  
          SearchBuilder<VpcGatewayVO> sb = _vpcGatewayDao.createSearchBuilder();
 -        _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
 +        _accountMgr.buildACLSearchBuilder(sb, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria);
-         
+ 
          if (vlan != null) {
              SearchBuilder<NetworkVO> ntwkSearch = _ntwkDao.createSearchBuilder();
              ntwkSearch.and("vlan", ntwkSearch.entity().getBroadcastUri(), SearchCriteria.Op.EQ);
              sb.join("networkSearch", ntwkSearch, sb.entity().getNetworkId(), ntwkSearch.entity().getId(), JoinBuilder.JoinType.INNER);
          }
-         
+ 
          SearchCriteria<VpcGatewayVO> sc = sb.create();
 -        _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
 +        _accountMgr.buildACLSearchBuilder(sb, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria);
-         
+ 
          if (id != null) {
              sc.addAnd("id", Op.EQ, id);
          }
@@@ -1829,19 -1796,19 +1800,19 @@@
          return Transaction.execute(new TransactionCallbackWithException<StaticRouteVO, NetworkRuleConflictException>() {
              @Override
              public StaticRouteVO doInTransaction(TransactionStatus status) throws NetworkRuleConflictException {
 -                StaticRouteVO newRoute = new StaticRouteVO(gateway.getId(), cidr, vpc.getId(), vpc.getAccountId(), vpc.getDomainId());
 -                s_logger.debug("Adding static route " + newRoute);
 -                newRoute = _staticRouteDao.persist(newRoute);
 +        StaticRouteVO newRoute = new StaticRouteVO(gateway.getId(), cidr, vpc.getId(), vpc.getAccountId(), vpc.getDomainId());
 +        s_logger.debug("Adding static route " + newRoute);
 +        newRoute = _staticRouteDao.persist(newRoute);
-         
+ 
 -                detectRoutesConflict(newRoute);
 +        detectRoutesConflict(newRoute);
  
 -                if (!_staticRouteDao.setStateToAdd(newRoute)) {
 -                    throw new CloudRuntimeException("Unable to update the state to add for " + newRoute);
 -                }
 -                CallContext.current().setEventDetails("Static route Id: " + newRoute.getId());
 +        if (!_staticRouteDao.setStateToAdd(newRoute)) {
 +            throw new CloudRuntimeException("Unable to update the state to add for " + newRoute);
 +        }
 +        CallContext.current().setEventDetails("Static route Id: " + newRoute.getId());
-         
+ 
 -                return newRoute;
 -            }
 +        return newRoute;
 +    }
          });
      }
  
@@@ -1905,10 -1869,10 +1876,10 @@@
              sb.groupBy(sb.entity().getId());
              sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER);
          }
-         
+ 
          SearchCriteria<StaticRouteVO> sc = sb.create();
 -        _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
 +        _accountMgr.buildACLSearchCriteria(sc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria);
-         
+ 
          if (id != null) {
              sc.addAnd("id", Op.EQ, id);
          }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java
index 5c4241d,ef4cccd..71a639b
--- a/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java
+++ b/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java
@@@ -595,10 -611,10 +613,13 @@@ public class RemoteAccessVpnManagerImp
          // do some parameter validation
          Account caller = CallContext.current().getCallingAccount();
          Long ipAddressId = cmd.getPublicIpId();
 +        List<Long> permittedDomains = new ArrayList<Long>();
 +        List<Long> permittedAccounts = new ArrayList<Long>();
 +        List<Long> permittedResources = new ArrayList<Long>();
 +
+         Long vpnId = cmd.getId();
+         Long networkId = cmd.getNetworkId();
 -        List<Long> permittedAccounts = new ArrayList<Long>();
+ 
          if (ipAddressId != null) {
              PublicIpAddress publicIp = _networkMgr.getPublicIpAddress(ipAddressId);
              if (publicIp == null) {
@@@ -622,9 -638,11 +642,11 @@@
  
          Filter filter = new Filter(RemoteAccessVpnVO.class, "serverAddressId", false, cmd.getStartIndex(), cmd.getPageSizeVal());
          SearchBuilder<RemoteAccessVpnVO> sb = _remoteAccessVpnDao.createSearchBuilder();
 -        _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
 +        _accountMgr.buildACLSearchBuilder(sb, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria);
  
          sb.and("serverAddressId", sb.entity().getServerAddressId(), Op.EQ);
+         sb.and("id", sb.entity().getId(), Op.EQ);
+         sb.and("networkId", sb.entity().getNetworkId(), Op.EQ);
          sb.and("state", sb.entity().getState(), Op.EQ);
  
          SearchCriteria<RemoteAccessVpnVO> sc = sb.create();
@@@ -688,4 -714,13 +718,13 @@@
      public ConfigKey<?>[] getConfigKeys() {
          return new ConfigKey<?>[] {RemoteAccessVpnClientIpRange};
      }
+ 
+     public List<RemoteAccessVPNServiceProvider> getVpnServiceProviders() {
+         return _vpnServiceProviders;
+     }
+ 
+     public void setVpnServiceProviders(List<RemoteAccessVPNServiceProvider> vpnServiceProviders) {
 -        this._vpnServiceProviders = vpnServiceProviders;
++        _vpnServiceProviders = vpnServiceProviders;
+     }
+ 
  }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/server/src/com/cloud/network/vpn/Site2SiteVpnManagerImpl.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/server/src/com/cloud/projects/ProjectManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/projects/ProjectManagerImpl.java
index d16aba2,5e7d9a9..6e6dfd0
--- a/server/src/com/cloud/projects/ProjectManagerImpl.java
+++ b/server/src/com/cloud/projects/ProjectManagerImpl.java
@@@ -279,14 -276,14 +276,14 @@@ public class ProjectManagerImpl extend
          boolean updateResult = Transaction.execute(new TransactionCallback<Boolean>() {
              @Override
              public Boolean doInTransaction(TransactionStatus status) {
 -                s_logger.debug("Marking project id=" + project.getId() + " with state " + State.Disabled + " as a part of project delete...");
 -                project.setState(State.Disabled);
 -                boolean updateResult = _projectDao.update(project.getId(), project);
 -                //owner can be already removed at this point, so adding the conditional check
 -                Account projectOwner = getProjectOwner(project.getId());
 -                if (projectOwner != null) {
 -                    _resourceLimitMgr.decrementResourceCount(projectOwner.getId(), ResourceType.project);
 -                }
 +        s_logger.debug("Marking project id=" + project.getId() + " with state " + State.Disabled + " as a part of project delete...");
 +        project.setState(State.Disabled);
 +        boolean updateResult = _projectDao.update(project.getId(), project);
 +        //owner can be already removed at this point, so adding the conditional check
 +        Account projectOwner = getProjectOwner(project.getId());
 +        if (projectOwner != null) {
 +            _resourceLimitMgr.decrementResourceCount(projectOwner.getId(), ResourceType.project);
-         } 
++        }
  
                  return updateResult;
              }
@@@ -472,43 -468,43 +468,43 @@@
          Transaction.execute(new TransactionCallbackWithExceptionNoReturn<ResourceAllocationException>() {
              @Override
              public void doInTransactionWithoutResult(TransactionStatus status) throws ResourceAllocationException {
 -                if (displayText != null) {
 -                    project.setDisplayText(displayText);
 -                    _projectDao.update(projectId, project);
 -                }
 +        if (displayText != null) {
 +            project.setDisplayText(displayText);
 +            _projectDao.update(projectId, project);
 +        }
  
 -                if (newOwnerName != null) {
 -                    //check that the new owner exists
 -                    Account futureOwnerAccount = _accountMgr.getActiveAccountByName(newOwnerName, project.getDomainId());
 -                    if (futureOwnerAccount == null) {
 -                        throw new InvalidParameterValueException("Unable to find account name=" + newOwnerName + " in domain id=" + project.getDomainId());
 -                    }
 -                    Account currentOwnerAccount = getProjectOwner(projectId);
 -                    if (currentOwnerAccount.getId() != futureOwnerAccount.getId()) {
 -                        ProjectAccountVO futureOwner = _projectAccountDao.findByProjectIdAccountId(projectId, futureOwnerAccount.getAccountId());
 -                        if (futureOwner == null) {
 +        if (newOwnerName != null) {
 +            //check that the new owner exists
 +            Account futureOwnerAccount = _accountMgr.getActiveAccountByName(newOwnerName, project.getDomainId());
 +            if (futureOwnerAccount == null) {
 +                throw new InvalidParameterValueException("Unable to find account name=" + newOwnerName + " in domain id=" + project.getDomainId());
 +            }
 +            Account currentOwnerAccount = getProjectOwner(projectId);
 +            if (currentOwnerAccount.getId() != futureOwnerAccount.getId()) {
 +                ProjectAccountVO futureOwner = _projectAccountDao.findByProjectIdAccountId(projectId, futureOwnerAccount.getAccountId());
 +                if (futureOwner == null) {
-                     throw new InvalidParameterValueException("Account " + newOwnerName + " doesn't belong to the project. Add it to the project first and then change the project's ownership");
+                             throw new InvalidParameterValueException("Account " + newOwnerName +
+                                 " doesn't belong to the project. Add it to the project first and then change the project's ownership");
 -                        }
 +                }
  
 -                        //do resource limit check
 -                        _resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(futureOwnerAccount.getId()), ResourceType.project);
 +                //do resource limit check
 +                _resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(futureOwnerAccount.getId()), ResourceType.project);
  
 -                        //unset the role for the old owner
 -                        ProjectAccountVO currentOwner = _projectAccountDao.findByProjectIdAccountId(projectId, currentOwnerAccount.getId());
 -                        currentOwner.setAccountRole(Role.Regular);
 -                        _projectAccountDao.update(currentOwner.getId(), currentOwner);
 -                        _resourceLimitMgr.decrementResourceCount(currentOwnerAccount.getId(), ResourceType.project);
 +                //unset the role for the old owner
 +                ProjectAccountVO currentOwner = _projectAccountDao.findByProjectIdAccountId(projectId, currentOwnerAccount.getId());
 +                currentOwner.setAccountRole(Role.Regular);
 +                _projectAccountDao.update(currentOwner.getId(), currentOwner);
 +                _resourceLimitMgr.decrementResourceCount(currentOwnerAccount.getId(), ResourceType.project);
  
 -                        //set new owner
 -                        futureOwner.setAccountRole(Role.Admin);
 -                        _projectAccountDao.update(futureOwner.getId(), futureOwner);
 -                        _resourceLimitMgr.incrementResourceCount(futureOwnerAccount.getId(), ResourceType.project);
 +                //set new owner
 +                futureOwner.setAccountRole(Role.Admin);
 +                _projectAccountDao.update(futureOwner.getId(), futureOwner);
 +                _resourceLimitMgr.incrementResourceCount(futureOwnerAccount.getId(), ResourceType.project);
  
- 
 -                    } else {
 -                        s_logger.trace("Future owner " + newOwnerName + "is already the owner of the project id=" + projectId);
 -                    }
 -                }
 +            } else {
 +                s_logger.trace("Future owner " + newOwnerName + "is already the owner of the project id=" + projectId);
 +            }
 +        }
              }
          });
  
@@@ -630,10 -627,10 +627,10 @@@
          }
  
          //verify permissions
-         _accountMgr.checkAccess(caller,AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId()));
+         _accountMgr.checkAccess(caller, AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId()));
  
          //Check if the account exists in the project
 -        ProjectAccount projectAccount = _projectAccountDao.findByProjectIdAccountId(projectId, account.getId());
 +        ProjectAccount projectAccount =  _projectAccountDao.findByProjectIdAccountId(projectId, account.getId());
          if (projectAccount == null) {
              InvalidParameterValueException ex = new InvalidParameterValueException("Account " + accountName + " is not assigned to the project with specified id");
              // Use the projectVO object and not the projectAccount object to inject the projectId.
@@@ -669,35 -665,35 +665,35 @@@
          return Transaction.execute(new TransactionCallback<Boolean>() {
              @Override
              public Boolean doInTransaction(TransactionStatus status) {
 -                //verify if the invitation was already generated
 -                ProjectInvitationVO invite = null;
 +        //verify if the invitation was already generated
 +        ProjectInvitationVO invite = null;
 +        if (accountId != null) {
 +            invite = _projectInvitationDao.findByAccountIdProjectId(accountId, project.getId());
 +        } else if (email != null) {
 +            invite = _projectInvitationDao.findByEmailAndProjectId(email, project.getId());
 +        }
 +
 +        if (invite != null) {
-             if (invite.getState() == ProjectInvitation.State.Completed || 
++            if (invite.getState() == ProjectInvitation.State.Completed ||
 +                    (invite.getState() == ProjectInvitation.State.Pending && _projectInvitationDao.isActive(invite.getId(), _invitationTimeOut))) {
 +                return true;
 +            } else {
 +                if (invite.getState() == ProjectInvitation.State.Pending) {
 +                    expireInvitation(invite);
 +                }
 +                //remove the expired/declined invitation
                  if (accountId != null) {
 -                    invite = _projectInvitationDao.findByAccountIdProjectId(accountId, project.getId());
 +                    s_logger.debug("Removing invitation in state " + invite.getState() + " for account id=" + accountId + " to project " + project);
                  } else if (email != null) {
 -                    invite = _projectInvitationDao.findByEmailAndProjectId(email, project.getId());
 +                    s_logger.debug("Removing invitation in state " + invite.getState() + " for email " + email + " to project " + project);
                  }
  
 -                if (invite != null) {
 -                    if (invite.getState() == ProjectInvitation.State.Completed ||
 -                        (invite.getState() == ProjectInvitation.State.Pending && _projectInvitationDao.isActive(invite.getId(), _invitationTimeOut))) {
 -                        return true;
 -                    } else {
 -                        if (invite.getState() == ProjectInvitation.State.Pending) {
 -                            expireInvitation(invite);
 -                        }
 -                        //remove the expired/declined invitation
 -                        if (accountId != null) {
 -                            s_logger.debug("Removing invitation in state " + invite.getState() + " for account id=" + accountId + " to project " + project);
 -                        } else if (email != null) {
 -                            s_logger.debug("Removing invitation in state " + invite.getState() + " for email " + email + " to project " + project);
 -                        }
 -
 -                        _projectInvitationDao.expunge(invite.getId());
 -                    }
 -                }
 -
 -                return false;
 +                _projectInvitationDao.expunge(invite.getId());
              }
 +        }
 +
 +        return false;
 +    }
          });
      }
  
@@@ -790,17 -785,17 +785,17 @@@
                          inviteFinal.setState(newState);
                          result = _projectInvitationDao.update(inviteFinal.getId(), inviteFinal);
  
 -                        if (result && accept) {
 -                            //check if account already exists for the project (was added before invitation got accepted)
 -                            ProjectAccount projectAccount = _projectAccountDao.findByProjectIdAccountId(projectId, accountIdFinal);
 -                            if (projectAccount != null) {
 +                if (result && accept) {
 +                    //check if account already exists for the project (was added before invitation got accepted)
 +                            ProjectAccount projectAccount =  _projectAccountDao.findByProjectIdAccountId(projectId, accountIdFinal);
 +                    if (projectAccount != null) {
                                  s_logger.debug("Account " + accountNameFinal + " already added to the project id=" + projectId);
 -                            } else {
 +                    } else {
-                                 assignAccountToProject(project, accountIdFinal, ProjectAccount.Role.Regular); 
+                                 assignAccountToProject(project, accountIdFinal, ProjectAccount.Role.Regular);
 -                            }
 -                        } else {
 +                    }
 +                } else {
                              s_logger.warn("Failed to update project invitation " + inviteFinal + " with state " + newState);
 -                        }
 +                }
  
                          return result;
                      }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/server/src/com/cloud/resource/ResourceManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/resource/ResourceManagerImpl.java
index 5682d6f,c9e2e7a..5f14419
--- a/server/src/com/cloud/resource/ResourceManagerImpl.java
+++ b/server/src/com/cloud/resource/ResourceManagerImpl.java
@@@ -1252,23 -1274,29 +1274,29 @@@ public class ResourceManagerImpl extend
  
          if (guestOSCategoryId != null) {
              // Verify that the guest OS Category exists
-             if (guestOSCategoryId > 0) {
-                 if (_guestOSCategoryDao.findById(guestOSCategoryId) == null) {
+             if (!(guestOSCategoryId > 0) || _guestOSCategoryDao.findById(guestOSCategoryId) == null) {
 -                throw new InvalidParameterValueException("Please specify a valid guest OS category.");
 -            }
 +                    throw new InvalidParameterValueException("Please specify a valid guest OS category.");
 +                }
-             }
  
              GuestOSCategoryVO guestOSCategory = _guestOSCategoryDao.findById(guestOSCategoryId);
-             Map<String, String> hostDetails = _hostDetailsDao.findDetails(hostId);
+             DetailVO guestOSDetail = _hostDetailsDao.findDetail(hostId, "guest.os.category.id");
  
              if (guestOSCategory != null && !GuestOSCategoryVO.CATEGORY_NONE.equalsIgnoreCase(guestOSCategory.getName())) {
-                 // Save a new entry for guest.os.category.id
-                 hostDetails.put("guest.os.category.id", String.valueOf(guestOSCategory.getId()));
+                 // Create/Update an entry for guest.os.category.id
+                 if (guestOSDetail != null) {
+                     guestOSDetail.setValue(String.valueOf(guestOSCategory.getId()));
+                     _hostDetailsDao.update(guestOSDetail.getId(), guestOSDetail);
+                 } else {
+                     Map<String, String> detail = new HashMap<String, String>();
+                     detail.put("guest.os.category.id", String.valueOf(guestOSCategory.getId()));
+                     _hostDetailsDao.persist(hostId, detail);
+                 }
              } else {
                  // Delete any existing entry for guest.os.category.id
-                 hostDetails.remove("guest.os.category.id");
+                 if (guestOSDetail != null) {
+                     _hostDetailsDao.remove(guestOSDetail.getId());
+                 }
              }
-             _hostDetailsDao.persist(hostId, hostDetails);
          }
  
          List<String> hostTags = cmd.getHostTags();
@@@ -1422,8 -1450,9 +1450,9 @@@
                          break;
                      }
                  } else if (event == ResourceStateAdapter.Event.CREATE_HOST_VO_FOR_DIRECT_CONNECT) {
-                     result = adapter.createHostVOForDirectConnectAgent((HostVO)args[0], (StartupCommand[])args[1], (ServerResource)args[2], (Map<String, String>)args[3],
+                     result =
+                         adapter.createHostVOForDirectConnectAgent((HostVO)args[0], (StartupCommand[])args[1], (ServerResource)args[2], (Map<String, String>)args[3],
 -                            (List<String>)args[4]);
 +                        (List<String>)args[4]);
                      if (result != null && singleTaker) {
                          break;
                      }
@@@ -1460,9 -1489,10 +1489,10 @@@
          String cidrSubnet = NetUtils.getCidrSubNet(cidrAddress, cidrSize);
          String serverSubnet = NetUtils.getSubNet(serverPrivateIP, serverPrivateNetmask);
          if (!cidrSubnet.equals(serverSubnet)) {
-             s_logger.warn("The private ip address of the server (" + serverPrivateIP + ") is not compatible with the CIDR of pod: " + pod.getName() + " and zone: " + dc.getName());
+             s_logger.warn("The private ip address of the server (" + serverPrivateIP + ") is not compatible with the CIDR of pod: " + pod.getName() + " and zone: " +
+                 dc.getName());
              throw new IllegalArgumentException("The private ip address of the server (" + serverPrivateIP + ") is not compatible with the CIDR of pod: " + pod.getName() +
 -                " and zone: " + dc.getName());
 +                                               " and zone: " + dc.getName());
          }
  
          // If the server's private netmask is less inclusive than the pod's CIDR

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java
index 1ce76a9,3a7251b..6b4bdd9
--- a/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java
+++ b/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java
@@@ -382,48 -402,51 +404,51 @@@ public class ResourceLimitManagerImpl e
          Transaction.execute(new TransactionCallbackWithExceptionNoReturn<ResourceAllocationException>() {
              @Override
              public void doInTransactionWithoutResult(TransactionStatus status) throws ResourceAllocationException {
 -                // Lock all rows first so nobody else can read it
 -                Set<Long> rowIdsToLock = _resourceCountDao.listAllRowsToUpdate(account.getId(), ResourceOwnerType.Account, type);
 -                SearchCriteria<ResourceCountVO> sc = ResourceCountSearch.create();
 -                sc.setParameters("id", rowIdsToLock.toArray());
 -                _resourceCountDao.lockRows(sc, null, true);
 -
 -                // Check account limits
 -                long accountLimit = findCorrectResourceLimitForAccount(account, type);
 -                long potentialCount = _resourceCountDao.getResourceCount(account.getId(), ResourceOwnerType.Account, type) + numResources;
 -                if (accountLimit != Resource.RESOURCE_UNLIMITED && potentialCount > accountLimit) {
 +            // Lock all rows first so nobody else can read it
 +            Set<Long> rowIdsToLock = _resourceCountDao.listAllRowsToUpdate(account.getId(), ResourceOwnerType.Account, type);
 +            SearchCriteria<ResourceCountVO> sc = ResourceCountSearch.create();
 +            sc.setParameters("id", rowIdsToLock.toArray());
 +            _resourceCountDao.lockRows(sc, null, true);
 +
 +            // Check account limits
 +            long accountLimit = findCorrectResourceLimitForAccount(account, type);
 +            long potentialCount = _resourceCountDao.getResourceCount(account.getId(), ResourceOwnerType.Account, type) + numResources;
 +            if (accountLimit != Resource.RESOURCE_UNLIMITED && potentialCount > accountLimit) {
-                 String message = "Maximum number of resources of type '" + type + "' for account name=" + account.getAccountName()
-                         + " in domain id=" + account.getDomainId() + " has been exceeded.";
+                     String message =
+                         "Maximum number of resources of type '" + type + "' for account name=" + account.getAccountName() + " in domain id=" + account.getDomainId() +
+                             " has been exceeded.";
                      if (projectFinal != null) {
-                         message = "Maximum number of resources of type '" + type + "' for project name=" + projectFinal.getName()
-                             + " in domain id=" + account.getDomainId() + " has been exceeded.";
+                         message =
+                             "Maximum number of resources of type '" + type + "' for project name=" + projectFinal.getName() + " in domain id=" + account.getDomainId() +
+                                 " has been exceeded.";
 -                    }
 -                    throw new ResourceAllocationException(message, type);
                  }
 +                throw new ResourceAllocationException(message, type);
 +            }
  
 -                // check all domains in the account's domain hierarchy
 -                Long domainId = null;
 +            // check all domains in the account's domain hierarchy
 +            Long domainId = null;
                  if (projectFinal != null) {
                      domainId = projectFinal.getDomainId();
 -                } else {
 -                    domainId = account.getDomainId();
 -                }
 +            } else {
 +                domainId = account.getDomainId();
 +            }
  
 -                while (domainId != null) {
 -                    DomainVO domain = _domainDao.findById(domainId);
 -                    // no limit check if it is ROOT domain
 -                    if (domainId != Domain.ROOT_DOMAIN) {
 -                        ResourceLimitVO domainLimit = _resourceLimitDao.findByOwnerIdAndType(domainId, ResourceOwnerType.Domain, type);
 -                        if (domainLimit != null && domainLimit.getMax().longValue() != Resource.RESOURCE_UNLIMITED) {
 -                            long domainCount = _resourceCountDao.getResourceCount(domainId, ResourceOwnerType.Domain, type);
 -                            if ((domainCount + numResources) > domainLimit.getMax().longValue()) {
 +            while (domainId != null) {
 +                DomainVO domain = _domainDao.findById(domainId);
 +                // no limit check if it is ROOT domain
 +                if (domainId != Domain.ROOT_DOMAIN) {
 +                    ResourceLimitVO domainLimit = _resourceLimitDao.findByOwnerIdAndType(domainId, ResourceOwnerType.Domain, type);
 +                    if (domainLimit != null && domainLimit.getMax().longValue() != Resource.RESOURCE_UNLIMITED) {
 +                        long domainCount = _resourceCountDao.getResourceCount(domainId, ResourceOwnerType.Domain, type);
 +                        if ((domainCount + numResources) > domainLimit.getMax().longValue()) {
-                             throw new ResourceAllocationException("Maximum number of resources of type '" + type + "' for domain id=" + domainId + " has been exceeded.", type);
+                                 throw new ResourceAllocationException("Maximum number of resources of type '" + type + "' for domain id=" + domainId +
+                                     " has been exceeded.", type);
 -                            }
                          }
                      }
 -                    domainId = domain.getParent();
                  }
 +                domainId = domain.getParent();
              }
 +        }
          });
      }
  
@@@ -609,8 -636,8 +638,8 @@@
              }
  
              //only Unlimited value is accepted if account is  Root Admin
-             if (_accountMgr.isRootAdmin(account.getId()) && max.shortValue() != ResourceLimit.RESOURCE_UNLIMITED) {
-                 throw new InvalidParameterValueException("Only " + ResourceLimit.RESOURCE_UNLIMITED + " limit is supported for Root Admin accounts");
 -            if (_accountMgr.isRootAdmin(account.getType()) && max.shortValue() != Resource.RESOURCE_UNLIMITED) {
++            if (_accountMgr.isRootAdmin(account.getId()) && max.shortValue() != Resource.RESOURCE_UNLIMITED) {
+                 throw new InvalidParameterValueException("Only " + Resource.RESOURCE_UNLIMITED + " limit is supported for Root Admin accounts");
              }
  
              if ((caller.getAccountId() == accountId.longValue()) &&
@@@ -754,48 -782,48 +785,48 @@@
          return Transaction.execute(new TransactionCallback<Long>() {
              @Override
              public Long doInTransaction(TransactionStatus status) {
 -                long newCount = 0;
 +        long newCount = 0;
  
 -                // Lock all rows first so nobody else can read it
 -                Set<Long> rowIdsToLock = _resourceCountDao.listAllRowsToUpdate(domainId, ResourceOwnerType.Domain, type);
 -                SearchCriteria<ResourceCountVO> sc = ResourceCountSearch.create();
 -                sc.setParameters("id", rowIdsToLock.toArray());
 -                _resourceCountDao.lockRows(sc, null, true);
 +            // Lock all rows first so nobody else can read it
 +            Set<Long> rowIdsToLock = _resourceCountDao.listAllRowsToUpdate(domainId, ResourceOwnerType.Domain, type);
 +            SearchCriteria<ResourceCountVO> sc = ResourceCountSearch.create();
 +            sc.setParameters("id", rowIdsToLock.toArray());
 +            _resourceCountDao.lockRows(sc, null, true);
  
 -                ResourceCountVO domainRC = _resourceCountDao.findByOwnerAndType(domainId, ResourceOwnerType.Domain, type);
 -                long oldCount = domainRC.getCount();
 +            ResourceCountVO domainRC = _resourceCountDao.findByOwnerAndType(domainId, ResourceOwnerType.Domain, type);
 +            long oldCount = domainRC.getCount();
  
 -                List<DomainVO> domainChildren = _domainDao.findImmediateChildrenForParent(domainId);
 -                // for each child domain update the resource count
 -                if (type.supportsOwner(ResourceOwnerType.Domain)) {
 +            List<DomainVO> domainChildren = _domainDao.findImmediateChildrenForParent(domainId);
 +            // for each child domain update the resource count
 +            if (type.supportsOwner(ResourceOwnerType.Domain)) {
  
 -                    // calculate project count here
 -                    if (type == ResourceType.project) {
 -                        newCount = newCount + _projectDao.countProjectsForDomain(domainId);
 -                    }
 +                // calculate project count here
 +                if (type == ResourceType.project) {
 +                    newCount = newCount + _projectDao.countProjectsForDomain(domainId);
 +                }
  
 -                    for (DomainVO domainChild : domainChildren) {
 -                        long domainCount = recalculateDomainResourceCount(domainChild.getId(), type);
 -                        newCount = newCount + domainCount; // add the child domain count to parent domain count
 -                    }
 +                for (DomainVO domainChild : domainChildren) {
 +                    long domainCount = recalculateDomainResourceCount(domainChild.getId(), type);
 +                    newCount = newCount + domainCount; // add the child domain count to parent domain count
                  }
 +            }
  
 -                if (type.supportsOwner(ResourceOwnerType.Account)) {
 -                    List<AccountVO> accounts = _accountDao.findActiveAccountsForDomain(domainId);
 -                    for (AccountVO account : accounts) {
 -                        long accountCount = recalculateAccountResourceCount(account.getId(), type);
 -                        newCount = newCount + accountCount; // add account's resource count to parent domain count
 -                    }
 +            if (type.supportsOwner(ResourceOwnerType.Account)) {
 +                List<AccountVO> accounts = _accountDao.findActiveAccountsForDomain(domainId);
 +                for (AccountVO account : accounts) {
 +                    long accountCount = recalculateAccountResourceCount(account.getId(), type);
 +                    newCount = newCount + accountCount; // add account's resource count to parent domain count
                  }
 -                _resourceCountDao.setResourceCount(domainId, ResourceOwnerType.Domain, type, newCount);
 +            }
 +            _resourceCountDao.setResourceCount(domainId, ResourceOwnerType.Domain, type, newCount);
  
 -                if (oldCount != newCount) {
 +            if (oldCount != newCount) {
-                 s_logger.info("Discrepency in the resource count " + "(original count=" + oldCount + " correct count = " +
-                         newCount + ") for type " + type + " for domain ID " + domainId + " is fixed during resource count recalculation.");
+                     s_logger.info("Discrepency in the resource count " + "(original count=" + oldCount + " correct count = " + newCount + ") for type " + type +
+                         " for domain ID " + domainId + " is fixed during resource count recalculation.");
 -                }
 -
 -                return newCount;
              }
 +
 +        return newCount;
 +    }
          });
      }
  
@@@ -804,56 -832,56 +835,56 @@@
          Long newCount = Transaction.execute(new TransactionCallback<Long>() {
              @Override
              public Long doInTransaction(TransactionStatus status) {
 -                Long newCount = null;
 -
 -                // this lock guards against the updates to user_vm, volume, snapshot, public _ip and template table
 -                // as any resource creation precedes with the resourceLimitExceeded check which needs this lock too
 -                SearchCriteria<ResourceCountVO> sc = ResourceCountSearch.create();
 -                sc.setParameters("accountId", accountId);
 -                _resourceCountDao.lockRows(sc, null, true);
 -
 -                ResourceCountVO accountRC = _resourceCountDao.findByOwnerAndType(accountId, ResourceOwnerType.Account, type);
 -                long oldCount = 0;
 -                if (accountRC != null)
 -                    oldCount = accountRC.getCount();
 -
 -                if (type == Resource.ResourceType.user_vm) {
 -                    newCount = _userVmDao.countAllocatedVMsForAccount(accountId);
 -                } else if (type == Resource.ResourceType.volume) {
 -                    newCount = _volumeDao.countAllocatedVolumesForAccount(accountId);
 -                    long virtualRouterCount = _vmDao.findIdsOfAllocatedVirtualRoutersForAccount(accountId).size();
 -                    newCount = newCount - virtualRouterCount; // don't count the volumes of virtual router
 -                } else if (type == Resource.ResourceType.snapshot) {
 -                    newCount = _snapshotDao.countSnapshotsForAccount(accountId);
 -                } else if (type == Resource.ResourceType.public_ip) {
 -                    newCount = calculatePublicIpForAccount(accountId);
 -                } else if (type == Resource.ResourceType.template) {
 -                    newCount = _vmTemplateDao.countTemplatesForAccount(accountId);
 -                } else if (type == Resource.ResourceType.project) {
 -                    newCount = _projectAccountDao.countByAccountIdAndRole(accountId, Role.Admin);
 -                } else if (type == Resource.ResourceType.network) {
 -                    newCount = _networkDao.countNetworksUserCanCreate(accountId);
 -                } else if (type == Resource.ResourceType.vpc) {
 -                    newCount = _vpcDao.countByAccountId(accountId);
 -                } else if (type == Resource.ResourceType.cpu) {
 -                    newCount = countCpusForAccount(accountId);
 -                } else if (type == Resource.ResourceType.memory) {
 -                    newCount = calculateMemoryForAccount(accountId);
 -                } else if (type == Resource.ResourceType.primary_storage) {
 -                    List<Long> virtualRouters = _vmDao.findIdsOfAllocatedVirtualRoutersForAccount(accountId);
 -                    newCount = _volumeDao.primaryStorageUsedForAccount(accountId, virtualRouters);
 -                } else if (type == Resource.ResourceType.secondary_storage) {
 -                    newCount = calculateSecondaryStorageForAccount(accountId);
 -                } else {
 -                    throw new InvalidParameterValueException("Unsupported resource type " + type);
 -                }
 -                _resourceCountDao.setResourceCount(accountId, ResourceOwnerType.Account, type, (newCount == null) ? 0 : newCount.longValue());
 +        Long newCount = null;
 +
 +        // this lock guards against the updates to user_vm, volume, snapshot, public _ip and template table
 +        // as any resource creation precedes with the resourceLimitExceeded check which needs this lock too
 +        SearchCriteria<ResourceCountVO> sc = ResourceCountSearch.create();
 +        sc.setParameters("accountId", accountId);
 +        _resourceCountDao.lockRows(sc, null, true);
 +
 +        ResourceCountVO accountRC = _resourceCountDao.findByOwnerAndType(accountId, ResourceOwnerType.Account, type);
 +        long oldCount = 0;
 +        if (accountRC != null)
 +            oldCount = accountRC.getCount();
 +
 +        if (type == Resource.ResourceType.user_vm) {
 +            newCount = _userVmDao.countAllocatedVMsForAccount(accountId);
 +        } else if (type == Resource.ResourceType.volume) {
 +            newCount = _volumeDao.countAllocatedVolumesForAccount(accountId);
 +            long virtualRouterCount = _vmDao.findIdsOfAllocatedVirtualRoutersForAccount(accountId).size();
 +            newCount = newCount - virtualRouterCount; // don't count the volumes of virtual router
 +        } else if (type == Resource.ResourceType.snapshot) {
 +            newCount = _snapshotDao.countSnapshotsForAccount(accountId);
 +        } else if (type == Resource.ResourceType.public_ip) {
 +            newCount = calculatePublicIpForAccount(accountId);
 +        } else if (type == Resource.ResourceType.template) {
 +            newCount = _vmTemplateDao.countTemplatesForAccount(accountId);
 +        } else if (type == Resource.ResourceType.project) {
 +            newCount = _projectAccountDao.countByAccountIdAndRole(accountId, Role.Admin);
 +        } else if (type == Resource.ResourceType.network) {
 +            newCount = _networkDao.countNetworksUserCanCreate(accountId);
 +        } else if (type == Resource.ResourceType.vpc) {
 +            newCount = _vpcDao.countByAccountId(accountId);
 +        } else if (type == Resource.ResourceType.cpu) {
 +            newCount = countCpusForAccount(accountId);
 +        } else if (type == Resource.ResourceType.memory) {
 +            newCount = calculateMemoryForAccount(accountId);
 +        } else if (type == Resource.ResourceType.primary_storage) {
 +            List<Long> virtualRouters = _vmDao.findIdsOfAllocatedVirtualRoutersForAccount(accountId);
 +            newCount = _volumeDao.primaryStorageUsedForAccount(accountId, virtualRouters);
 +        } else if (type == Resource.ResourceType.secondary_storage) {
 +            newCount = calculateSecondaryStorageForAccount(accountId);
 +        } else {
 +            throw new InvalidParameterValueException("Unsupported resource type " + type);
 +        }
 +        _resourceCountDao.setResourceCount(accountId, ResourceOwnerType.Account, type, (newCount == null) ? 0 : newCount.longValue());
  
 -                if (oldCount != newCount) {
 +        if (oldCount != newCount) {
-             s_logger.info("Discrepency in the resource count " + "(original count=" + oldCount + " correct count = " +
-                     newCount + ") for type " + type + " for account ID " + accountId + " is fixed during resource count recalculation.");
+                     s_logger.info("Discrepency in the resource count " + "(original count=" + oldCount + " correct count = " + newCount + ") for type " + type +
+                         " for account ID " + accountId + " is fixed during resource count recalculation.");
 -                }
 +        }
-                 
+ 
                  return newCount;
              }
          });