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:42 UTC

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

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/server/src/com/cloud/network/NetworkServiceImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/network/NetworkServiceImpl.java
index b4f26c7,056190f..4b7195c
--- a/server/src/com/cloud/network/NetworkServiceImpl.java
+++ b/server/src/com/cloud/network/NetworkServiceImpl.java
@@@ -188,9 -188,8 +190,8 @@@ import com.cloud.vm.dao.VMInstanceDao
  /**
   * NetworkServiceImpl implements NetworkService.
   */
- @Local(value = { NetworkService.class })
+ @Local(value = {NetworkService.class})
 -public class NetworkServiceImpl extends ManagerBase implements NetworkService {
 +public class NetworkServiceImpl extends ManagerBase implements  NetworkService {
      private static final Logger s_logger = Logger.getLogger(NetworkServiceImpl.class);
  
      private static final long MIN_VLAN_ID = 0L;
@@@ -696,16 -678,17 +680,17 @@@
              } catch (InsufficientAddressCapacityException e) {
                  throw new InvalidParameterValueException("Allocating guest ip for nic failed");
              }
-         } else if (dc.getNetworkType() == NetworkType.Basic || ntwkOff.getGuestType()  == Network.GuestType.Shared) {
-             //handle the basic networks here
+         } else if (network.getGuestType() == Network.GuestType.Shared) {
+             //for basic zone, need to provide the podId to ensure proper ip alloation
+             Long podId = null;
+             DataCenter dc = _dcDao.findById(network.getDataCenterId());
+ 
+             if (dc.getNetworkType() == NetworkType.Basic) {
 -                VMInstanceVO vmi = (VMInstanceVO)vm;
 +            VMInstanceVO vmi = (VMInstanceVO)vm;
-             Long podId = vmi.getPodIdToDeployIn();
+                 podId = vmi.getPodIdToDeployIn();
 -                if (podId == null) {
 +            if (podId == null) {
-                 throw new InvalidParameterValueException("vm pod id is null");
+                     throw new InvalidParameterValueException("vm pod id is null in Basic zone; can't decide the range for ip allocation");
 -                }
 +            }
-             Pod pod = _hostPodDao.findById(podId);
-             if (pod == null) {
-                 throw new InvalidParameterValueException("vm pod is null");
              }
  
              try {
@@@ -728,18 -711,18 +713,18 @@@
              long id = Transaction.execute(new TransactionCallback<Long>() {
                  @Override
                  public Long doInTransaction(TransactionStatus status) {
 -                    boolean nicSecondaryIpSet = nicVO.getSecondaryIp();
 -                    if (!nicSecondaryIpSet) {
 -                        nicVO.setSecondaryIp(true);
 -                        // commit when previously set ??
 -                        s_logger.debug("Setting nics table ...");
 -                        _nicDao.update(nicId, nicVO);
 -                    }
 +            boolean nicSecondaryIpSet = nicVO.getSecondaryIp();
 +            if (!nicSecondaryIpSet) {
 +                nicVO.setSecondaryIp(true);
 +                // commit when previously set ??
 +                s_logger.debug("Setting nics table ...");
 +                _nicDao.update(nicId, nicVO);
 +            }
  
 -                    s_logger.debug("Setting nic_secondary_ip table ...");
 +            s_logger.debug("Setting nic_secondary_ip table ...");
                      Long vmId = nicVO.getInstanceId();
-                     NicSecondaryIpVO secondaryIpVO = new NicSecondaryIpVO(nicId, addrFinal, vmId, accountId, domainId, networkId);
+                     NicSecondaryIpVO secondaryIpVO = new NicSecondaryIpVO(nicId, addrFinal, vmId, ipOwner.getId(), ipOwner.getDomainId(), networkId);
 -                    _nicSecondaryIpDao.persist(secondaryIpVO);
 +            _nicSecondaryIpDao.persist(secondaryIpVO);
                      return secondaryIpVO.getId();
                  }
              });
@@@ -797,10 -780,10 +782,10 @@@
          if (dc.getNetworkType() == NetworkType.Advanced && network.getGuestType() == Network.GuestType.Isolated) {
              //check PF or static NAT is configured on this ip address
              String secondaryIp = secIpVO.getIp4Address();
 -            List<FirewallRuleVO> fwRulesList = _firewallDao.listByNetworkAndPurpose(network.getId(), Purpose.PortForwarding);
 +            List<FirewallRuleVO> fwRulesList =  _firewallDao.listByNetworkAndPurpose(network.getId(), Purpose.PortForwarding);
  
              if (fwRulesList.size() != 0) {
-                 for (FirewallRuleVO rule: fwRulesList) {
+                 for (FirewallRuleVO rule : fwRulesList) {
                      if (_portForwardingDao.findByIdAndIp(rule.getId(), secondaryIp) != null) {
                          s_logger.debug("VM nic IP " + secondaryIp + " is associated with the port forwarding rule");
                          throw new InvalidParameterValueException("Can't remove the secondary ip " + secondaryIp + " is associate with the port forwarding rule");
@@@ -813,8 -796,8 +798,8 @@@
                  s_logger.debug("VM nic IP " + secondaryIp + " is associated with the static NAT rule public IP address id " + publicIpVO.getId());
                  throw new InvalidParameterValueException("Can' remove the ip " + secondaryIp + "is associate with static NAT rule public IP address id " + publicIpVO.getId());
              }
 -        } else if (dc.getNetworkType() == NetworkType.Basic || ntwkOff.getGuestType() == Network.GuestType.Shared) {
 +        } else if (dc.getNetworkType() == NetworkType.Basic || ntwkOff.getGuestType()  == Network.GuestType.Shared) {
-             final IPAddressVO ip = _ipAddressDao.findByIpAndNetworkId(secIpVO.getNetworkId(), secIpVO.getIp4Address());
+             final IPAddressVO ip = _ipAddressDao.findByIpAndSourceNetworkId(secIpVO.getNetworkId(), secIpVO.getIp4Address());
              if (ip != null) {
                  Transaction.execute(new TransactionCallbackNoReturn() {
                      @Override
@@@ -1035,11 -1014,11 +1019,11 @@@
              zoneId = pNtwk.getDataCenterId();
          }
  
 -        if (displayNetwork != null) {
 -            if (!_accountMgr.isRootAdmin(caller.getType())) {
 +        if(displayNetwork != null){
 +            if(!_accountMgr.isRootAdmin(caller.getId())){
                  throw new PermissionDeniedException("Only admin allowed to update displaynetwork parameter");
              }
-         }else{
+         } else {
              displayNetwork = true;
          }
  
@@@ -1203,12 -1180,11 +1185,11 @@@
          }
  
          // Regular user can create Guest Isolated Source Nat enabled network only
 -        if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL
 +        if (_accountMgr.isNormalUser(caller.getId())
                  && (ntwkOff.getTrafficType() != TrafficType.Guest || ntwkOff.getGuestType() != Network.GuestType.Isolated
                          && areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
-             throw new InvalidParameterValueException("Regular user can create a network only from the network" +
-                     " offering having traffic type " + TrafficType.Guest + " and network type "
-                     + Network.GuestType.Isolated + " with a service " + Service.SourceNat.getName() + " enabled");
+             throw new InvalidParameterValueException("Regular user can create a network only from the network" + " offering having traffic type " + TrafficType.Guest
+                     + " and network type " + Network.GuestType.Isolated + " with a service " + Service.SourceNat.getName() + " enabled");
          }
  
          // Don't allow to specify vlan if the caller is not ROOT admin
@@@ -1217,16 -1193,16 +1198,16 @@@
          }
  
          if (ipv4) {
-         	// For non-root admins check cidr limit - if it's allowed by global config value
+             // For non-root admins check cidr limit - if it's allowed by global config value
 -            if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN && cidr != null) {
 +            if (!_accountMgr.isRootAdmin(caller.getId()) && cidr != null) {
  
-         		String[] cidrPair = cidr.split("\\/");
-         		int cidrSize = Integer.valueOf(cidrPair[1]);
+                 String[] cidrPair = cidr.split("\\/");
+                 int cidrSize = Integer.valueOf(cidrPair[1]);
  
-         		if (cidrSize < _cidrLimit) {
-         			throw new InvalidParameterValueException("Cidr size can't be less than " + _cidrLimit);
-         		}
-         	}
+                 if (cidrSize < _cidrLimit) {
+                     throw new InvalidParameterValueException("Cidr size can't be less than " + _cidrLimit);
+                 }
+             }
          }
  
          Collection<String> ntwkProviders = _networkMgr.finalizeServicesAndProvidersForNetwork(ntwkOff, physicalNetworkId).values();
@@@ -1317,62 -1288,61 +1293,61 @@@
                      Account owner = ownerFinal;
                      Boolean subdomainAccess = subdomainAccessFinal;
  
 -                    Long sharedDomainId = null;
 -                    if (isDomainSpecific) {
 -                        if (domainId != null) {
 -                            sharedDomainId = domainId;
 -                        } else {
 -                            sharedDomainId = _domainMgr.getDomain(Domain.ROOT_DOMAIN).getId();
 -                            subdomainAccess = true;
 -                        }
 -                    }
 +        Long sharedDomainId = null;
 +        if (isDomainSpecific) {
 +            if (domainId != null) {
 +                sharedDomainId = domainId;
 +            } else {
 +                sharedDomainId = _domainMgr.getDomain(Domain.ROOT_DOMAIN).getId();
 +                subdomainAccess = true;
 +            }
 +        }
  
 -                    // default owner to system if network has aclType=Domain
 -                    if (aclType == ACLType.Domain) {
 -                        owner = _accountMgr.getAccount(Account.ACCOUNT_ID_SYSTEM);
 -                    }
 +        // default owner to system if network has aclType=Domain
 +        if (aclType == ACLType.Domain) {
 +            owner = _accountMgr.getAccount(Account.ACCOUNT_ID_SYSTEM);
 +        }
  
 -                    //Create guest network
 -                    Network network = null;
 -                    if (vpcId != null) {
 +        //Create guest network
 +        Network network = null;
 +        if (vpcId != null) {
-             if (!_configMgr.isOfferingForVpc(ntwkOff)){
+                         if (!_configMgr.isOfferingForVpc(ntwkOff)) {
 -                            throw new InvalidParameterValueException("Network offering can't be used for VPC networks");
 -                        }
 +                throw new InvalidParameterValueException("Network offering can't be used for VPC networks");
 +            }
  
-             if(aclId != null){
+                         if (aclId != null) {
 -                            NetworkACL acl = _networkACLDao.findById(aclId);
 +                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");
 +                }
  
-                 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 should be associated with a VPC
 +                    //ACL is not default DENY/ALLOW
 +                    // ACL should be associated with a VPC
-                     if(!vpcId.equals(acl.getVpcId())){
-                         throw new InvalidParameterValueException("ACL: "+aclId+" do not belong to the VPC");
+                                 if (!vpcId.equals(acl.getVpcId())) {
+                                     throw new InvalidParameterValueException("ACL: " + aclId + " do not belong to the VPC");
 -                                }
 -                            }
 -                        }
 +                    }
 +                }
 +            }
-             network = _vpcMgr.createVpcGuestNetwork(networkOfferingId, name, displayText, gateway, cidr, vlanId,
-                     networkDomain, owner, sharedDomainId, pNtwk, zoneId, aclType, subdomainAccess, vpcId, aclId, caller, displayNetwork);
+                         network = _vpcMgr.createVpcGuestNetwork(networkOfferingId, name, displayText, gateway, cidr, vlanId, networkDomain, owner, sharedDomainId, pNtwk, zoneId,
+                                 aclType, subdomainAccess, vpcId, aclId, caller, displayNetwork);
 -                    } else {
 +        } else {
-             if (_configMgr.isOfferingForVpc(ntwkOff)){
+                         if (_configMgr.isOfferingForVpc(ntwkOff)) {
 -                            throw new InvalidParameterValueException("Network offering can be used for VPC networks only");
 -                        }
 -                        if (ntwkOff.getInternalLb()) {
 -                            throw new InvalidParameterValueException("Internal Lb can be enabled on vpc networks only");
 -                        }
 +                throw new InvalidParameterValueException("Network offering can be used for VPC networks only");
 +            }
 +            if (ntwkOff.getInternalLb()) {
 +                throw new InvalidParameterValueException("Internal Lb can be enabled on vpc networks only");
 +            }
  
-             network = _networkMgr.createGuestNetwork(networkOfferingId, name, displayText, gateway, cidr, vlanId,
-             		networkDomain, owner, sharedDomainId, pNtwk, zoneId, aclType, subdomainAccess, vpcId,
-             		ip6Gateway, ip6Cidr, displayNetwork, isolatedPvlan);
+                         network = _networkMgr.createGuestNetwork(networkOfferingId, name, displayText, gateway, cidr, vlanId, networkDomain, owner, sharedDomainId, pNtwk, zoneId,
+                                 aclType, subdomainAccess, vpcId, ip6Gateway, ip6Cidr, displayNetwork, isolatedPvlan);
 -                    }
 +        }
  
 -                    if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN && createVlan) {
 -                        // Create vlan ip range
 +        if (_accountMgr.isRootAdmin(caller.getId()) && createVlan) {
 +            // Create vlan ip range
-             _configMgr.createVlanAndPublicIpRange(pNtwk.getDataCenterId(), network.getId(), physicalNetworkId,
-                     false, null, startIP, endIP, gateway, netmask, vlanId, null, startIPv6, endIPv6, ip6Gateway, ip6Cidr);
+                         _configMgr.createVlanAndPublicIpRange(pNtwk.getDataCenterId(), network.getId(), physicalNetworkId, false, null, startIP, endIP, gateway, netmask, vlanId,
+                                 null, startIPv6, endIPv6, ip6Gateway, ip6Cidr);
 -                    }
 +        }
                      return network;
                  }
              });
@@@ -1528,13 -1498,11 +1503,11 @@@
              sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER);
          }
  
- 
 -        SearchBuilder<AccountVO> accountSearch = _accountDao.createSearchBuilder();
 +            SearchBuilder<AccountVO> accountSearch = _accountDao.createSearchBuilder();
          accountSearch.and("typeNEQ", accountSearch.entity().getType(), SearchCriteria.Op.NEQ);
          accountSearch.and("typeEQ", accountSearch.entity().getType(), SearchCriteria.Op.EQ);
  
- 
 -        sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER);
 +            sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER);
  
          List<NetworkVO> networksToReturn = new ArrayList<NetworkVO>();
  
@@@ -2001,10 -1976,18 +1981,18 @@@
              network.setDisplayText(displayText);
          }
  
-         if(displayNetwork != null){
+         // display flag is not null and has changed
+         if (displayNetwork != null && displayNetwork != network.getDisplayNetwork()) {
 -            if (!_accountMgr.isRootAdmin(callerAccount.getType())) {
 +            if (!_accountMgr.isRootAdmin(callerAccount.getId())) {
                  throw new PermissionDeniedException("Only admin allowed to update displaynetwork parameter");
              }
+ 
+             // Update resource count if it needs to be updated
+             NetworkOffering networkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId());
+             if (_networkMgr.resourceCountNeedsUpdate(networkOffering, network.getAclType())) {
+                 _resourceLimitMgr.changeResourceCount(network.getAccountId(), Resource.ResourceType.network, displayNetwork);
+             }
+ 
              network.setDisplayNetwork(displayNetwork);
          }
  
@@@ -2098,9 -2081,9 +2086,9 @@@
          DataCenter dc = _dcDao.findById(network.getDataCenterId());
          String networkCidr = network.getNetworkCidr();
  
-         if (guestVmCidr!= null ) {
-             if(dc.getNetworkType() == NetworkType.Basic) {
+         if (guestVmCidr != null) {
+             if (dc.getNetworkType() == NetworkType.Basic) {
 -                throw new InvalidParameterValueException("Guest VM CIDR can't be specified for zone with " + NetworkType.Basic + " networking");
 +                throw new InvalidParameterValueException("Guest VM CIDR can't be specified for zone with " + NetworkType.Basic  + " networking");
              }
              if (network.getGuestType() != GuestType.Isolated) {
                  throw new InvalidParameterValueException("Can only allow IP Reservation in networks with guest type " + GuestType.Isolated);
@@@ -2131,59 -2117,60 +2122,60 @@@
              }
  
              // This check makes sure there are no active IPs existing outside the guestVmCidr in the network
 -            String[] guestVmCidrPair = guestVmCidr.split("\\/");
 -            Long size = Long.valueOf(guestVmCidrPair[1]);
 -            List<NicVO> nicsPresent = _nicDao.listByNetworkId(networkId);
 +                String[] guestVmCidrPair = guestVmCidr.split("\\/");
 +                Long size = Long.valueOf(guestVmCidrPair[1]);
 +                List<NicVO> nicsPresent = _nicDao.listByNetworkId(networkId);
  
 -            String cidrIpRange[] = NetUtils.getIpRangeFromCidr(guestVmCidrPair[0], size);
 +                String cidrIpRange[] = NetUtils.getIpRangeFromCidr(guestVmCidrPair[0], size);
-                 s_logger.info("The start IP of the specified guest vm cidr is: " +  cidrIpRange[0] +" and end IP is: " +  cidrIpRange[1]);
+             s_logger.info("The start IP of the specified guest vm cidr is: " + cidrIpRange[0] + " and end IP is: " + cidrIpRange[1]);
 -            long startIp = NetUtils.ip2Long(cidrIpRange[0]);
 -            long endIp = NetUtils.ip2Long(cidrIpRange[1]);
 -            long range = endIp - startIp + 1;
 -            s_logger.info("The specified guest vm cidr has " + range + " IPs");
 -
 -            for (NicVO nic : nicsPresent) {
 -                long nicIp = NetUtils.ip2Long(nic.getIp4Address());
 -                //check if nic IP is outside the guest vm cidr
 -                if (nicIp < startIp || nicIp > endIp) {
 +                long startIp = NetUtils.ip2Long(cidrIpRange[0]);
 +                long endIp = NetUtils.ip2Long(cidrIpRange[1]);
 +                long range =  endIp - startIp + 1;
 +                s_logger.info("The specified guest vm cidr has " +  range + " IPs");
 +
 +                for (NicVO nic : nicsPresent) {
 +                    long nicIp = NetUtils.ip2Long(nic.getIp4Address());
 +                    //check if nic IP is outside the guest vm cidr
 +                    if (nicIp < startIp || nicIp > endIp) {
-                         if(!(nic.getState() == Nic.State.Deallocating)) {
+                     if (!(nic.getState() == Nic.State.Deallocating)) {
 -                        throw new InvalidParameterValueException("Active IPs like " + nic.getIp4Address() + " exist outside the Guest VM CIDR. Cannot apply reservation ");
 +                            throw new InvalidParameterValueException("Active IPs like " + nic.getIp4Address() + " exist outside the Guest VM CIDR. Cannot apply reservation ");
 +                            }
 +                        }
                      }
 -                }
 -            }
  
 -            // In some scenarios even though guesVmCidr and network CIDR do not appear similar but
 -            // the IP ranges exactly matches, in these special cases make sure no Reservation gets applied
 -            if (network.getNetworkCidr() == null) {
 -                if (NetUtils.isSameIpRange(guestVmCidr, network.getCidr()) && !guestVmCidr.equals(network.getCidr())) {
 +                // In some scenarios even though guesVmCidr and network CIDR do not appear similar but
 +                // the IP ranges exactly matches, in these special cases make sure no Reservation gets applied
 +                if (network.getNetworkCidr() == null) {
 +                    if (NetUtils.isSameIpRange(guestVmCidr, network.getCidr()) && !guestVmCidr.equals(network.getCidr())) {
-                         throw new InvalidParameterValueException("The Start IP and End IP of guestvmcidr: "+ guestVmCidr + " and CIDR: " + network.getCidr() + " are same, " +
-                                 "even though both the cidrs appear to be different. As a precaution no IP Reservation will be applied.");
+                     throw new InvalidParameterValueException("The Start IP and End IP of guestvmcidr: " + guestVmCidr + " and CIDR: " + network.getCidr() + " are same, "
+                             + "even though both the cidrs appear to be different. As a precaution no IP Reservation will be applied.");
 -                }
 -            } else {
 +                    }
 +                } else {
-                     if(NetUtils.isSameIpRange(guestVmCidr, network.getNetworkCidr()) && !guestVmCidr.equals(network.getNetworkCidr())) {
-                         throw new InvalidParameterValueException("The Start IP and End IP of guestvmcidr: "+ guestVmCidr + " and Network CIDR: " + network.getNetworkCidr() + " are same, " +
-                                 "even though both the cidrs appear to be different. As a precaution IP Reservation will not be affected. If you want to reset IP Reservation, " +
-                                 "specify guestVmCidr to be: " + network.getNetworkCidr());
+                 if (NetUtils.isSameIpRange(guestVmCidr, network.getNetworkCidr()) && !guestVmCidr.equals(network.getNetworkCidr())) {
+                     throw new InvalidParameterValueException("The Start IP and End IP of guestvmcidr: " + guestVmCidr + " and Network CIDR: " + network.getNetworkCidr()
+                             + " are same, "
+                             + "even though both the cidrs appear to be different. As a precaution IP Reservation will not be affected. If you want to reset IP Reservation, "
+                             + "specify guestVmCidr to be: " + network.getNetworkCidr());
 +                    }
                  }
 -            }
  
 -            // When reservation is applied for the first time, network_cidr will be null
 -            // Populate it with the actual network cidr
 -            if (network.getNetworkCidr() == null) {
 -                network.setNetworkCidr(network.getCidr());
 -            }
 +                // When reservation is applied for the first time, network_cidr will be null
 +                // Populate it with the actual network cidr
 +                if (network.getNetworkCidr() == null) {
 +                    network.setNetworkCidr(network.getCidr());
 +                }
  
 -            // Condition for IP Reservation reset : guestVmCidr and network CIDR are same
 -            if (network.getNetworkCidr().equals(guestVmCidr)) {
 -                s_logger.warn("Guest VM CIDR and Network CIDR both are same, reservation will reset.");
 -                network.setNetworkCidr(null);
 +                // Condition for IP Reservation reset : guestVmCidr and network CIDR are same
 +                if (network.getNetworkCidr().equals(guestVmCidr)) {
 +                    s_logger.warn("Guest VM CIDR and Network CIDR both are same, reservation will reset.");
 +                    network.setNetworkCidr(null);
 +                }
 +                // Finally update "cidr" with the guestVmCidr
 +                // which becomes the effective address space for CloudStack guest VMs
 +                network.setCidr(guestVmCidr);
 +                _networksDao.update(networkId, network);
 +                s_logger.info("IP Reservation has been applied. The new CIDR for Guests Vms is " + guestVmCidr);
              }
 -            // Finally update "cidr" with the guestVmCidr
 -            // which becomes the effective address space for CloudStack guest VMs
 -            network.setCidr(guestVmCidr);
 -            _networksDao.update(networkId, network);
 -            s_logger.info("IP Reservation has been applied. The new CIDR for Guests Vms is " + guestVmCidr);
 -        }
  
          ReservationContext context = new ReservationContextImpl(null, null, callerUser, callerAccount);
          // 1) Shutdown all the elements and cleanup all the rules. Don't allow to shutdown network in intermediate
@@@ -2242,33 -2232,34 +2237,34 @@@
                  Transaction.execute(new TransactionCallbackNoReturn() {
                      @Override
                      public void doInTransactionWithoutResult(TransactionStatus status) {
 -                        network.setNetworkOfferingId(networkOfferingId);
 -                        _networksDao.update(networkId, network, newSvcProviders);
 -                        // get all nics using this network
 -                        // log remove usage events for old offering
 -                        // log assign usage events for new offering
 -                        List<NicVO> nics = _nicDao.listByNetworkId(networkId);
 -                        for (NicVO nic : nics) {
 -                            long vmId = nic.getInstanceId();
 -                            VMInstanceVO vm = _vmDao.findById(vmId);
 -                            if (vm == null) {
 -                                s_logger.error("Vm for nic " + nic.getId() + " not found with Vm Id:" + vmId);
 -                                continue;
 -                            }
 -                            long isDefault = (nic.isDefaultNic()) ? 1 : 0;
 -                            String nicIdString = Long.toString(nic.getId());
 +                network.setNetworkOfferingId(networkOfferingId);
 +                _networksDao.update(networkId, network, newSvcProviders);
 +                // get all nics using this network
 +                // log remove usage events for old offering
 +                // log assign usage events for new offering
 +                List<NicVO> nics = _nicDao.listByNetworkId(networkId);
 +                for (NicVO nic : nics) {
 +                    long vmId = nic.getInstanceId();
 +                    VMInstanceVO vm = _vmDao.findById(vmId);
 +                    if (vm == null) {
 +                        s_logger.error("Vm for nic " + nic.getId() + " not found with Vm Id:" + vmId);
 +                        continue;
 +                    }
 +                    long isDefault = (nic.isDefaultNic()) ? 1 : 0;
 +                    String nicIdString = Long.toString(nic.getId());
-                     UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_REMOVE, vm.getAccountId(), vm.getDataCenterId(),
-                             vm.getId(), nicIdString, oldNetworkOfferingId, null, isDefault, VirtualMachine.class.getName(), vm.getUuid());
-                     UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_ASSIGN, vm.getAccountId(), vm.getDataCenterId(),
-                             vm.getId(), nicIdString, networkOfferingId, null, isDefault, VirtualMachine.class.getName(), vm.getUuid());
+                             UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_REMOVE, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), nicIdString,
+                                     oldNetworkOfferingId, null, isDefault, VirtualMachine.class.getName(), vm.getUuid());
+                             UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_ASSIGN, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), nicIdString,
+                                     networkOfferingId, null, isDefault, VirtualMachine.class.getName(), vm.getUuid());
 -                        }
 +                }
                      }
                  });
 -            } else {
 +            }   else {
                  network.setNetworkOfferingId(networkOfferingId);
-                 _networksDao.update(networkId, network, _networkMgr.finalizeServicesAndProvidersForNetwork(_entityMgr.findById(NetworkOffering.class, networkOfferingId), network.getPhysicalNetworkId()));
+                 _networksDao.update(networkId, network,
+                         _networkMgr.finalizeServicesAndProvidersForNetwork(_entityMgr.findById(NetworkOffering.class, networkOfferingId), network.getPhysicalNetworkId()));
              }
 -        } else {
 +        }   else {
              _networksDao.update(networkId, network);
          }
  
@@@ -2490,35 -2474,38 +2479,38 @@@
              return Transaction.execute(new TransactionCallback<PhysicalNetworkVO>() {
                  @Override
                  public PhysicalNetworkVO doInTransaction(TransactionStatus status) {
 -                    // Create the new physical network in the database
 -                    long id = _physicalNetworkDao.getNextInSequence(Long.class, "id");
 +            // Create the new physical network in the database
 +            long id = _physicalNetworkDao.getNextInSequence(Long.class, "id");
                      PhysicalNetworkVO pNetwork = new PhysicalNetworkVO(id, zoneId, vnetRange, networkSpeed, domainId, broadcastDomainRangeFinal, name);
 -                    pNetwork.setTags(tags);
 -                    pNetwork.setIsolationMethods(isolationMethods);
 +            pNetwork.setTags(tags);
 +            pNetwork.setIsolationMethods(isolationMethods);
  
 -                    pNetwork = _physicalNetworkDao.persist(pNetwork);
 +            pNetwork = _physicalNetworkDao.persist(pNetwork);
  
 -                    // Add vnet entries for the new zone if zone type is Advanced
 -                    if (vnetRange != null) {
 -                        addOrRemoveVnets(vnetRange.split(","), pNetwork);
 -                    }
 +            // Add vnet entries for the new zone if zone type is Advanced
 +            if (vnetRange != null) {
 +                addOrRemoveVnets(vnetRange.split(","), pNetwork);
 +            }
  
 -                    // add VirtualRouter as the default network service provider
 -                    addDefaultVirtualRouterToPhysicalNetwork(pNetwork.getId());
 +            // add VirtualRouter as the default network service provider
 +            addDefaultVirtualRouterToPhysicalNetwork(pNetwork.getId());
  
+                     if (pNetwork.getIsolationMethods().contains("GRE"))
+                         addDefaultOvsToPhysicalNetwork(pNetwork.getId());
+ 
 -                    // add security group provider to the physical network
 -                    addDefaultSecurityGroupProviderToPhysicalNetwork(pNetwork.getId());
 +            // add security group provider to the physical network
 +            addDefaultSecurityGroupProviderToPhysicalNetwork(pNetwork.getId());
  
 -                    // add VPCVirtualRouter as the defualt network service provider
 -                    addDefaultVpcVirtualRouterToPhysicalNetwork(pNetwork.getId());
 +            // add VPCVirtualRouter as the defualt network service provider
 +            addDefaultVpcVirtualRouterToPhysicalNetwork(pNetwork.getId());
  
 -                    // add baremetal as the defualt network service provider
 -                    addDefaultBaremetalProvidersToPhysicalNetwork(pNetwork.getId());
 +            // add baremetal as the defualt network service provider
 +            addDefaultBaremetalProvidersToPhysicalNetwork(pNetwork.getId());
  
 -                    //Add Internal Load Balancer element as a default network service provider
 -                    addDefaultInternalLbProviderToPhysicalNetwork(pNetwork.getId());
 +            //Add Internal Load Balancer element as a default network service provider
 +            addDefaultInternalLbProviderToPhysicalNetwork(pNetwork.getId());
  
 -                    return pNetwork;
 +            return pNetwork;
                  }
              });
          } catch (Exception ex) {
@@@ -2611,9 -2597,9 +2602,9 @@@
      }
  
      @DB
-     public void addOrRemoveVnets(String [] listOfRanges, final PhysicalNetworkVO network) {
+     public void addOrRemoveVnets(String[] listOfRanges, final PhysicalNetworkVO network) {
 -        List<String> addVnets = null;
 +        List<String>  addVnets = null;
-         List<String>  removeVnets =null;
+         List<String> removeVnets = null;
          HashSet<String> tempVnets = new HashSet<String>();
          HashSet<String> vnetsInDb = new HashSet<String>();
          List<Pair<Integer, Integer>> vnetranges = null;
@@@ -2660,18 -2646,18 +2651,18 @@@
                  @Override
                  public void doInTransactionWithoutResult(TransactionStatus status) {
                      if (addVnetsFinal != null) {
-                         s_logger.debug("Adding vnet range " + addVnetsFinal.toString()+ " for the physicalNetwork id= " + network.getId() + " and zone id=" + network.getDataCenterId()
-                         + " as a part of updatePhysicalNetwork call");
+                         s_logger.debug("Adding vnet range " + addVnetsFinal.toString() + " for the physicalNetwork id= " + network.getId() + " and zone id="
+                                 + network.getDataCenterId() + " as a part of updatePhysicalNetwork call");
 -                        //add vnet takes a list of strings to be added. each string is a vnet.
 +                //add vnet takes a list of strings to be added. each string is a vnet.
                          _dcDao.addVnet(network.getDataCenterId(), network.getId(), addVnetsFinal);
 -                    }
 +            }
                      if (removeVnetsFinal != null) {
-                         s_logger.debug("removing vnet range " + removeVnetsFinal.toString()+ " for the physicalNetwork id= " + network.getId() + " and zone id=" + network.getDataCenterId()
-                         + " as a part of updatePhysicalNetwork call");
+                         s_logger.debug("removing vnet range " + removeVnetsFinal.toString() + " for the physicalNetwork id= " + network.getId() + " and zone id="
+                                 + network.getDataCenterId() + " as a part of updatePhysicalNetwork call");
 -                        //deleteVnets  takes a list of strings to be removed. each string is a vnet.
 +                //deleteVnets  takes a list of strings to be removed. each string is a vnet.
-                         _datacneter_vnet.deleteVnets(TransactionLegacy.currentTxn(), network.getDataCenterId(), network.getId(), removeVnetsFinal);
+                         _datacneterVnet.deleteVnets(TransactionLegacy.currentTxn(), network.getDataCenterId(), network.getId(), removeVnetsFinal);
 -                    }
 -                    _physicalNetworkDao.update(network.getId(), network);
 +            }
 +            _physicalNetworkDao.update(network.getId(), network);
                  }
              });
  
@@@ -2748,8 -2736,7 +2741,7 @@@
  
      }
  
- 
 -    public String generateVnetString(List<String> vnetList) {
 +    public  String generateVnetString(List<String> vnetList) {
          Collections.sort(vnetList, new Comparator<String>() {
              @Override
              public int compare(String s1, String s2) {
@@@ -2826,10 -2812,9 +2817,9 @@@
                  }
              }
          }
 -        return removeVnets;
 +        return  removeVnets;
      }
  
- 
      @Override
      @ActionEvent(eventType = EventTypes.EVENT_PHYSICAL_NETWORK_DELETE, eventDescription = "deleting physical network", async = true)
      @DB
@@@ -2848,40 -2833,40 +2838,40 @@@
          return Transaction.execute(new TransactionCallback<Boolean>() {
              @Override
              public Boolean doInTransaction(TransactionStatus status) {
 -                // delete vlans for this zone
 -                List<VlanVO> vlans = _vlanDao.listVlansByPhysicalNetworkId(physicalNetworkId);
 -                for (VlanVO vlan : vlans) {
 -                    _vlanDao.remove(vlan.getId());
 -                }
 +        // delete vlans for this zone
 +        List<VlanVO> vlans = _vlanDao.listVlansByPhysicalNetworkId(physicalNetworkId);
 +        for (VlanVO vlan : vlans) {
 +            _vlanDao.remove(vlan.getId());
 +        }
  
 -                // Delete networks
 -                List<NetworkVO> networks = _networksDao.listByPhysicalNetwork(physicalNetworkId);
 -                if (networks != null && !networks.isEmpty()) {
 -                    for (NetworkVO network : networks) {
 -                        _networksDao.remove(network.getId());
 -                    }
 -                }
 +        // Delete networks
 +        List<NetworkVO> networks = _networksDao.listByPhysicalNetwork(physicalNetworkId);
 +        if (networks != null && !networks.isEmpty()) {
 +            for (NetworkVO network : networks) {
 +                _networksDao.remove(network.getId());
 +            }
 +        }
  
 -                // delete vnets
 -                _dcDao.deleteVnet(physicalNetworkId);
 +        // delete vnets
 +        _dcDao.deleteVnet(physicalNetworkId);
  
 -                // delete service providers
 -                List<PhysicalNetworkServiceProviderVO> providers = _pNSPDao.listBy(physicalNetworkId);
 +        // delete service providers
 +        List<PhysicalNetworkServiceProviderVO> providers = _pNSPDao.listBy(physicalNetworkId);
  
-         for(PhysicalNetworkServiceProviderVO provider : providers){
+                 for (PhysicalNetworkServiceProviderVO provider : providers) {
 -                    try {
 -                        deleteNetworkServiceProvider(provider.getId());
 +            try {
 +                deleteNetworkServiceProvider(provider.getId());
-             }catch (ResourceUnavailableException e) {
-                 s_logger.warn("Unable to complete destroy of the physical network provider: " + provider.getProviderName() + ", id: "+ provider.getId(), e);
+                     } catch (ResourceUnavailableException e) {
+                         s_logger.warn("Unable to complete destroy of the physical network provider: " + provider.getProviderName() + ", id: " + provider.getId(), e);
 -                        return false;
 -                    } catch (ConcurrentOperationException e) {
 +                return false;
 +            } catch (ConcurrentOperationException e) {
-                 s_logger.warn("Unable to complete destroy of the physical network provider: " + provider.getProviderName() + ", id: "+ provider.getId(), e);
+                         s_logger.warn("Unable to complete destroy of the physical network provider: " + provider.getProviderName() + ", id: " + provider.getId(), e);
 -                        return false;
 -                    }
 -                }
 +                return false;
 +            }
 +        }
  
 -                // delete traffic types
 -                _pNTrafficTypeDao.deleteTrafficTypes(physicalNetworkId);
 +        // delete traffic types
 +        _pNTrafficTypeDao.deleteTrafficTypes(physicalNetworkId);
  
                  return _physicalNetworkDao.remove(physicalNetworkId);
              }
@@@ -3037,12 -3021,12 +3026,12 @@@
  
          // Verify guest vlans in the range don't belong to a network of a different account
          for (int i = startVlan; i <= endVlan; i++) {
-             List<DataCenterVnetVO> allocatedVlans = _datacneter_vnet.listAllocatedVnetsInRange(physicalNetwork.getDataCenterId(), physicalNetwork.getId(), startVlan, endVlan);
-             if (allocatedVlans != null && !allocatedVlans.isEmpty()){
+             List<DataCenterVnetVO> allocatedVlans = _datacneterVnet.listAllocatedVnetsInRange(physicalNetwork.getDataCenterId(), physicalNetwork.getId(), startVlan, endVlan);
+             if (allocatedVlans != null && !allocatedVlans.isEmpty()) {
                  for (DataCenterVnetVO allocatedVlan : allocatedVlans) {
 -                    if (allocatedVlan.getAccountId() != vlanOwner.getAccountId()) {
 +                    if (allocatedVlan.getAccountId() !=  vlanOwner.getAccountId()) {
-                         throw new InvalidParameterValueException("Guest vlan from this range " + allocatedVlan.getVnet() + " is allocated to a different account." +
-                                 " Can only dedicate a range which has no allocated vlans or has vlans allocated to the same account ");
+                         throw new InvalidParameterValueException("Guest vlan from this range " + allocatedVlan.getVnet() + " is allocated to a different account."
+                                 + " Can only dedicate a range which has no allocated vlans or has vlans allocated to the same account ");
                      }
                  }
              }
@@@ -3742,12 -3730,27 +3735,27 @@@
          return nsp;
      }
  
+     private PhysicalNetworkServiceProvider addDefaultOvsToPhysicalNetwork(long physicalNetworkId) {
+         PhysicalNetworkServiceProvider nsp = addProviderToPhysicalNetwork(physicalNetworkId, Network.Provider.Ovs.getName(), null, null);
+         NetworkElement networkElement = _networkModel.getElementImplementingProvider(Network.Provider.Ovs.getName());
+         if (networkElement == null) {
+             throw new CloudRuntimeException("Unable to find the Network Element implementing the Ovs Provider");
+         }
+         OvsProviderVO element = _ovsProviderDao.findByNspId(nsp.getId());
+         if (element != null) {
+             s_logger.debug("There is already a Ovs element with service provider id " + nsp.getId());
+             return nsp;
+         }
+         element = new OvsProviderVO(nsp.getId());
+         _ovsProviderDao.persist(element);
+         return nsp;
+     }
+ 
      protected PhysicalNetworkServiceProvider addDefaultVpcVirtualRouterToPhysicalNetwork(long physicalNetworkId) {
  
-         PhysicalNetworkServiceProvider nsp = addProviderToPhysicalNetwork(physicalNetworkId,
-                 Network.Provider.VPCVirtualRouter.getName(), null, null);
+         PhysicalNetworkServiceProvider nsp = addProviderToPhysicalNetwork(physicalNetworkId, Network.Provider.VPCVirtualRouter.getName(), null, null);
  
 -        NetworkElement networkElement = _networkModel.getElementImplementingProvider(Network.Provider.VPCVirtualRouter.getName());
 +        NetworkElement networkElement =  _networkModel.getElementImplementingProvider(Network.Provider.VPCVirtualRouter.getName());
          if (networkElement == null) {
              throw new CloudRuntimeException("Unable to find the Network Element implementing the VPCVirtualRouter Provider");
          }
@@@ -3757,14 -3760,12 +3765,12 @@@
  
          return nsp;
      }
-     
-     
+ 
      protected PhysicalNetworkServiceProvider addDefaultInternalLbProviderToPhysicalNetwork(long physicalNetworkId) {
  
-         PhysicalNetworkServiceProvider nsp = addProviderToPhysicalNetwork(physicalNetworkId,
-                 Network.Provider.InternalLbVm.getName(), null, null);
-  
+         PhysicalNetworkServiceProvider nsp = addProviderToPhysicalNetwork(physicalNetworkId, Network.Provider.InternalLbVm.getName(), null, null);
+ 
 -        NetworkElement networkElement = _networkModel.getElementImplementingProvider(Network.Provider.InternalLbVm.getName());
 +        NetworkElement networkElement =  _networkModel.getElementImplementingProvider(Network.Provider.InternalLbVm.getName());
          if (networkElement == null) {
              throw new CloudRuntimeException("Unable to find the Network Element implementing the " + Network.Provider.InternalLbVm.getName() + " Provider");
          }
@@@ -3788,13 -3786,13 +3791,13 @@@
          PhysicalNetworkVO pvo = _physicalNetworkDao.findById(physicalNetworkId);
          DataCenterVO dvo = _dcDao.findById(pvo.getDataCenterId());
          if (dvo.getNetworkType() == NetworkType.Basic) {
 -
 -            Provider provider = Network.Provider.getProvider("BaremetalDhcpProvider");
 -            if (provider == null) {
 +
 +            Provider provider = Network.Provider.getProvider("BaremetalDhcpProvider");
 +            if (provider == null) {
                  // baremetal is not loaded
                  return null;
 -            }
 +            }
-             
+ 
              addProviderToPhysicalNetwork(physicalNetworkId, "BaremetalDhcpProvider", null, null);
              addProviderToPhysicalNetwork(physicalNetworkId, "BaremetalPxeProvider", null, null);
              addProviderToPhysicalNetwork(physicalNetworkId, "BaremetalUserdataProvider", null, null);
@@@ -3859,11 -3853,11 +3858,11 @@@
  
      }
  
- 
-     @Override @DB
-     public Network createPrivateNetwork(final String networkName, final String displayText, long physicalNetworkId,
-             String broadcastUriString, final String startIp, String endIp, final String gateway, String netmask, final long networkOwnerId, final Long vpcId, final Boolean sourceNat, final Long networkOfferingId)
+     @Override
+     @DB
+     public Network createPrivateNetwork(final String networkName, final String displayText, long physicalNetworkId, String broadcastUriString, final String startIp, String endIp,
+             final String gateway, String netmask, final long networkOwnerId, final Long vpcId, final Boolean sourceNat, final Long networkOfferingId)
 -            throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException {
 +                    throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException {
  
          final Account owner = _accountMgr.getAccount(networkOwnerId);
  
@@@ -3919,49 -3909,48 +3914,48 @@@
  
          final NetworkOfferingVO ntwkOffFinal = ntwkOff;
          try {
-             return Transaction.execute(new TransactionCallbackWithException<Network,Exception>() {
+             return Transaction.execute(new TransactionCallbackWithException<Network, Exception>() {
                  @Override
                  public Network doInTransaction(TransactionStatus status) throws ResourceAllocationException, InsufficientCapacityException {
 -                    //lock datacenter as we need to get mac address seq from there
 -                    DataCenterVO dc = _dcDao.lockRow(pNtwk.getDataCenterId(), true);
 +        //lock datacenter as we need to get mac address seq from there
 +        DataCenterVO dc = _dcDao.lockRow(pNtwk.getDataCenterId(), true);
  
 -                    //check if we need to create guest network
 +        //check if we need to create guest network
-         Network privateNetwork = _networksDao.getPrivateNetwork(uriString, cidr,
-                             networkOwnerId, pNtwk.getDataCenterId(), networkOfferingId);
+                     Network privateNetwork = _networksDao.getPrivateNetwork(uriString, cidr, networkOwnerId, pNtwk.getDataCenterId(), networkOfferingId);
 -                    if (privateNetwork == null) {
 -                        //create Guest network
 +        if (privateNetwork == null) {
 +            //create Guest network
-                         privateNetwork = _networkMgr.createGuestNetwork(ntwkOffFinal.getId(), networkName, displayText, gateway, cidr, uriString,
-                     null, owner, null, pNtwk, pNtwk.getDataCenterId(), ACLType.Account, null, vpcId, null, null, true, null);
+                         privateNetwork = _networkMgr.createGuestNetwork(ntwkOffFinal.getId(), networkName, displayText, gateway, cidr, uriString, null, owner, null, pNtwk,
+                                 pNtwk.getDataCenterId(), ACLType.Account, null, vpcId, null, null, true, null);
 -                        s_logger.debug("Created private network " + privateNetwork);
 -                    } else {
 -                        s_logger.debug("Private network already exists: " + privateNetwork);
 -                        //Do not allow multiple private gateways with same Vlan within a VPC
 +            s_logger.debug("Created private network " + privateNetwork);
 +        } else {
 +            s_logger.debug("Private network already exists: " + privateNetwork);
 +            //Do not allow multiple private gateways with same Vlan within a VPC
-             if(vpcId.equals(privateNetwork.getVpcId())){
-                 throw new InvalidParameterValueException("Private network for the vlan: " + uriString + " and cidr  "+ cidr +"  already exists " +
-                         "for Vpc "+vpcId+" in zone " + _entityMgr.findById(DataCenter.class, pNtwk.getDataCenterId()).getName());
+                         if (vpcId.equals(privateNetwork.getVpcId())) {
+                             throw new InvalidParameterValueException("Private network for the vlan: " + uriString + " and cidr  " + cidr + "  already exists " + "for Vpc " + vpcId
+                                     + " in zone " + _entityMgr.findById(DataCenter.class, pNtwk.getDataCenterId()).getName());
 -                        }
 -                    }
 +            }
 +        }
  
 -                    //add entry to private_ip_address table
 -                    PrivateIpVO privateIp = _privateIpDao.findByIpAndSourceNetworkIdAndVpcId(privateNetwork.getId(), startIp, vpcId);
 -                    if (privateIp != null) {
 +        //add entry to private_ip_address table
 +        PrivateIpVO privateIp = _privateIpDao.findByIpAndSourceNetworkIdAndVpcId(privateNetwork.getId(), startIp, vpcId);
 +        if (privateIp != null) {
-             throw new InvalidParameterValueException("Private ip address " + startIp + " already used for private gateway" +
-                     " in zone " + _entityMgr.findById(DataCenter.class, pNtwk.getDataCenterId()).getName());
+                         throw new InvalidParameterValueException("Private ip address " + startIp + " already used for private gateway" + " in zone "
+                                 + _entityMgr.findById(DataCenter.class, pNtwk.getDataCenterId()).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(startIp, privateNetwork.getId(), nextMac, vpcId, sourceNat);
 -                    _privateIpDao.persist(privateIp);
 +        privateIp = new PrivateIpVO(startIp, privateNetwork.getId(), nextMac, vpcId, sourceNat);
 +        _privateIpDao.persist(privateIp);
  
 -                    _dcDao.update(dc.getId(), dc);
 +        _dcDao.update(dc.getId(), dc);
  
 -                    s_logger.debug("Private network " + privateNetwork + " is created");
 +        s_logger.debug("Private network " + privateNetwork + " is created");
  
 -                    return privateNetwork;
 -                }
 +        return privateNetwork;
 +    }
              });
          } catch (Exception e) {
              ExceptionUtil.rethrowRuntime(e);
@@@ -3991,17 -3979,18 +3984,18 @@@
      public List<? extends Nic> listNics(ListNicsCmd cmd) {
          Account caller = CallContext.current().getCallingAccount();
          Long nicId = cmd.getNicId();
-         Long vmId = cmd.getVmId();
+         long vmId = cmd.getVmId();
+         Long networkId = cmd.getNetworkId();
  
 -        UserVmVO userVm = _userVmDao.findById(vmId);
 +        UserVmVO  userVm = _userVmDao.findById(vmId);
  
          if (userVm == null) {
 -            InvalidParameterValueException ex = new InvalidParameterValueException("Virtual mahine id does not exist");
 +                InvalidParameterValueException ex = new InvalidParameterValueException("Virtual mahine id does not exist");
-                 ex.addProxyObject(vmId.toString(), "vmId");
+             ex.addProxyObject(Long.valueOf(vmId).toString(), "vmId");
 -            throw ex;
 -        }
 +                throw ex;
 +            }
          _accountMgr.checkAccess(caller, null, true, userVm);
-         return _networkMgr.listVmNics(vmId, nicId);
+         return _networkMgr.listVmNics(vmId, nicId, networkId);
      }
  
      public List<NetworkGuru> getNetworkGurus() {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/server/src/com/cloud/network/as/AutoScaleManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/network/as/AutoScaleManagerImpl.java
index d32d31c,0751b69..367b8e6
--- a/server/src/com/cloud/network/as/AutoScaleManagerImpl.java
+++ b/server/src/com/cloud/network/as/AutoScaleManagerImpl.java
@@@ -25,14 -30,12 +30,17 @@@ import java.util.concurrent.TimeUnit
  import javax.ejb.Local;
  import javax.inject.Inject;
  
 +import org.apache.log4j.Logger;
 +
 +import com.google.gson.Gson;
 +import com.google.gson.reflect.TypeToken;
 +
  import org.apache.cloudstack.acl.ControlledEntity;
  import org.apache.cloudstack.api.ApiConstants;
+ import org.apache.cloudstack.api.ApiErrorCode;
+ import org.apache.cloudstack.api.BaseCmd.HTTPMethod;
  import org.apache.cloudstack.api.BaseListAccountResourcesCmd;
+ import org.apache.cloudstack.api.ServerApiException;
  import org.apache.cloudstack.api.command.admin.autoscale.CreateCounterCmd;
  import org.apache.cloudstack.api.command.user.autoscale.CreateAutoScalePolicyCmd;
  import org.apache.cloudstack.api.command.user.autoscale.CreateAutoScaleVmGroupCmd;
@@@ -100,10 -116,15 +120,13 @@@ import com.cloud.utils.db.Transaction
  import com.cloud.utils.db.TransactionCallback;
  import com.cloud.utils.db.TransactionStatus;
  import com.cloud.utils.net.NetUtils;
+ import com.cloud.vm.UserVmManager;
+ import com.cloud.vm.UserVmService;
 -import com.google.gson.Gson;
 -import com.google.gson.reflect.TypeToken;
  
- @Local(value = { AutoScaleService.class, AutoScaleManager.class })
+ @Local(value = {AutoScaleService.class, AutoScaleManager.class})
  public class AutoScaleManagerImpl<Type> extends ManagerBase implements AutoScaleManager, AutoScaleService {
      private static final Logger s_logger = Logger.getLogger(AutoScaleManagerImpl.class);
+     private ScheduledExecutorService _executor = Executors.newScheduledThreadPool(1);
  
      @Inject
      EntityManager _entityMgr;
@@@ -596,10 -619,9 +627,9 @@@
              return searchBuilder;
          }
  
-         public SearchCriteria<VO> buildSearchCriteria()
-         {
+         public SearchCriteria<VO> buildSearchCriteria() {
              searchCriteria = searchBuilder.create();
 -            _accountMgr.buildACLSearchCriteria(searchCriteria, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
 +            _accountMgr.buildACLSearchCriteria(searchCriteria, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria);
              return searchCriteria;
          }
  

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/server/src/com/cloud/network/firewall/FirewallManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/network/firewall/FirewallManagerImpl.java
index 8cb4574,448abe3..a260863
--- a/server/src/com/cloud/network/firewall/FirewallManagerImpl.java
+++ b/server/src/com/cloud/network/firewall/FirewallManagerImpl.java
@@@ -179,29 -177,27 +177,27 @@@ public class FirewallManagerImpl extend
      @Override
      @ActionEvent(eventType = EventTypes.EVENT_FIREWALL_OPEN, eventDescription = "creating firewall rule", create = true)
      public FirewallRule createIngressFirewallRule(FirewallRule rule) throws NetworkRuleConflictException {
 -        Account caller = CallContext.current().getCallingAccount();
 +         Account caller = CallContext.current().getCallingAccount();
          Long sourceIpAddressId = rule.getSourceIpAddressId();
-  
-         return createFirewallRule(sourceIpAddressId, caller, rule.getXid(), rule.getSourcePortStart(),
-                  rule.getSourcePortEnd(), rule.getProtocol(), rule.getSourceCidrList(), rule.getIcmpCode(),
-                 rule.getIcmpType(), null, rule.getType(), rule.getNetworkId(), rule.getTrafficType());
+ 
+         return createFirewallRule(sourceIpAddressId, caller, rule.getXid(), rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol(),
+             rule.getSourceCidrList(), rule.getIcmpCode(), rule.getIcmpType(), null, rule.getType(), rule.getNetworkId(), rule.getTrafficType());
      }
  
      @DB
-     protected FirewallRule createFirewallRule(final Long ipAddrId, Account caller, final String xId, final Integer portStart,
-             final Integer portEnd, final String protocol, final List<String> sourceCidrList, final Integer icmpCode, final Integer icmpType,
-             final Long relatedRuleId, final FirewallRule.FirewallRuleType type, final Long networkId, final FirewallRule.TrafficType trafficType) throws NetworkRuleConflictException {
+     protected FirewallRule createFirewallRule(final Long ipAddrId, Account caller, final String xId, final Integer portStart, final Integer portEnd,
+         final String protocol, final List<String> sourceCidrList, final Integer icmpCode, final Integer icmpType, final Long relatedRuleId,
+         final FirewallRule.FirewallRuleType type, final Long networkId, final FirewallRule.TrafficType trafficType) throws NetworkRuleConflictException {
  
          IPAddressVO ipAddress = null;
-         if (ipAddrId != null){
+         if (ipAddrId != null) {
              // this for ingress firewall rule, for egress id is null
 -            ipAddress = _ipAddressDao.findById(ipAddrId);
 -            // Validate ip address
 -            if (ipAddress == null && type == FirewallRule.FirewallRuleType.User) {
 +             ipAddress = _ipAddressDao.findById(ipAddrId);
 +        // Validate ip address
 +        if (ipAddress == null && type == FirewallRule.FirewallRuleType.User) {
-               throw new InvalidParameterValueException("Unable to create firewall rule; " +
-                     "couldn't locate IP address by id in the system");
+                 throw new InvalidParameterValueException("Unable to create firewall rule; " + "couldn't locate IP address by id in the system");
 -            }
 -            _networkModel.checkIpForService(ipAddress, Service.Firewall, null);
 +        }
 +        _networkModel.checkIpForService(ipAddress, Service.Firewall, null);
          }
  
          validateFirewallRule(caller, ipAddress, portStart, portEnd, protocol, Purpose.Firewall, type, networkId, trafficType);
@@@ -231,24 -227,25 +227,25 @@@
  
          final Long accountIdFinal = accountId;
          final Long domainIdFinal = domainId;
-         return Transaction.execute(new TransactionCallbackWithException<FirewallRuleVO,NetworkRuleConflictException>() {
+         return Transaction.execute(new TransactionCallbackWithException<FirewallRuleVO, NetworkRuleConflictException>() {
              @Override
              public FirewallRuleVO doInTransaction(TransactionStatus status) throws NetworkRuleConflictException {
-         FirewallRuleVO newRule = new FirewallRuleVO(xId, ipAddrId, portStart, portEnd, protocol.toLowerCase(), networkId,
-                         accountIdFinal, domainIdFinal, Purpose.Firewall, sourceCidrList, icmpCode, icmpType, relatedRuleId, trafficType);
+                 FirewallRuleVO newRule =
+                     new FirewallRuleVO(xId, ipAddrId, portStart, portEnd, protocol.toLowerCase(), networkId, accountIdFinal, domainIdFinal, Purpose.Firewall,
+                         sourceCidrList, icmpCode, icmpType, relatedRuleId, trafficType);
 -                newRule.setType(type);
 -                newRule = _firewallDao.persist(newRule);
 +        newRule.setType(type);
 +        newRule = _firewallDao.persist(newRule);
  
 -                if (type == FirewallRuleType.User)
 -                    detectRulesConflict(newRule);
 +        if (type == FirewallRuleType.User)
 +            detectRulesConflict(newRule);
  
 -                if (!_firewallDao.setStateToAdd(newRule)) {
 -                    throw new CloudRuntimeException("Unable to update the state to add for " + newRule);
 -                }
 -                CallContext.current().setEventDetails("Rule Id: " + newRule.getId());
 +        if (!_firewallDao.setStateToAdd(newRule)) {
 +            throw new CloudRuntimeException("Unable to update the state to add for " + newRule);
 +        }
 +        CallContext.current().setEventDetails("Rule Id: " + newRule.getId());
  
 -                return newRule;
 -            }
 +        return newRule;
 +    }
          });
      }
  
@@@ -284,18 -281,13 +281,13 @@@
  
          sb.and("id", sb.entity().getId(), Op.EQ);
          sb.and("trafficType", sb.entity().getTrafficType(), Op.EQ);
-         if (cmd instanceof ListEgressFirewallRulesCmd ) {
-             networkId =((ListEgressFirewallRulesCmd)cmd).getNetworkId();
 -        sb.and("networkId", sb.entity().getNetworkId(), Op.EQ);
 +            sb.and("networkId", sb.entity().getNetworkId(), Op.EQ);
-         } else {
          sb.and("ip", sb.entity().getSourceIpAddressId(), Op.EQ);
-         }
          sb.and("purpose", sb.entity().getPurpose(), Op.EQ);
  
- 
          if (tags != null && !tags.isEmpty()) {
              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(), SearchCriteria.Op.EQ);
                  tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ);
                  tagSearch.cp();
@@@ -324,11 -316,11 +316,11 @@@
  
          if (ipId != null) {
              sc.setParameters("ip", ipId);
-         } else if (cmd instanceof ListEgressFirewallRulesCmd) {
+         }
+ 
 -        if (networkId != null) {
 -            sc.setParameters("networkId", networkId);
 -        }
 +            if (networkId != null) {
 +                sc.setParameters("networkId", networkId);
 +            }
-         }
  
          sc.setParameters("purpose", Purpose.Firewall);
          sc.setParameters("trafficType", trafficType);
@@@ -340,10 -332,10 +332,10 @@@
      @Override
      public void detectRulesConflict(FirewallRule newRule) throws NetworkRuleConflictException {
          List<FirewallRuleVO> rules;
-         if(newRule.getSourceIpAddressId() != null){
+         if (newRule.getSourceIpAddressId() != null) {
 -            rules = _firewallDao.listByIpAndPurposeAndNotRevoked(newRule.getSourceIpAddressId(), null);
 +             rules = _firewallDao.listByIpAndPurposeAndNotRevoked(newRule.getSourceIpAddressId(), null);
-         assert (rules.size() >= 1) : "For network rules, we now always first persist the rule and then check for " +
-         "network conflicts so we should at least have one rule at this point.";
+             assert (rules.size() >= 1) : "For network rules, we now always first persist the rule and then check for "
+                 + "network conflicts so we should at least have one rule at this point.";
          } else {
              // fetches only firewall egress rules.
              rules = _firewallDao.listByNetworkPurposeTrafficTypeAndNotRevoked(newRule.getNetworkId(), Purpose.Firewall, newRule.getTrafficType());
@@@ -356,9 -347,9 +347,9 @@@
                  continue; // Skips my own rule.
              }
  
-             boolean oneOfRulesIsFirewall = ((rule.getPurpose() == Purpose.Firewall || newRule.getPurpose() == Purpose.Firewall)
-                     && ((newRule.getPurpose() != rule.getPurpose()) || (!newRule.getProtocol()
+             boolean oneOfRulesIsFirewall =
+                 ((rule.getPurpose() == Purpose.Firewall || newRule.getPurpose() == Purpose.Firewall) && ((newRule.getPurpose() != rule.getPurpose()) || (!newRule.getProtocol()
 -                    .equalsIgnoreCase(rule.getProtocol()))));
 +                            .equalsIgnoreCase(rule.getProtocol()))));
  
              // if both rules are firewall and their cidrs are different, we can skip port ranges verification
              boolean bothRulesFirewall = (rule.getPurpose() == newRule.getPurpose() && rule.getPurpose() == Purpose.Firewall);
@@@ -457,9 -446,9 +446,9 @@@
              return;
          }
  
-         if (ipAddress != null){
+         if (ipAddress != null) {
              if (ipAddress.getAssociatedWithNetworkId() == null) {
 -                throw new InvalidParameterValueException("Unable to create firewall rule ; ip with specified id is not associated with any network");
 +                    throw new InvalidParameterValueException("Unable to create firewall rule ; ip with specified id is not associated with any network");
              } else {
                  networkId = ipAddress.getAssociatedWithNetworkId();
              }
@@@ -559,52 -547,51 +547,51 @@@
      }
  
      @Override
-     public  boolean applyRules(Network network, Purpose purpose, List<? extends FirewallRule> rules)
-             throws ResourceUnavailableException {
+     public boolean applyRules(Network network, Purpose purpose, List<? extends FirewallRule> rules) throws ResourceUnavailableException {
          boolean handled = false;
-         switch (purpose){
+         switch (purpose) {
          /* StaticNatRule would be applied by Firewall provider, since the incompatible of two object */
 -            case StaticNat:
 -            case Firewall:
 +        case StaticNat:
 +        case Firewall:
-             for (FirewallServiceProvider fwElement: _firewallElements) {
+                 for (FirewallServiceProvider fwElement : _firewallElements) {
 -                    Network.Provider provider = fwElement.getProvider();
 -                    boolean isFwProvider = _networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.Firewall, provider);
 -                    if (!isFwProvider) {
 -                        continue;
 -                    }
 -                    handled = fwElement.applyFWRules(network, rules);
 -                    if (handled)
 -                        break;
 +                Network.Provider provider = fwElement.getProvider();
 +                boolean  isFwProvider = _networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.Firewall, provider);
 +                if (!isFwProvider) {
 +                    continue;
                  }
 -                break;
 -            case PortForwarding:
 +                handled = fwElement.applyFWRules(network, rules);
 +                if (handled)
 +                    break;
 +            }
 +            break;
 +        case PortForwarding:
-             for (PortForwardingServiceProvider element: _pfElements) {
+                 for (PortForwardingServiceProvider element : _pfElements) {
 -                    Network.Provider provider = element.getProvider();
 -                    boolean isPfProvider = _networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.PortForwarding, provider);
 -                    if (!isPfProvider) {
 -                        continue;
 -                    }
 -                    handled = element.applyPFRules(network, (List<PortForwardingRule>)rules);
 -                    if (handled)
 -                        break;
 +                Network.Provider provider = element.getProvider();
 +                boolean  isPfProvider = _networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.PortForwarding, provider);
 +                if (!isPfProvider) {
 +                    continue;
                  }
-                 handled = element.applyPFRules(network, (List<PortForwardingRule>) rules);
 -                break;
++                    handled = element.applyPFRules(network, (List<PortForwardingRule>)rules);
 +                if (handled)
 +                    break;
 +            }
 +            break;
- /*        case NetworkACL:
+             /*        case NetworkACL:
 -                        for (NetworkACLServiceProvider element: _networkAclElements) {
 -                            Network.Provider provider = element.getProvider();
 -                            boolean  isAclProvider = _networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.NetworkACL, provider);
 -                            if (!isAclProvider) {
 -                                continue;
 -                            }
 -                            handled = element.applyNetworkACLs(network, rules);
 -                            if (handled)
 -                                break;
 -                        }
 -                        break;*/
 -            default:
 +            for (NetworkACLServiceProvider element: _networkAclElements) {
 +                Network.Provider provider = element.getProvider();
 +                boolean  isAclProvider = _networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.NetworkACL, provider);
 +                if (!isAclProvider) {
 +                    continue;
 +                }
 +                handled = element.applyNetworkACLs(network, rules);
 +                if (handled)
 +                    break;
 +            }
 +            break;*/
 +        default:
-             assert(false): "Unexpected fall through in applying rules to the network elements";
+                 assert (false) : "Unexpected fall through in applying rules to the network elements";
 -                s_logger.error("FirewallManager cannot process rules of type " + purpose);
 -                throw new CloudRuntimeException("FirewallManager cannot process rules of type " + purpose);
 +            s_logger.error("FirewallManager cannot process rules of type " + purpose);
 +            throw new CloudRuntimeException("FirewallManager cannot process rules of type " + purpose);
          }
          return handled;
      }
@@@ -623,10 -610,9 +610,9 @@@
      }
  
      @Override
-     public boolean applyEgressFirewallRules (FirewallRule rule, Account caller) throws ResourceUnavailableException {
+     public boolean applyEgressFirewallRules(FirewallRule rule, Account caller) throws ResourceUnavailableException {
 -        List<FirewallRuleVO> rules = _firewallDao.listByNetworkPurposeTrafficType(rule.getNetworkId(), Purpose.Firewall, FirewallRule.TrafficType.Egress);
 -        return applyFirewallRules(rules, false, caller);
 +                List<FirewallRuleVO> rules = _firewallDao.listByNetworkPurposeTrafficType(rule.getNetworkId(), Purpose.Firewall, FirewallRule.TrafficType.Egress);
-                 applyDefaultEgressFirewallRule(rule.getNetworkId(), true);
 +                return applyFirewallRules(rules, false, caller);
      }
  
      @Override
@@@ -708,12 -692,12 +692,12 @@@
  
          if (apply) {
              // ingress firewall rule
-             if (rule.getSourceIpAddressId() != null){
+             if (rule.getSourceIpAddressId() != null) {
                  //feteches ingress firewall, ingress firewall rules associated with the ip
 -                List<FirewallRuleVO> rules = _firewallDao.listByIpAndPurpose(rule.getSourceIpAddressId(), Purpose.Firewall);
 -                return applyFirewallRules(rules, false, caller);
 +            List<FirewallRuleVO> rules = _firewallDao.listByIpAndPurpose(rule.getSourceIpAddressId(), Purpose.Firewall);
 +            return applyFirewallRules(rules, false, caller);
                  //egress firewall rule
-             } else if ( networkId != null){
+             } else if (networkId != null) {
                  List<FirewallRuleVO> rules = _firewallDao.listByNetworkPurposeTrafficType(rule.getNetworkId(), Purpose.Firewall, FirewallRule.TrafficType.Egress);
                  return applyFirewallRules(rules, false, caller);
              }
@@@ -742,24 -726,24 +726,24 @@@
          Transaction.execute(new TransactionCallbackNoReturn() {
              @Override
              public void doInTransactionWithoutResult(TransactionStatus status) {
 -                boolean generateUsageEvent = false;
 +        boolean generateUsageEvent = false;
  
 -                if (rule.getState() == State.Staged) {
 -                    if (s_logger.isDebugEnabled()) {
 -                        s_logger.debug("Found a rule that is still in stage state so just removing it: " + rule);
 -                    }
 -                    removeRule(rule);
 -                    generateUsageEvent = true;
 -                } else if (rule.getState() == State.Add || rule.getState() == State.Active) {
 -                    rule.setState(State.Revoke);
 -                    _firewallDao.update(rule.getId(), rule);
 -                    generateUsageEvent = true;
 -                }
 +        if (rule.getState() == State.Staged) {
 +            if (s_logger.isDebugEnabled()) {
 +                s_logger.debug("Found a rule that is still in stage state so just removing it: " + rule);
 +            }
 +            removeRule(rule);
 +            generateUsageEvent = true;
 +        } else if (rule.getState() == State.Add || rule.getState() == State.Active) {
 +            rule.setState(State.Revoke);
 +            _firewallDao.update(rule.getId(), rule);
 +            generateUsageEvent = true;
 +        }
  
 -                if (generateUsageEvent && needUsageEvent) {
 +        if (generateUsageEvent && needUsageEvent) {
-             UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NET_RULE_DELETE, rule.getAccountId(), 0, rule.getId(),
-                     null, rule.getClass().getName(), rule.getUuid());
+                     UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NET_RULE_DELETE, rule.getAccountId(), 0, rule.getId(), null, rule.getClass().getName(),
+                         rule.getUuid());
 -                }
 +        }
              }
          });
      }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java
index 36c1540,8214274..a0ce19d
--- a/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java
+++ b/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java
@@@ -1406,10 -1498,10 +1498,10 @@@ public class LoadBalancingRulesManagerI
  
      @DB
      @Override
-     public LoadBalancer createPublicLoadBalancer(final String xId, final String name, final String description,
-             final int srcPort, final int destPort, final long sourceIpId, final String protocol, final String algorithm, final boolean openFirewall, final CallContext caller)
+     public LoadBalancer createPublicLoadBalancer(final String xId, final String name, final String description, final int srcPort, final int destPort,
+         final long sourceIpId, final String protocol, final String algorithm, final boolean openFirewall, final CallContext caller, final String lbProtocol)
 -        throws NetworkRuleConflictException {
 +            throws NetworkRuleConflictException {
-         
+ 
          if (!NetUtils.isValidPort(destPort)) {
              throw new InvalidParameterValueException("privatePort is an invalid value: " + destPort);
          }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/server/src/com/cloud/network/rules/RulesManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/network/rules/RulesManagerImpl.java
index 29875e2,69be58f..393db44
--- a/server/src/com/cloud/network/rules/RulesManagerImpl.java
+++ b/server/src/com/cloud/network/rules/RulesManagerImpl.java
@@@ -502,13 -498,12 +498,12 @@@ public class RulesManagerImpl extends M
                          try {
                              ipAddress = _ipAddrMgr.associateIPToGuestNetwork(ipId, networkId, false);
                          } catch (Exception ex) {
-                             s_logger.warn("Failed to associate ip id=" + ipId + " to VPC network id=" + networkId + " as " +
-                                     "a part of enable static nat");
+                             s_logger.warn("Failed to associate ip id=" + ipId + " to VPC network id=" + networkId + " as " + "a part of enable static nat");
                              return false;
                          }
 -                    } else if (ipAddress.isPortable()) {
 +                    }  else if (ipAddress.isPortable()) {
-                         s_logger.info("Portable IP " + ipAddress.getUuid() + " is not associated with the network yet "
-                                 + " so associate IP with the network " + networkId);
+                         s_logger.info("Portable IP " + ipAddress.getUuid() + " is not associated with the network yet " + " so associate IP with the network " +
+                             networkId);
                          try {
                              // check if StaticNat service is enabled in the network
                              _networkModel.checkIpForService(ipAddress, Service.StaticNat, networkId);
@@@ -663,11 -655,12 +655,12 @@@
  
              // If there is public ip address already associated with the vm, throw an exception
              if (!reassignStaticNat) {
-                 throw new InvalidParameterValueException("Failed to enable static nat for the ip address id=" + ipAddress.getId() + " as vm id=" + vmId + " is already associated with ip id=" + oldIP.getId());
+                 throw new InvalidParameterValueException("Failed to enable static nat for the ip address id=" + ipAddress.getId() + " as vm id=" + vmId +
+                     " is already associated with ip id=" + oldIP.getId());
              }
 -            // unassign old static nat rule
 -            s_logger.debug("Disassociating static nat for ip " + oldIP);
 -            if (!disableStaticNat(oldIP.getId(), caller, callerUserId, true)) {
 +        // unassign old static nat rule
 +        s_logger.debug("Disassociating static nat for ip " + oldIP);
 +        if (!disableStaticNat(oldIP.getId(), caller, callerUserId, true)) {
                  throw new CloudRuntimeException("Failed to disable old static nat rule for vm id=" + vmId + " and ip " + oldIP);
              }
          }
@@@ -784,11 -775,10 +775,12 @@@
          Long ipId = cmd.getIpAddressId();
          Long id = cmd.getId();
          Map<String, String> tags = cmd.getTags();
+         Long networkId = cmd.getNetworkId();
  
          Account caller = CallContext.current().getCallingAccount();
 +        List<Long> permittedDomains = new ArrayList<Long>();
          List<Long> permittedAccounts = new ArrayList<Long>();
 +        List<Long> permittedResources = new ArrayList<Long>();
  
          if (ipId != null) {
              IPAddressVO ipAddressVO = _ipAddressDao.findById(ipId);
@@@ -824,9 -816,8 +817,8 @@@
              sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER);
          }
  
- 
          SearchCriteria<PortForwardingRuleVO> sc = sb.create();
 -        _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
 +        _accountMgr.buildACLSearchCriteria(sc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria);
  
          if (id != null) {
              sc.setParameters("id", id);
@@@ -993,11 -987,10 +988,12 @@@
      }
  
      @Override
-     public Pair<List<? extends FirewallRule>, Integer> searchStaticNatRules(Long ipId, Long id, Long vmId, Long start, Long size, String accountName, Long domainId, Long projectId, boolean isRecursive, boolean listAll) {
+     public Pair<List<? extends FirewallRule>, Integer> searchStaticNatRules(Long ipId, Long id, Long vmId, Long start, Long size, String accountName, Long domainId,
+         Long projectId, boolean isRecursive, boolean listAll) {
          Account caller = CallContext.current().getCallingAccount();
 +        List<Long> permittedDomains = new ArrayList<Long>();
          List<Long> permittedAccounts = new ArrayList<Long>();
 +        List<Long> permittedResources = new ArrayList<Long>();
  
          if (ipId != null) {
              IPAddressVO ipAddressVO = _ipAddressDao.findById(ipId);