incubator-cloudstack-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ahu...@apache.org
Subject [35/51] [abbrv] All merge conflicts resolved
Date Sat, 19 Jan 2013 00:00:12 GMT
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/10d9c019/server/src/com/cloud/network/NetworkManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/network/NetworkManagerImpl.java
index 2a4b27e,bb60dcf..706d332
--- a/server/src/com/cloud/network/NetworkManagerImpl.java
+++ b/server/src/com/cloud/network/NetworkManagerImpl.java
@@@ -38,20 -33,22 +33,24 @@@ import java.util.concurrent.ScheduledEx
  import java.util.concurrent.TimeUnit;
  
  import javax.ejb.Local;
 +import javax.inject.Inject;
  import javax.naming.ConfigurationException;
  
- import com.cloud.utils.db.*;
- import org.apache.cloudstack.api.command.admin.usage.ListTrafficTypeImplementorsCmd;
- import org.apache.cloudstack.api.command.user.network.CreateNetworkCmd;
- import org.apache.cloudstack.api.command.user.network.RestartNetworkCmd;
- import org.apache.log4j.Logger;
- 
  import org.apache.cloudstack.acl.ControlledEntity.ACLType;
  import org.apache.cloudstack.acl.SecurityChecker.AccessType;
+ import org.apache.log4j.Logger;
++import org.springframework.stereotype.Component;
+ 
  import com.cloud.agent.AgentManager;
  import com.cloud.agent.Listener;
- import com.cloud.agent.api.*;
+ import com.cloud.agent.api.AgentControlAnswer;
+ import com.cloud.agent.api.AgentControlCommand;
+ import com.cloud.agent.api.Answer;
+ import com.cloud.agent.api.CheckNetworkAnswer;
+ import com.cloud.agent.api.CheckNetworkCommand;
+ import com.cloud.agent.api.Command;
+ import com.cloud.agent.api.StartupCommand;
+ import com.cloud.agent.api.StartupRoutingCommand;
  import com.cloud.agent.api.to.NicTO;
  import com.cloud.alert.AlertManager;
  import com.cloud.api.ApiDBUtils;
@@@ -96,11 -102,22 +104,23 @@@ import com.cloud.network.Networks.Addre
  import com.cloud.network.Networks.BroadcastDomainType;
  import com.cloud.network.Networks.IsolationType;
  import com.cloud.network.Networks.TrafficType;
- import com.cloud.network.PhysicalNetwork.BroadcastDomainRange;
- import com.cloud.network.VirtualRouterProvider.VirtualRouterProviderType;
  import com.cloud.network.addr.PublicIp;
- import com.cloud.network.dao.*;
- import com.cloud.network.element.*;
+ import com.cloud.network.dao.FirewallRulesDao;
+ import com.cloud.network.dao.IPAddressDao;
+ import com.cloud.network.dao.LoadBalancerDao;
+ import com.cloud.network.dao.NetworkDao;
++import com.cloud.network.dao.NetworkDomainDao;
+ import com.cloud.network.dao.NetworkServiceMapDao;
+ import com.cloud.network.dao.PhysicalNetworkDao;
+ import com.cloud.network.dao.PhysicalNetworkServiceProviderDao;
+ import com.cloud.network.dao.PhysicalNetworkTrafficTypeDao;
+ import com.cloud.network.dao.PhysicalNetworkTrafficTypeVO;
+ import com.cloud.network.element.DhcpServiceProvider;
+ import com.cloud.network.element.IpDeployer;
+ import com.cloud.network.element.LoadBalancingServiceProvider;
+ import com.cloud.network.element.NetworkElement;
+ import com.cloud.network.element.StaticNatServiceProvider;
+ import com.cloud.network.element.UserDataServiceProvider;
  import com.cloud.network.guru.NetworkGuru;
  import com.cloud.network.lb.LoadBalancingRule;
  import com.cloud.network.lb.LoadBalancingRule.LbDestination;
@@@ -121,23 -144,25 +147,24 @@@ import com.cloud.offerings.NetworkOffer
  import com.cloud.offerings.dao.NetworkOfferingDao;
  import com.cloud.offerings.dao.NetworkOfferingServiceMapDao;
  import com.cloud.org.Grouping;
- import com.cloud.projects.Project;
- import com.cloud.projects.ProjectManager;
- import com.cloud.server.ResourceTag.TaggedResourceType;
- import com.cloud.tags.ResourceTagVO;
- import com.cloud.tags.dao.ResourceTagDao;
- import com.cloud.user.*;
+ import com.cloud.user.Account;
+ import com.cloud.user.AccountManager;
+ import com.cloud.user.ResourceLimitService;
+ import com.cloud.user.User;
+ import com.cloud.user.UserContext;
  import com.cloud.user.dao.AccountDao;
- import com.cloud.user.dao.UserStatisticsDao;
- import com.cloud.utils.AnnotationHelper;
  import com.cloud.utils.NumbersUtil;
  import com.cloud.utils.Pair;
 -import com.cloud.utils.component.Adapters;
 -import com.cloud.utils.component.Inject;
 +import com.cloud.utils.component.AdapterBase;
- import com.cloud.utils.component.ComponentContext;
  import com.cloud.utils.component.Manager;
  import com.cloud.utils.concurrency.NamedThreadFactory;
+ import com.cloud.utils.db.DB;
+ import com.cloud.utils.db.Filter;
  import com.cloud.utils.db.JoinBuilder.JoinType;
+ import com.cloud.utils.db.SearchBuilder;
+ import com.cloud.utils.db.SearchCriteria;
  import com.cloud.utils.db.SearchCriteria.Op;
+ import com.cloud.utils.db.Transaction;
  import com.cloud.utils.exception.CloudRuntimeException;
  import com.cloud.utils.net.Ip;
  import com.cloud.utils.net.NetUtils;
@@@ -164,10 -184,9 +186,10 @@@ import com.cloud.vm.dao.VMInstanceDao
  /**
   * NetworkManagerImpl implements NetworkManager.
   */
 +@Component
- @Local(value = { NetworkManager.class, NetworkService.class })
- public class NetworkManagerImpl implements NetworkManager, NetworkService, Manager, Listener {
-     private static final Logger s_logger = Logger.getLogger(NetworkManagerImpl.class);
+ @Local(value = { NetworkManager.class})
+ public class NetworkManagerImpl implements NetworkManager, Manager, Listener {
+     static final Logger s_logger = Logger.getLogger(NetworkManagerImpl.class);
  
      String _name;
      @Inject
@@@ -212,15 -227,15 +230,17 @@@
      RemoteAccessVpnService _vpnMgr;
      @Inject
      PodVlanMapDao _podVlanMapDao;
-     
 -    @Inject(adapter = NetworkGuru.class)
 -    Adapters<NetworkGuru> _networkGurus;
 -    @Inject(adapter = NetworkElement.class)
 -    Adapters<NetworkElement> _networkElements;
 -    @Inject(adapter = IpDeployer.class)
 -    Adapters<IpDeployer> _ipDeployers;
 -    @Inject(adapter = DhcpServiceProvider.class)
 -    Adapters<DhcpServiceProvider> _dhcpProviders;
 - 
++
 +    @Inject 
 +    List<NetworkGuru> _networkGurus;
 +
 +    @Inject 
 +    List<NetworkElement> _networkElements;
-     
-     @Inject
-     NetworkDomainDao _networkDomainDao;
++
++    @Inject NetworkDomainDao _networkDomainDao;
++    @Inject List<IpDeployer> _ipDeployers;
++    @Inject List<DhcpServiceProvider> _dhcpProviders;
++
      @Inject
      VMInstanceDao _vmDao;
      @Inject
@@@ -228,15 -243,8 +248,8 @@@
      @Inject
      FirewallRulesDao _firewallDao;
      @Inject
-     PortForwardingRulesDao _portForwardingDao;
-     @Inject
      ResourceLimitService _resourceLimitMgr;
-     @Inject
-     DomainRouterDao _routerDao;
-     @Inject
-     DomainManager _domainMgr;
-     @Inject
-     ProjectManager _projectMgr;
 -   
++
      @Inject
      NetworkOfferingServiceMapDao _ntwkOfferingSrvcDao;
      @Inject
@@@ -322,9 -295,9 +300,9 @@@
      }
  
      @DB
 -    public PublicIp fetchNewPublicIp(long dcId, Long podId, Long vlanDbId, Account owner, VlanType vlanUse,
 +    public PublicIp fetchNewPublicIp(long dcId, Long podId, Long vlanDbId, Account owner, VlanType vlanUse, 
              Long guestNetworkId, boolean sourceNat, boolean assign, String requestedIp, boolean isSystem, Long vpcId)
--            throws InsufficientAddressCapacityException {
++                    throws InsufficientAddressCapacityException {
          StringBuilder errorMessage = new StringBuilder("Unable to get ip adress in ");
          Transaction txn = Transaction.currentTxn();
          txn.start();
@@@ -432,9 -405,9 +410,9 @@@
              VlanVO vlan = _vlanDao.findById(addr.getVlanId());
  
              String guestType = vlan.getVlanType().toString();
-             
+ 
 -            UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_NET_IP_ASSIGN, owner.getId(),
 -                    addr.getDataCenterId(), addr.getId(), addr.getAddress().toString(), addr.isSourceNat(), guestType,
 +            UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_NET_IP_ASSIGN, owner.getId(), 
 +                    addr.getDataCenterId(), addr.getId(), addr.getAddress().toString(), addr.isSourceNat(), guestType, 
                      addr.getSystem());
              _usageEventDao.persist(usageEvent);
              // don't increment resource count for direct ip addresses
@@@ -446,9 -419,9 +424,9 @@@
          txn.commit();
      }
  
-     
+ 
      @Override
 -    public PublicIp assignSourceNatIpAddressToGuestNetwork(Account owner, Network guestNetwork)
 +    public PublicIp assignSourceNatIpAddressToGuestNetwork(Account owner, Network guestNetwork) 
              throws InsufficientAddressCapacityException, ConcurrentOperationException {
          assert (guestNetwork.getTrafficType() != null) : "You're asking for a source nat but your network " +
                  "can't participate in source nat.  What do you have to say for yourself?";
@@@ -536,45 -509,7 +514,7 @@@
          }
      }
  
-     /**
-      * Returns the target account for an api command
-      * 
-      * @param accountName
-      *            - non-null if the account name was passed in in the command
-      * @param domainId
-      *            - non-null if the domainId was passed in in the command.
-      * @return
-      */
-     protected Account getAccountForApiCommand(String accountName, Long domainId) {
-         Account account = UserContext.current().getCaller();
- 
-         if (_accountMgr.isAdmin(account.getType())) {
-             // The admin is making the call, determine if it is for someone else or for himself
-             if (domainId != null) {
-                 if ((account != null) && !_domainDao.isChildDomain(account.getDomainId(), domainId)) {
-                     // TBD: Check if call to addProxyObject() needs correction.
-                     PermissionDeniedException ex = new PermissionDeniedException("Invalid domain id given, permission denied");
-                     ex.addProxyObject("domain", domainId, "domainId");
-                     throw ex;
-                 }
-                 if (accountName != null) {
-                     Account userAccount = _accountMgr.getActiveAccountByName(accountName, domainId);
-                     if (userAccount != null) {
-                         account = userAccount;
-                     } else {
-                         // TBD: Check if call to addProxyObject() needs correction.
-                         PermissionDeniedException ex = new PermissionDeniedException("Unable to find account " + accountName + " in specified domain, permission denied");
-                         ex.addProxyObject("domain", domainId, "domainId");
-                         throw ex;
-                     }
-                 }
-             } else {
-                 // the admin is calling the api on his own behalf
-                 return account;
-             }
-         }
-         return account;
-     }
 -    
++
  
      @Override
      public boolean applyIpAssociations(Network network, boolean continueOnError) throws ResourceUnavailableException {
@@@ -611,291 -546,15 +551,15 @@@
          return success;
      }
  
-     private Map<Provider, Set<Service>> getProviderServicesMap(long networkId) {
-         Map<Provider, Set<Service>> map = new HashMap<Provider, Set<Service>>();
-         List<NetworkServiceMapVO> nsms = _ntwkSrvcDao.getServicesInNetwork(networkId);
-         for (NetworkServiceMapVO nsm : nsms) {
-             Set<Service> services = map.get(Provider.getProvider(nsm.getProvider()));
-             if (services == null) {
-                 services = new HashSet<Service>();
-             }
-             services.add(Service.getService(nsm.getService()));
-             map.put(Provider.getProvider(nsm.getProvider()), services);
-         }
-         return map;
-     }
- 
-     private Map<Service, Set<Provider>> getServiceProvidersMap(long networkId) {
-         Map<Service, Set<Provider>> map = new HashMap<Service, Set<Provider>>();
-         List<NetworkServiceMapVO> nsms = _ntwkSrvcDao.getServicesInNetwork(networkId);
-         for (NetworkServiceMapVO nsm : nsms) {
-             Set<Provider> providers = map.get(Service.getService(nsm.getService()));
-             if (providers == null) {
-                 providers = new HashSet<Provider>();
-             }
-             providers.add(Provider.getProvider(nsm.getProvider()));
-             map.put(Service.getService(nsm.getService()), providers);
-         }
-         return map;
-     }
- 
-     /* Get a list of IPs, classify them by service */
-     @Override
-     public Map<PublicIp, Set<Service>> getIpToServices(List<PublicIp> publicIps, boolean rulesRevoked, boolean includingFirewall) {
-         Map<PublicIp, Set<Service>> ipToServices = new HashMap<PublicIp, Set<Service>>();
- 
-         if (publicIps != null && !publicIps.isEmpty()) {
-             Set<Long> networkSNAT = new HashSet<Long>();
-             for (PublicIp ip : publicIps) {
-                 Set<Service> services = ipToServices.get(ip);
-                 if (services == null) {
-                     services = new HashSet<Service>();
-                 }
-                 if (ip.isSourceNat()) {
-                     if (!networkSNAT.contains(ip.getAssociatedWithNetworkId())) {
-                         services.add(Service.SourceNat);
-                         networkSNAT.add(ip.getAssociatedWithNetworkId());
-                     } else {
-                         CloudRuntimeException ex = new CloudRuntimeException("Multiple generic soure NAT IPs provided for network");
-                         // see the IPAddressVO.java class.
-                         ex.addProxyObject("user_ip_address", ip.getAssociatedWithNetworkId(), "networkId");
-                         throw ex;
-                     }
-                 }
-                 ipToServices.put(ip, services);
- 
-                 // if IP in allocating state then it will not have any rules attached so skip IPAssoc to network service
-                 // provider
-                 if (ip.getState() == State.Allocating) {
-                     continue;
-                 }
- 
-                 // check if any active rules are applied on the public IP
-                 Set<Purpose> purposes = getPublicIpPurposeInRules(ip, false, includingFirewall);
-                 // Firewall rules didn't cover static NAT
-                 if (ip.isOneToOneNat() && ip.getAssociatedWithVmId() != null) {
-                     if (purposes == null) {
-                         purposes = new HashSet<Purpose>();
-                     }
-                     purposes.add(Purpose.StaticNat);
-                 }
-                 if (purposes == null || purposes.isEmpty()) {
-                     // since no active rules are there check if any rules are applied on the public IP but are in
- // revoking state
-                     
-                     purposes = getPublicIpPurposeInRules(ip, true, includingFirewall);
-                     if (ip.isOneToOneNat()) {
-                         if (purposes == null) {
-                             purposes = new HashSet<Purpose>();
-                         }
-                         purposes.add(Purpose.StaticNat);
-                     }
-                     if (purposes == null || purposes.isEmpty()) {
-                         // IP is not being used for any purpose so skip IPAssoc to network service provider
-                         continue;
-                     } else {
-                         if (rulesRevoked) {
-                             // no active rules/revoked rules are associated with this public IP, so remove the
- // association with the provider
-                             ip.setState(State.Releasing);
-                         } else {
-                             if (ip.getState() == State.Releasing) {
-                                 // rules are not revoked yet, so don't let the network service provider revoke the IP
- // association
-                                 // mark IP is allocated so that IP association will not be removed from the provider
-                                 ip.setState(State.Allocated);
-                             }
-                         }
-                     }
-                 }
-                 if (purposes.contains(Purpose.StaticNat)) {
-                     services.add(Service.StaticNat);
-                 }
-                 if (purposes.contains(Purpose.LoadBalancing)) {
-                     services.add(Service.Lb);
-                 }
-                 if (purposes.contains(Purpose.PortForwarding)) {
-                     services.add(Service.PortForwarding);
-                 }
-                 if (purposes.contains(Purpose.Vpn)) {
-                     services.add(Service.Vpn);
-                 }
-                 if (purposes.contains(Purpose.Firewall)) {
-                     services.add(Service.Firewall);
-                 }
-                 if (services.isEmpty()) {
-                     continue;
-                 }
-                 ipToServices.put(ip, services);
-             }
-         }
-         return ipToServices;
-     }
- 
-     public boolean canIpUsedForNonConserveService(PublicIp ip, Service service) {
-         // If it's non-conserve mode, then the new ip should not be used by any other services
-         List<PublicIp> ipList = new ArrayList<PublicIp>();
-         ipList.add(ip);
-         Map<PublicIp, Set<Service>> ipToServices = getIpToServices(ipList, false, false);
-         Set<Service> services = ipToServices.get(ip);
-         // Not used currently, safe
-         if (services == null || services.isEmpty()) {
-             return true;
-         }
-         // Since it's non-conserve mode, only one service should used for IP
-         if (services.size() != 1) {
-             throw new InvalidParameterException("There are multiple services used ip " + ip.getAddress() + ".");
-         }
-         if (service != null && !((Service) services.toArray()[0] == service || service.equals(Service.Firewall))) {
-             throw new InvalidParameterException("The IP " + ip.getAddress() + " is already used as " + ((Service) services.toArray()[0]).getName() + " rather than " + service.getName());
-         }
-         return true;
-     }
- 
-     protected boolean canIpsUsedForNonConserve(List<PublicIp> publicIps) {
-         boolean result = true;
-         for (PublicIp ip : publicIps) {
-             result = canIpUsedForNonConserveService(ip, null);
-             if (!result) {
-                 break;
-             }
-         }
-         return result;
-     }
- 
-     public boolean canIpsUseOffering(List<PublicIp> publicIps, long offeringId) {
-         Map<PublicIp, Set<Service>> ipToServices = getIpToServices(publicIps, false, true);
-         Map<Service, Set<Provider>> serviceToProviders = getNetworkOfferingServiceProvidersMap(offeringId);
-         NetworkOfferingVO offering = _networkOfferingDao.findById(offeringId);
-         //For inline mode checking, using firewall provider for LB instead, because public ip would apply on firewall provider
-         if (offering.isInline()) {
-             Provider firewallProvider = null;
-             if (serviceToProviders.containsKey(Service.Firewall)) {
-                 firewallProvider = (Provider)serviceToProviders.get(Service.Firewall).toArray()[0];
-             }
-             Set<Provider> p = new HashSet<Provider>();
-             p.add(firewallProvider);
-             serviceToProviders.remove(Service.Lb);
-             serviceToProviders.put(Service.Lb, p);
-         }
-         for (PublicIp ip : ipToServices.keySet()) {
-             Set<Service> services = ipToServices.get(ip);
-             Provider provider = null;
-             for (Service service : services) {
-                 Set<Provider> curProviders = serviceToProviders.get(service);
-                 if (curProviders == null || curProviders.isEmpty()) {
-                     continue;
-                 }
-                 Provider curProvider = (Provider) curProviders.toArray()[0];
-                 if (provider == null) {
-                     provider = curProvider;
-                     continue;
-                 }
-                 // We don't support multiple providers for one service now
-                 if (!provider.equals(curProvider)) {
-                     throw new InvalidParameterException("There would be multiple providers for IP " + ip.getAddress() + " with the new network offering!");
-                 }
-             }
-         }
-         return true;
-     }
 -   
 +
-     public boolean canIpUsedForService(PublicIp publicIp, Service service, Long networkId) {
-         List<PublicIp> ipList = new ArrayList<PublicIp>();
-         ipList.add(publicIp);
-         Map<PublicIp, Set<Service>> ipToServices = getIpToServices(ipList, false, true);
-         Set<Service> services = ipToServices.get(publicIp);
-         if (services == null || services.isEmpty()) {
-             return true;
-         }
-         
-         if (networkId == null) {
-             networkId = publicIp.getAssociatedWithNetworkId();
-         }
-         
-         // We only support one provider for one service now
-         Map<Service, Set<Provider>> serviceToProviders = getServiceProvidersMap(networkId);
-         Set<Provider> oldProviders = serviceToProviders.get(services.toArray()[0]);
-         Provider oldProvider = (Provider) oldProviders.toArray()[0];
-         // Since IP already has service to bind with, the oldProvider can't be null
-         Set<Provider> newProviders = serviceToProviders.get(service);
-         if (newProviders == null || newProviders.isEmpty()) {
-             throw new InvalidParameterException("There is no new provider for IP " + publicIp.getAddress() + " of service " + service.getName() + "!");
-         }
-         Provider newProvider = (Provider) newProviders.toArray()[0];
-         Network network = _networksDao.findById(networkId);
-         NetworkElement oldElement = getElementImplementingProvider(oldProvider.getName());
-         NetworkElement newElement = getElementImplementingProvider(newProvider.getName());
-         if (oldElement instanceof IpDeployingRequester && newElement instanceof IpDeployingRequester) {
-         	IpDeployer oldIpDeployer = ((IpDeployingRequester)oldElement).getIpDeployer(network);
-         	IpDeployer newIpDeployer = ((IpDeployingRequester)newElement).getIpDeployer(network);
-         	if (!oldIpDeployer.getProvider().getName().equals(newIpDeployer.getProvider().getName())) {
-             throw new InvalidParameterException("There would be multiple providers for IP " + publicIp.getAddress() + "!");
-         }
-         } else {
-         	throw new InvalidParameterException("Ip cannot be applied for new provider!");
-         }
-         return true;
-     }
  
-     /* Return a mapping between provider in the network and the IP they should applied */
      @Override
-     public Map<Provider, ArrayList<PublicIp>> getProviderToIpList(Network network, Map<PublicIp, Set<Service>> ipToServices) {
-         NetworkOffering offering = _networkOfferingDao.findById(network.getNetworkOfferingId());
-         if (!offering.isConserveMode()) {
-             for (PublicIp ip : ipToServices.keySet()) {
-                 Set<Service> services = new HashSet<Service>() ;
-                 services.addAll(ipToServices.get(ip));
-                 if (services != null && services.contains(Service.Firewall)) {
-                     services.remove(Service.Firewall);
-                 }
-                 if (services != null && services.size() > 1) {
-                     throw new CloudRuntimeException("Ip " + ip.getAddress() + " is used by multiple services!");
-                 }
-             }
-         }
-         Map<Service, Set<PublicIp>> serviceToIps = new HashMap<Service, Set<PublicIp>>();
-         for (PublicIp ip : ipToServices.keySet()) {
-             for (Service service : ipToServices.get(ip)) {
-                 Set<PublicIp> ips = serviceToIps.get(service);
-                 if (ips == null) {
-                     ips = new HashSet<PublicIp>();
-                 }
-                 ips.add(ip);
-                 serviceToIps.put(service, ips);
-             }
-         }
-         // TODO Check different provider for same IP
-         Map<Provider, Set<Service>> providerToServices = getProviderServicesMap(network.getId());
-         Map<Provider, ArrayList<PublicIp>> providerToIpList = new HashMap<Provider, ArrayList<PublicIp>>();
-         for (Provider provider : providerToServices.keySet()) {
-             Set<Service> services = providerToServices.get(provider);
-             ArrayList<PublicIp> ipList = new ArrayList<PublicIp>();
-             Set<PublicIp> ipSet = new HashSet<PublicIp>();
-             for (Service service : services) {
-                 Set<PublicIp> serviceIps = serviceToIps.get(service);
-                 if (serviceIps == null || serviceIps.isEmpty()) {
-                     continue;
-                 }
-                 ipSet.addAll(serviceIps);
-             }
-             Set<PublicIp> sourceNatIps = serviceToIps.get(Service.SourceNat);
-             if (sourceNatIps != null && !sourceNatIps.isEmpty()) {
-                 ipList.addAll(0, sourceNatIps);
-                 ipSet.removeAll(sourceNatIps);
-             }
-             ipList.addAll(ipSet);
-             providerToIpList.put(provider, ipList);
-         }
-         return providerToIpList;
-     }
- 
-     protected boolean applyIpAssociations(Network network, boolean rulesRevoked, boolean continueOnError, 
-             List<PublicIp> publicIps) throws ResourceUnavailableException {
+     public boolean applyIpAssociations(Network network, boolean rulesRevoked, boolean continueOnError, 
+             List<? extends PublicIpAddress> publicIps) throws ResourceUnavailableException {
          boolean success = true;
  
-         Map<PublicIp, Set<Service>> ipToServices = getIpToServices(publicIps, rulesRevoked, true);
-         Map<Provider, ArrayList<PublicIp>> providerToIpList = getProviderToIpList(network, ipToServices);
+         Map<PublicIpAddress, Set<Service>> ipToServices = _networkModel.getIpToServices(publicIps, rulesRevoked, true);
+         Map<Provider, ArrayList<PublicIpAddress>> providerToIpList = _networkModel.getProviderToIpList(network, ipToServices);
  
          for (Provider provider : providerToIpList.keySet()) {
              try {
@@@ -939,85 -590,26 +595,26 @@@
          return success;
      }
  
-     Set<Purpose> getPublicIpPurposeInRules(PublicIp ip, boolean includeRevoked, boolean includingFirewall) {
-         Set<Purpose> result = new HashSet<Purpose>();
-         List<FirewallRuleVO> rules = null;
-         if (includeRevoked) {
-             rules = _firewallDao.listByIp(ip.getId());
-         } else {
-             rules = _firewallDao.listByIpAndNotRevoked(ip.getId());
-         }
- 
-         if (rules == null || rules.isEmpty()) {
-             return null;
-         }
- 
-         for (FirewallRuleVO rule : rules) {
-             if (rule.getPurpose() != Purpose.Firewall || includingFirewall) {
-                 result.add(rule.getPurpose());
-             }
-         }
  
-         return result;
-     }
 -    
 -    
 +
-     @Override
-     public List<? extends Network> getIsolatedNetworksOwnedByAccountInZone(long zoneId, Account owner) {
 +
-         return _networksDao.listByZoneAndGuestType(owner.getId(), zoneId, Network.GuestType.Isolated, false);
-     }
-     
-     @Override
-     public List<? extends Network> getIsolatedNetworksWithSourceNATOwnedByAccountInZone(long zoneId, Account owner) {
+     protected List<? extends Network> getIsolatedNetworksWithSourceNATOwnedByAccountInZone(long zoneId, Account owner) {
  
          return _networksDao.listSourceNATEnabledNetworks(owner.getId(), zoneId, Network.GuestType.Isolated);
      }
  
-     @Override
-     @ActionEvent(eventType = EventTypes.EVENT_NET_IP_ASSIGN, eventDescription = "allocating Ip", create = true)
-     public IpAddress allocateIP(Account ipOwner, long zoneId, Long networkId)
-             throws ResourceAllocationException, InsufficientAddressCapacityException, ConcurrentOperationException {
- 
-         if (networkId != null) {
-             Network network = _networksDao.findById(networkId);
-             if (network == null) {
-                 throw new InvalidParameterValueException("Invalid network id is given");
-             }
-             if (network.getGuestType() == Network.GuestType.Shared) {
-                 DataCenter zone = _configMgr.getZone(zoneId);
-                 if (zone == null) {
-                     throw new InvalidParameterValueException("Invalid zone Id is given");
-                 }
- 
-                 // if shared network in the advanced zone, then check the caller against the network for 'AccessType.UseNetwork'
-                 if (isSharedNetworkOfferingWithServices(network.getNetworkOfferingId()) && zone.getNetworkType() == NetworkType.Advanced) {
-                     Account caller = UserContext.current().getCaller();
-                     long callerUserId = UserContext.current().getCallerUserId();
-                     _accountMgr.checkAccess(caller, AccessType.UseNetwork, false, network);
-                     if (s_logger.isDebugEnabled()) {
-                         s_logger.debug("Associate IP address called by the user " + callerUserId + " account " + ipOwner.getId());
-                     }
-                     return allocateIp(ipOwner, false, caller, zone);
-                 } else {
-                     throw new InvalidParameterValueException("Associate IP address can only be called on the shared networks in the advanced zone" +
-                             " with Firewall/Source Nat/Static Nat/Port Forwarding/Load balancing services enabled");
-                 }
-             }
-         }
 -    
 +
-         return allocateIP(ipOwner, false,  zoneId);
-     }
  
-     public IpAddress allocateIP(Account ipOwner, boolean isSystem, long zoneId) 
+     private IpAddress allocateIP(Account ipOwner, boolean isSystem, long zoneId) 
              throws ResourceAllocationException, InsufficientAddressCapacityException, ConcurrentOperationException {
          Account caller = UserContext.current().getCaller();
          long callerUserId = UserContext.current().getCallerUserId();
          // check permissions
          _accountMgr.checkAccess(caller, null, false, ipOwner);
-         
+ 
          DataCenter zone = _configMgr.getZone(zoneId);
--        
-         return allocateIp(ipOwner, isSystem, caller, zone);
++
+         return allocateIp(ipOwner, isSystem, caller, callerUserId, zone);
      }
  
      @DB
@@@ -1088,11 -681,10 +686,10 @@@
          return ip;
      }
  
-     
      protected IPAddressVO getExistingSourceNatInNetwork(long ownerId, Long networkId) {
 -        
 +
-         List<IPAddressVO> addrs = listPublicIpsAssignedToGuestNtwk(ownerId, networkId, true);
+         List<? extends IpAddress> addrs = _networkModel.listPublicIpsAssignedToGuestNtwk(ownerId, networkId, true);
 -    
 +
          IPAddressVO sourceNatIp = null;
          if (addrs.isEmpty()) {
              return null;
@@@ -1104,19 -696,19 +701,19 @@@
                      return sourceNatIp;
                  }
              }
 -    
 +
              assert (sourceNatIp != null) : "How do we get a bunch of ip addresses but none of them are source nat? " +
--                    "account=" + ownerId + "; networkId=" + networkId;
 -        }
++            "account=" + ownerId + "; networkId=" + networkId;
 +        } 
-         
+ 
          return sourceNatIp;
      }
 -    
 +
      @DB
      @Override
 -    public IPAddressVO associateIPToGuestNetwork(long ipId, long networkId, boolean releaseOnFailure)
 -            throws ResourceAllocationException, ResourceUnavailableException,
 -    InsufficientAddressCapacityException, ConcurrentOperationException {
 +    public IPAddressVO associateIPToGuestNetwork(long ipId, long networkId, boolean releaseOnFailure) 
 +            throws ResourceAllocationException, ResourceUnavailableException, 
-     InsufficientAddressCapacityException, ConcurrentOperationException {
++            InsufficientAddressCapacityException, ConcurrentOperationException {
          Account caller = UserContext.current().getCaller();
          Account owner = null;
  
@@@ -1164,21 -741,17 +746,17 @@@
              throw new InvalidParameterValueException("Ip address can be associated to the network with trafficType " + TrafficType.Guest);
          }
  
-         // Check that network belongs to IP owner - skip this check
-         //     - if zone is basic zone as there is just one guest network,
-         //     - if shared network in Advanced zone
-         //     - and it belongs to the system
-         if (network.getAccountId() != owner.getId()) {
-             if (zone.getNetworkType() != NetworkType.Basic && !(zone.getNetworkType() == NetworkType.Advanced && network.getGuestType() == Network.GuestType.Shared)) {
+         // Check that network belongs to IP owner - skip this check for Basic zone as there is just one guest network,
+         // and it belongs to the system
+         if (zone.getNetworkType() != NetworkType.Basic && network.getAccountId() != owner.getId()) {
              throw new InvalidParameterValueException("The owner of the network is not the same as owner of the IP");
          }
-         }
-         
-         // In Advance zone only allow to do IP assoc
-         //      - for Isolated networks with source nat service enabled
-         //      - for shared networks with source nat service enabled
-         if (zone.getNetworkType() == NetworkType.Advanced && (!areServicesSupportedInNetwork(network.getId(), Service.SourceNat))) {
+ 
+         // In Advance zone only allow to do IP assoc for Isolated networks with source nat service enabled
+         if (zone.getNetworkType() == NetworkType.Advanced &&
 -            !(network.getGuestType() == GuestType.Isolated && _networkModel.areServicesSupportedInNetwork(network.getId(),
 -                Service.SourceNat))) {
 -            throw new InvalidParameterValueException("In zone of type " + NetworkType.Advanced +
++                !(network.getGuestType() == GuestType.Isolated && _networkModel.areServicesSupportedInNetwork(network.getId(),
++                        Service.SourceNat))) {
 +            throw new InvalidParameterValueException("In zone of type " + NetworkType.Advanced + 
                      " ip address can be associated only to the network of guest type " + GuestType.Isolated + " with the "
                      + Service.SourceNat.getName() + " enabled");
          }
@@@ -1288,26 -861,9 +866,9 @@@
          _configs = _configDao.getConfiguration("Network", params);
          _networkDomain = _configs.get(Config.GuestDomainSuffix.key());
  
-         _cidrLimit = NumbersUtil.parseInt(_configs.get(Config.NetworkGuestCidrLimit.key()), 22);
          _networkLockTimeout = NumbersUtil.parseInt(_configs.get(Config.NetworkLockTimeout.key()), 600);
  
-         NetworkOfferingVO publicNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemPublicNetwork, TrafficType.Public, true);
-         publicNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(publicNetworkOffering);
-         _systemNetworks.put(NetworkOfferingVO.SystemPublicNetwork, publicNetworkOffering);
-         NetworkOfferingVO managementNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemManagementNetwork, TrafficType.Management, false);
-         managementNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(managementNetworkOffering);
-         _systemNetworks.put(NetworkOfferingVO.SystemManagementNetwork, managementNetworkOffering);
-         NetworkOfferingVO controlNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemControlNetwork, TrafficType.Control, false);
-         controlNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(controlNetworkOffering);
-         _systemNetworks.put(NetworkOfferingVO.SystemControlNetwork, controlNetworkOffering);
-         NetworkOfferingVO storageNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemStorageNetwork, TrafficType.Storage, true);
-         storageNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(storageNetworkOffering);
-         _systemNetworks.put(NetworkOfferingVO.SystemStorageNetwork, storageNetworkOffering);
-         NetworkOfferingVO privateGatewayNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemPrivateGatewayNetworkOffering,
-                 GuestType.Isolated);
-         privateGatewayNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(privateGatewayNetworkOffering);
-         _systemNetworks.put(NetworkOfferingVO.SystemPrivateGatewayNetworkOffering, privateGatewayNetworkOffering);
-         _privateOfferingId = privateGatewayNetworkOffering.getId();
 -        
++
  
  
          // populate providers
@@@ -1343,9 -899,9 +904,9 @@@
          defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.StaticNat, defaultProviders);
          defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.PortForwarding, defaultProviders);
          defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.Vpn, defaultProviders);
-         
-         
+ 
+ 
 -        Map<Network.Service, Set<Network.Provider>> defaultVPCOffProviders =
 +        Map<Network.Service, Set<Network.Provider>> defaultVPCOffProviders = 
                  new HashMap<Network.Service, Set<Network.Provider>>();
          defaultProviders.clear();
          defaultProviders.add(Network.Provider.VirtualRouter);
@@@ -1463,13 -1019,7 +1024,7 @@@
  
          txn.commit();
  
-         AccountsUsingNetworkSearch = _accountDao.createSearchBuilder();
-         SearchBuilder<NetworkAccountVO> networkAccountSearch = _networksDao.createSearchBuilderForAccount();
-         AccountsUsingNetworkSearch.join("nc", networkAccountSearch, AccountsUsingNetworkSearch.entity().getId(), networkAccountSearch.entity().getAccountId(), JoinType.INNER);
-         networkAccountSearch.and("config", networkAccountSearch.entity().getNetworkId(), SearchCriteria.Op.EQ);
-         networkAccountSearch.and("owner", networkAccountSearch.entity().isOwner(), SearchCriteria.Op.EQ);
-         AccountsUsingNetworkSearch.done();
 -       
 +
          AssignIpAddressSearch = _ipAddressDao.createSearchBuilder();
          AssignIpAddressSearch.and("dc", AssignIpAddressSearch.entity().getDataCenterId(), Op.EQ);
          AssignIpAddressSearch.and("allocated", AssignIpAddressSearch.entity().getAllocatedTime(), Op.NULL);
@@@ -1527,36 -1058,7 +1063,6 @@@
  
      @Override
      public boolean start() {
--
-         // populate s_serviceToImplementedProvidersMap & s_providerToNetworkElementMap with current _networkElements
-         // Need to do this in start() since _networkElements are not completely configured until then.
-         for (NetworkElement element : _networkElements) {
-             Map<Service, Map<Capability, String>> capabilities = element.getCapabilities();
-             Provider implementedProvider = element.getProvider();
-             if (implementedProvider != null) {
-                 if (s_providerToNetworkElementMap.containsKey(implementedProvider.getName())) {
-                     s_logger.error("Cannot start NetworkManager: Provider <-> NetworkElement must be a one-to-one map, " +
-                             "multiple NetworkElements found for Provider: " + implementedProvider.getName());
-                     return false;
-                 }
-                 s_logger.info("add element/provider mapping. provider: " + implementedProvider.getName() + " -> " + element.getName()
-                 		+ ", class: " + ComponentContext.getTargetClass(element).getName());
-                 s_providerToNetworkElementMap.put(implementedProvider.getName(), element.getName());
-             }
-             if (capabilities != null && implementedProvider != null) {
-                 for (Service service : capabilities.keySet()) {
-                     if (s_serviceToImplementedProvidersMap.containsKey(service)) {
-                         List<Provider> providers = s_serviceToImplementedProvidersMap.get(service);
-                         providers.add(implementedProvider);
-                     } else {
-                         List<Provider> providers = new ArrayList<Provider>();
-                         providers.add(implementedProvider);
-                         s_serviceToImplementedProvidersMap.put(service, providers);
-                     }
-                 }
-             }
-         }
- 
          _executor.scheduleWithFixedDelay(new NetworkGarbageCollector(), _networkGcInterval, _networkGcInterval, TimeUnit.SECONDS);
          return true;
      }
@@@ -1570,38 -1072,9 +1076,9 @@@
      }
  
      @Override
-     public List<IPAddressVO> listPublicIpsAssignedToGuestNtwk(long accountId, long associatedNetworkId, Boolean sourceNat) {
-         SearchCriteria<IPAddressVO> sc = IpAddressSearch.create();
-         sc.setParameters("accountId", accountId);
-         sc.setParameters("associatedWithNetworkId", associatedNetworkId); 
- 
-         if (sourceNat != null) {
-             sc.addAnd("sourceNat", SearchCriteria.Op.EQ, sourceNat);
-         }
-         sc.setJoinParameters("virtualNetworkVlanSB", "vlanType", VlanType.VirtualNetwork);
- 
-         return _ipAddressDao.search(sc, null);
-     }
-     
-     @Override
-     public List<IPAddressVO> listPublicIpsAssignedToAccount(long accountId, long dcId, Boolean sourceNat) {
-         SearchCriteria<IPAddressVO> sc = IpAddressSearch.create();
-         sc.setParameters("accountId", accountId);
-         sc.setParameters("dataCenterId", dcId);
- 
-         if (sourceNat != null) {
-             sc.addAnd("sourceNat", SearchCriteria.Op.EQ, sourceNat);
-         }
-         sc.setJoinParameters("virtualNetworkVlanSB", "vlanType", VlanType.VirtualNetwork);
- 
-         return _ipAddressDao.search(sc, null);
-     }
- 
- 
-     @Override
-     public List<NetworkVO> setupNetwork(Account owner, NetworkOfferingVO offering, DeploymentPlan plan, String name, 
+     public List<NetworkVO> setupNetwork(Account owner, NetworkOffering offering, DeploymentPlan plan, String name, 
              String displayText, boolean isDefault)
--            throws ConcurrentOperationException {
++                    throws ConcurrentOperationException {
          return setupNetwork(owner, offering, null, plan, name, displayText, false, null, null, null, null);
      }
  
@@@ -1708,18 -1181,7 +1185,7 @@@
          }
      }
  
-     @Override
-     public List<NetworkOfferingVO> getSystemAccountNetworkOfferings(String... offeringNames) {
-         List<NetworkOfferingVO> offerings = new ArrayList<NetworkOfferingVO>(offeringNames.length);
-         for (String offeringName : offeringNames) {
-             NetworkOfferingVO network = _systemNetworks.get(offeringName);
-             if (network == null) {
-                 throw new CloudRuntimeException("Unable to find system network profile for " + offeringName);
-             }
-             offerings.add(network);
-         }
-         return offerings;
-     }
 -    
++
  
      @Override
      @DB
@@@ -1748,10 -1210,10 +1214,10 @@@
              while (deviceIds[deviceId] && deviceId < deviceIds.length) {
                  deviceId++;
              }
-             
+ 
 -            Pair<NicProfile,Integer> vmNicPair = allocateNic(requested, config, isDefaultNic,
 +            Pair<NicProfile,Integer> vmNicPair = allocateNic(requested, config, isDefaultNic, 
                      deviceId, vm);
-             
+ 
              NicProfile vmNic = vmNicPair.first();
              if (vmNic == null) {
                  continue;
@@@ -1768,11 -1230,11 +1234,11 @@@
              }
  
              deviceIds[devId] = true;
-             
+ 
              if (vmNic.isDefaultNic()) {
                  if (defaultNic != null) {
 -                    throw new IllegalArgumentException("You cannot specify two nics as default nics: nic 1 = " +
 -                defaultNic + "; nic 2 = " + vmNic);
 +                    throw new IllegalArgumentException("You cannot specify two nics as default nics: nic 1 = " + 
-                 defaultNic + "; nic 2 = " + vmNic);
++                            defaultNic + "; nic 2 = " + vmNic);
                  }
                  defaultNic = vmNic;
              }
@@@ -1793,17 -1255,17 +1259,17 @@@
  
          txn.commit();
      }
-     
-     
+ 
+ 
      @DB
      @Override
 -    public Pair<NicProfile,Integer> allocateNic(NicProfile requested, Network network, Boolean isDefaultNic,
 +    public Pair<NicProfile,Integer> allocateNic(NicProfile requested, Network network, Boolean isDefaultNic, 
              int deviceId, VirtualMachineProfile<? extends VMInstanceVO> vm) throws InsufficientVirtualNetworkCapcityException,
              InsufficientAddressCapacityException, ConcurrentOperationException{
-         
+ 
          NetworkVO ntwkVO = _networksDao.findById(network.getId());
          s_logger.debug("Allocating nic for vm " + vm.getVirtualMachine() + " in network " + network + " with requested profile " + requested);
 -        NetworkGuru guru = _networkGurus.get(ntwkVO.getGuruName());
 +        NetworkGuru guru = AdapterBase.getAdapterByName(_networkGurus, ntwkVO.getGuruName());
  
          if (requested != null && requested.getMode() == null) {
              requested.setMode(network.getMode());
@@@ -1828,14 -1290,14 +1294,14 @@@
          deviceId = applyProfileToNic(vo, profile, deviceId);
  
          vo = _nicDao.persist(vo);
--    
-         Integer networkRate = getNetworkRate(network.getId(), vm.getId());
++
+         Integer networkRate = _networkModel.getNetworkRate(network.getId(), vm.getId());
          NicProfile vmNic = new NicProfile(vo, network, vo.getBroadcastUri(), vo.getIsolationUri(), networkRate, 
-                 isSecurityGroupSupportedInNetwork(network), getNetworkTag(vm.getHypervisorType(),
-                 network));
-         
+                 _networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(vm.getHypervisorType(),
 -                network));
++                        network));
+ 
          return new Pair<NicProfile,Integer>(vmNic, Integer.valueOf(deviceId));
 -    }
 +    }    
  
      protected Integer applyProfileToNic(NicVO vo, NicProfile profile, Integer deviceId) {
          if (profile.getDeviceId() != null) {
@@@ -1948,9 -1410,9 +1414,9 @@@
          }
  
          try {
 -            NetworkGuru guru = _networkGurus.get(network.getGuruName());
 +            NetworkGuru guru = AdapterBase.getAdapterByName(_networkGurus, network.getGuruName());
              Network.State state = network.getState();
-             if (state == Network.State.Implemented || state == Network.State.Implementing) {
+             if (state == Network.State.Implemented || state == Network.State.Setup || state == Network.State.Implementing) {
                  s_logger.debug("Network id=" + networkId + " is already implemented");
                  implemented.set(guru, network);
                  return implemented;
@@@ -2013,21 -1466,21 +1470,21 @@@
          return super.equals(o);    //To change body of overridden methods use File | Settings | File Templates.
      }
  
-     private void implementNetworkElementsAndResources(DeployDestination dest, ReservationContext context, 
+     @Override
+     public void implementNetworkElementsAndResources(DeployDestination dest, ReservationContext context,
 -                                                      NetworkVO network, NetworkOfferingVO offering)
 -            throws ConcurrentOperationException, InsufficientAddressCapacityException, ResourceUnavailableException, InsufficientCapacityException {
 +            NetworkVO network, NetworkOfferingVO offering)
-             throws ConcurrentOperationException, InsufficientAddressCapacityException, ResourceUnavailableException, InsufficientCapacityException {
++                    throws ConcurrentOperationException, InsufficientAddressCapacityException, ResourceUnavailableException, InsufficientCapacityException {
  
-         // Associate a source NAT IP (if one isn't already associated with the network) if this is a
-         //     1) 'Isolated' or 'Shared' guest virtual network in the advance zone
-         //     2) network has sourceNat service
-         //     3) network offering does not support a shared source NAT rule
+         // If this is a 1) guest virtual network 2) network has sourceNat service 3) network offering does not support a
+         // Shared source NAT rule,
+         // associate a source NAT IP (if one isn't already associated with the network)
  
          boolean sharedSourceNat = offering.getSharedSourceNat();
          DataCenter zone = _dcDao.findById(network.getDataCenterId());
-         if (!sharedSourceNat && areServicesSupportedInNetwork(network.getId(), Service.SourceNat)
-                 && (network.getGuestType() == Network.GuestType.Isolated ||
-                 (network.getGuestType() == Network.GuestType.Shared && zone.getNetworkType() == NetworkType.Advanced))) {
-             
+         if (network.getGuestType() == Network.GuestType.Isolated
 -               && _networkModel.areServicesSupportedInNetwork(network.getId(), Service.SourceNat)
 -               && !sharedSourceNat) {
++                && _networkModel.areServicesSupportedInNetwork(network.getId(), Service.SourceNat)
++                && !sharedSourceNat) {
+ 
              List<IPAddressVO> ips = null;
              if (network.getVpcId() != null) {
                  ips = _ipAddressDao.listByAssociatedVpc(network.getVpcId(), true);
@@@ -2122,7 -1575,7 +1579,7 @@@
  
      @Override
      public void prepare(VirtualMachineProfile<? extends VMInstanceVO> vmProfile, DeployDestination dest, ReservationContext context) throws InsufficientCapacityException,
--            ConcurrentOperationException, ResourceUnavailableException {
++    ConcurrentOperationException, ResourceUnavailableException {
          List<NicVO> nics = _nicDao.listByVmId(vmProfile.getId());
  
          // we have to implement default nics first - to ensure that default network elements start up first in multiple
@@@ -2149,15 -1602,15 +1606,15 @@@
      }
  
      @Override
 -    public NicProfile prepareNic(VirtualMachineProfile<? extends VMInstanceVO> vmProfile, DeployDestination
 +    public NicProfile prepareNic(VirtualMachineProfile<? extends VMInstanceVO> vmProfile, DeployDestination 
              dest, ReservationContext context, long nicId, NetworkVO network)
-             throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException, 
-             ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException {
-         
-         Integer networkRate = getNetworkRate(network.getId(), vmProfile.getId());
 -            throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException,
 -            ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException {
 -        
++                    throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException, 
++                    ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException {
++
+         Integer networkRate = _networkModel.getNetworkRate(network.getId(), vmProfile.getId());
 -        NetworkGuru guru = _networkGurus.get(network.getGuruName());
 +        NetworkGuru guru = AdapterBase.getAdapterByName(_networkGurus, network.getGuruName());
          NicVO nic = _nicDao.findById(nicId);
-         
+ 
          NicProfile profile = null;
          if (nic.getReservationStrategy() == Nic.ReservationStrategy.Start) {
              nic.setState(Nic.State.Reserving);
@@@ -2170,9 -1623,9 +1627,9 @@@
  
              URI isolationUri = nic.getIsolationUri();
  
 -            profile = new NicProfile(nic, network, broadcastUri, isolationUri,
 +            profile = new NicProfile(nic, network, broadcastUri, isolationUri, 
  
-             networkRate, isSecurityGroupSupportedInNetwork(network), getNetworkTag(vmProfile.getHypervisorType(), network));
 -            networkRate, _networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(vmProfile.getHypervisorType(), network));
++                    networkRate, _networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(vmProfile.getHypervisorType(), network));
              guru.reserve(profile, network, vmProfile, dest, context);
              nic.setIp4Address(profile.getIp4Address());
              nic.setAddressFormat(profile.getFormat());
@@@ -2192,7 -1645,7 +1649,7 @@@
              updateNic(nic, network.getId(), 1);
          } else {
              profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), 
-                         networkRate, isSecurityGroupSupportedInNetwork(network), getNetworkTag(vmProfile.getHypervisorType(), network));
 -                        networkRate, _networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(vmProfile.getHypervisorType(), network));
++                    networkRate, _networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(vmProfile.getHypervisorType(), network));
              guru.updateNicProfile(profile, network);
              nic.setState(Nic.State.Reserved);
              updateNic(nic, network.getId(), 1);
@@@ -2215,11 -1668,11 +1672,11 @@@
          List<NicVO> nics = _nicDao.listByVmId(vm.getId());
          for (NicVO nic : nics) {
              NetworkVO network = _networksDao.findById(nic.getNetworkId());
-             Integer networkRate = getNetworkRate(network.getId(), vm.getId());
+             Integer networkRate = _networkModel.getNetworkRate(network.getId(), vm.getId());
  
 -            NetworkGuru guru = _networkGurus.get(network.getGuruName());
 +            NetworkGuru guru = AdapterBase.getAdapterByName(_networkGurus, network.getGuruName());
              NicProfile profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), networkRate, 
-                     isSecurityGroupSupportedInNetwork(network), getNetworkTag(vm.getHypervisorType(), network));
+                     _networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(vm.getHypervisorType(), network));
              guru.updateNicProfile(profile, network);
              vm.addNic(profile);
          }
@@@ -2228,7 -1681,7 +1685,7 @@@
      @Override
      @DB
      public void release(VirtualMachineProfile<? extends VMInstanceVO> vmProfile, boolean forced) throws
--            ConcurrentOperationException, ResourceUnavailableException {
++    ConcurrentOperationException, ResourceUnavailableException {
          List<NicVO> nics = _nicDao.listByVmId(vmProfile.getId());
          for (NicVO nic : nics) {
              releaseNic(vmProfile, nic);
@@@ -2492,8 -1771,8 +1775,8 @@@
          _nicDao.update(nic.getId(), nic);
          NetworkVO network = _networksDao.findById(nic.getNetworkId());
          NicProfile profile = new NicProfile(nic, network, null, null, null,
-                 isSecurityGroupSupportedInNetwork(network), getNetworkTag(vm.getHypervisorType(), network));
+                 _networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(vm.getHypervisorType(), network));
 -        NetworkGuru guru = _networkGurus.get(network.getGuruName());
 +        NetworkGuru guru = AdapterBase.getAdapterByName(_networkGurus, network.getGuruName());
          guru.deallocate(network, profile, vm);
          _nicDao.remove(nic.getId());
          s_logger.debug("Removed nic id=" + nic.getId());
@@@ -2507,352 -1786,7 +1790,7 @@@
          }
      }
  
-     private void checkSharedNetworkCidrOverlap(Long zoneId, long physicalNetworkId, String cidr) {
-         if (zoneId == null || cidr == null) {
-             return;
-         }
- 
-         DataCenter zone = _dcDao.findById(zoneId);
-         List<NetworkVO> networks = _networksDao.listByZone(zoneId);
-         Map<Long, String> networkToCidr = new HashMap<Long, String>();
- 
-         // check for CIDR overlap with all possible CIDR for isolated guest networks
-         // in the zone when using external networking
-         PhysicalNetworkVO pNetwork = _physicalNetworkDao.findById(physicalNetworkId);
-         if (pNetwork.getVnet() != null) {
-             String vlanRange[] = pNetwork.getVnet().split("-");
-             int lowestVlanTag = Integer.valueOf(vlanRange[0]);
-             int highestVlanTag = Integer.valueOf(vlanRange[1]);
-             for (int vlan=lowestVlanTag; vlan <= highestVlanTag; ++vlan) {
-                 int offset = vlan - lowestVlanTag;
-                 String globalVlanBits = _configDao.getValue(Config.GuestVlanBits.key());
-                 int cidrSize = 8 + Integer.parseInt(globalVlanBits);
-                 String guestNetworkCidr = zone.getGuestNetworkCidr();
-                 String[] cidrTuple = guestNetworkCidr.split("\\/");
-                 long newCidrAddress = (NetUtils.ip2Long(cidrTuple[0]) & 0xff000000) | (offset << (32 - cidrSize));
-                 if (NetUtils.isNetworksOverlap(NetUtils.long2Ip(newCidrAddress), cidr)) {
-                     throw new InvalidParameterValueException("Specified CIDR for shared network conflict with CIDR that is reserved for zone vlan " + vlan);
-                 }
-             }
-         }
- 
-         // check for CIDR overlap with all CIDR's of the shared networks in the zone
-         for (NetworkVO network : networks) {
-             if (network.getGuestType() == GuestType.Isolated) {
-                 continue;
-             }
-             if (network.getCidr() != null) {
-                 networkToCidr.put(network.getId(), network.getCidr());
-             }
-         }
-         if (networkToCidr != null && !networkToCidr.isEmpty()) {
-             for (long networkId : networkToCidr.keySet()) {
-                 String ntwkCidr = networkToCidr.get(networkId);
-                 if (NetUtils.isNetworksOverlap(ntwkCidr, cidr)) {
-                     throw new InvalidParameterValueException("Specified CIDR for shared network conflict with CIDR of a shared network in the zone.");
-                 }
-             }
-         }
-     }
-         public void checkVirtualNetworkCidrOverlap(Long zoneId, String cidr) {
-         if (zoneId == null) {
-             return;
-         }
-         if (cidr == null) {
-             return;
-         }
-         List<NetworkVO> networks = _networksDao.listByZone(zoneId);
-         Map<Long, String> networkToCidr = new HashMap<Long, String>();
-         for (NetworkVO network : networks) {
-             if (network.getGuestType() != GuestType.Isolated) {
-                 continue;
-             }
-             if (network.getCidr() != null) {
-                 networkToCidr.put(network.getId(), network.getCidr());
-             }
-         }
-         if (networkToCidr == null || networkToCidr.isEmpty()) {
-             return;
-         }
- 
-         for (long networkId : networkToCidr.keySet()) {
-             String ntwkCidr = networkToCidr.get(networkId);
-             if (NetUtils.isNetworksOverlap(ntwkCidr, cidr)) {
-                 throw new InvalidParameterValueException("Warning: The specified existing network has conflict CIDR subnets with new network!");
-             }
-         }
-     }
- 
-     @Override
-     @DB
-     @ActionEvent(eventType = EventTypes.EVENT_NETWORK_CREATE, eventDescription = "creating network")
-     public Network createGuestNetwork(CreateNetworkCmd cmd) throws InsufficientCapacityException, ConcurrentOperationException, ResourceAllocationException {
-         Long networkOfferingId = cmd.getNetworkOfferingId();
-         String gateway = cmd.getGateway();
-         String startIP = cmd.getStartIp();
-         String endIP = cmd.getEndIp();
-         String netmask = cmd.getNetmask();
-         String networkDomain = cmd.getNetworkDomain();
-         String vlanId = cmd.getVlan();
-         String name = cmd.getNetworkName();
-         String displayText = cmd.getDisplayText();
-         Account caller = UserContext.current().getCaller();
-         Long physicalNetworkId = cmd.getPhysicalNetworkId();
-         Long zoneId = cmd.getZoneId();
-         String aclTypeStr = cmd.getAclType();
-         Long domainId = cmd.getDomainId();
-         boolean isDomainSpecific = false;
-         Boolean subdomainAccess = cmd.getSubdomainAccess();
-         Long vpcId = cmd.getVpcId();
- 
-         // Validate network offering
-         NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
-         if (ntwkOff == null || ntwkOff.isSystemOnly()) {
-             InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find network offering by specified id");
-             if (ntwkOff != null) {
-                 ex.addProxyObject(ntwkOff, networkOfferingId, "networkOfferingId");                
-                 // Get the VO object's table name.
-                 String tablename = AnnotationHelper.getTableName(ntwkOff);
-                 if (tablename != null) {
-                     ex.addProxyObject(tablename, networkOfferingId, "networkOfferingId");
-                 } else {
-                     s_logger.info("\nCould not retrieve table name (annotation) from " + tablename + " VO proxy object\n");
-                 }
-                 throw ex;
-             }
-             throw ex;
-         }
-         // validate physical network and zone
-         // Check if physical network exists
-         PhysicalNetwork pNtwk = null;
-         if (physicalNetworkId != null) {
-             pNtwk = _physicalNetworkDao.findById(physicalNetworkId);
-             if (pNtwk == null) {
-                 throw new InvalidParameterValueException("Unable to find a physical network having the specified physical network id");
-             }
-         }
- 
-         if (zoneId == null) {
-             zoneId = pNtwk.getDataCenterId();
-         }
- 
-         DataCenter zone = _dcDao.findById(zoneId);
-         if (zone == null) {
-             throw new InvalidParameterValueException("Specified zone id was not found");
-         }
-         
-         if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getType())) {
-             // See DataCenterVO.java
-             PermissionDeniedException ex = new PermissionDeniedException("Cannot perform this operation since specified Zone is currently disabled");
-             ex.addProxyObject(zone, zoneId, "zoneId");
-             throw ex;            
-         }
- 
-         // Only domain and account ACL types are supported in Acton.
-         ACLType aclType = null;
-         if (aclTypeStr != null) {
-             if (aclTypeStr.equalsIgnoreCase(ACLType.Account.toString())) {
-                 aclType = ACLType.Account;
-             } else if (aclTypeStr.equalsIgnoreCase(ACLType.Domain.toString())) {
-                 aclType = ACLType.Domain;
-             } else {
-                 throw new InvalidParameterValueException("Incorrect aclType specified. Check the API documentation for supported types");
-             }
-             // In 3.0 all Shared networks should have aclType == Domain, all Isolated networks aclType==Account
-             if (ntwkOff.getGuestType() == GuestType.Isolated) {
-                 if (aclType != ACLType.Account) {
-                     throw new InvalidParameterValueException("AclType should be " + ACLType.Account + " for network of type " + Network.GuestType.Isolated);
-                 }
-             } else if (ntwkOff.getGuestType() == GuestType.Shared) {
-                 if (!(aclType == ACLType.Domain || aclType == ACLType.Account)) {
-                     throw new InvalidParameterValueException("AclType should be " + ACLType.Domain + " or " + 
-                 ACLType.Account + " for network of type " + Network.GuestType.Shared);
-                 }
-             }
-         } else {
-             if (ntwkOff.getGuestType() == GuestType.Isolated) {
-                 aclType = ACLType.Account;
-             } else if (ntwkOff.getGuestType() == GuestType.Shared) {
-                 aclType = ACLType.Domain;
-             }
-         }
- 
-         // Only Admin can create Shared networks
-         if (ntwkOff.getGuestType() == GuestType.Shared && !_accountMgr.isAdmin(caller.getType())) {
-             throw new InvalidParameterValueException("Only Admins can create network with guest type " + GuestType.Shared);
-         }
- 
-         // Check if the network is domain specific
-         if (aclType == ACLType.Domain) {
-             // only Admin can create domain with aclType=Domain
-             if (!_accountMgr.isAdmin(caller.getType())) {
-                 throw new PermissionDeniedException("Only admin can create networks with aclType=Domain");
-             }
- 
-             // only shared networks can be Domain specific
-             if (ntwkOff.getGuestType() != GuestType.Shared) {
-                 throw new InvalidParameterValueException("Only " + GuestType.Shared + " networks can have aclType=" + ACLType.Domain);
-             }
- 
-             if (domainId != null) {
-                 if (ntwkOff.getTrafficType() != TrafficType.Guest || ntwkOff.getGuestType() != Network.GuestType.Shared) {
-                     throw new InvalidParameterValueException("Domain level networks are supported just for traffic type "
-                 + TrafficType.Guest + " and guest type " + Network.GuestType.Shared);
-                 }
- 
-                 DomainVO domain = _domainDao.findById(domainId);
-                 if (domain == null) {                    
-                     throw new InvalidParameterValueException("Unable to find domain by specified id");
-                 }
-                 _accountMgr.checkAccess(caller, domain);
-             }
-             isDomainSpecific = true;
- 
-         } else if (subdomainAccess != null) {
-             throw new InvalidParameterValueException("Parameter subDomainAccess can be specified only with aclType=Domain");
-         }
-         Account owner = null;
-         if ((cmd.getAccountName() != null && domainId != null) || cmd.getProjectId() != null) {
-             owner = _accountMgr.finalizeOwner(caller, cmd.getAccountName(), domainId, cmd.getProjectId());
-         } else {
-             owner = caller;
-         }
- 
-         UserContext.current().setAccountId(owner.getAccountId());
- 
-         // VALIDATE IP INFO
-         // if end ip is not specified, default it to startIp
-         if (startIP != null) {
-             if (!NetUtils.isValidIp(startIP)) {
-                 throw new InvalidParameterValueException("Invalid format for the startIp parameter");
-             }
-             if (endIP == null) {
-                 endIP = startIP;
-             } else if (!NetUtils.isValidIp(endIP)) {
-                 throw new InvalidParameterValueException("Invalid format for the endIp parameter");
-             }
-         }
- 
-         if (startIP != null && endIP != null) {
-             if (!(gateway != null && netmask != null)) {
-                 throw new InvalidParameterValueException("gateway and netmask should be defined when startIP/endIP are passed in");
-             }
-         }
- 
-         String cidr = null;
-         if (gateway != null && netmask != null) {
-             if (!NetUtils.isValidIp(gateway)) {
-                 throw new InvalidParameterValueException("Invalid gateway");
-             }
-             if (!NetUtils.isValidNetmask(netmask)) {
-                 throw new InvalidParameterValueException("Invalid netmask");
-             }
- 
-             cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask);
-         }
- 
-         // Regular user can create Guest Isolated Source Nat enabled network only
-         if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL
-                 && (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");
-         }
- 
-         // Don't allow to specify vlan if the caller is a regular user
-         if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL && (ntwkOff.getSpecifyVlan() || vlanId != null)) {
-             throw new InvalidParameterValueException("Regular user is not allowed to specify vlanId");
-         }
- 
-         // For non-root admins check cidr limit - if it's allowed by global config value
-         if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN && cidr != null) {
- 
-             String[] cidrPair = cidr.split("\\/");
-             int cidrSize = Integer.valueOf(cidrPair[1]);
- 
-             if (cidrSize < _cidrLimit) {
-                 throw new InvalidParameterValueException("Cidr size can't be less than " + _cidrLimit);
-             }
-         }
- 
-         Collection<String> ntwkProviders = finalizeServicesAndProvidersForNetwork(ntwkOff, physicalNetworkId).values();
-         if (cidr != null && providersConfiguredForExternalNetworking(ntwkProviders)) {
-             if (ntwkOff.getGuestType() == GuestType.Shared && (zone.getNetworkType() == NetworkType.Advanced) &&
-                     isSharedNetworkOfferingWithServices(networkOfferingId)) {
-                 // validate if CIDR specified overlaps with any of the CIDR's allocated for isolated networks and shared networks in the zone
-                 checkSharedNetworkCidrOverlap(zoneId, pNtwk.getId(), cidr);
-             } else {
-             throw new InvalidParameterValueException("Cannot specify CIDR when using network offering with external devices!");
-         }
-         }
- 
- 
-         // Vlan is created in 2 cases - works in Advance zone only:
-         // 1) GuestType is Shared
-         // 2) GuestType is Isolated, but SourceNat service is disabled
-         boolean createVlan = (startIP != null && endIP != null && zone.getNetworkType() == NetworkType.Advanced
-                 && ((ntwkOff.getGuestType() == Network.GuestType.Shared)
-                 || (ntwkOff.getGuestType() == GuestType.Isolated && 
-                 !areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))));
- 
-         // Can add vlan range only to the network which allows it
-         if (createVlan && !ntwkOff.getSpecifyIpRanges()) {
-             InvalidParameterValueException ex = new InvalidParameterValueException("Network offering with specified id doesn't support adding multiple ip ranges");
-             ex.addProxyObject(ntwkOff, ntwkOff.getId(), "networkOfferingId");
-             String tablename = AnnotationHelper.getTableName(ntwkOff);
-             if (tablename != null) {
-                 ex.addProxyObject(tablename, ntwkOff.getId(), "networkOfferingId");
-             } else {
-                 s_logger.info("\nCould not retrieve table name (annotation) from " + tablename + " VO proxy object\n");
-             }
-             throw ex;   
-         }
- 
-         Transaction txn = Transaction.currentTxn();
-         txn.start();
- 
-         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);
-         }
- 
-         //Create guest network
-         Network network = null;
-         if (vpcId != null) {
-             if (!_configMgr.isOfferingForVpc(ntwkOff)){
-                 throw new InvalidParameterValueException("Network offering can't be used for VPC networks");
-             }
-             network = _vpcMgr.createVpcGuestNetwork(networkOfferingId, name, displayText, gateway, cidr, vlanId, 
-                     networkDomain, owner, sharedDomainId, pNtwk, zoneId, aclType, subdomainAccess, vpcId, caller);
-         } else {
-             if (_configMgr.isOfferingForVpc(ntwkOff)){
-                 throw new InvalidParameterValueException("Network offering can be used for VPC networks only");
-             }
-             network = createGuestNetwork(networkOfferingId, name, displayText, gateway, cidr, vlanId, 
-                     networkDomain, owner, sharedDomainId, pNtwk, zoneId, aclType, subdomainAccess, vpcId);
-         }  
- 
-         if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN && createVlan) {
-             // Create vlan ip range
-             _configMgr.createVlanAndPublicIpRange(pNtwk.getDataCenterId(), network.getId(), physicalNetworkId,
-                     false, null, startIP, endIP, gateway, netmask, vlanId, null);
-         }
- 
-         txn.commit();
 -   
 +
-         return network;
-     }
  
      @Override
      @DB
@@@ -2903,7 -1837,7 +1841,7 @@@
              List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
              if (!guestNetworks.isEmpty()) {
                  throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type "
--                                                        + NetworkType.Basic);
++                        + NetworkType.Basic);
              }
  
              // if zone is basic, only Shared network offerings w/o source nat service are allowed
@@@ -2967,21 -1901,20 +1905,20 @@@
              // For Isolated networks, don't allow to create network with vlan that already exists in the zone
              if (ntwkOff.getGuestType() == GuestType.Isolated) {
                  if (_networksDao.countByZoneAndUri(zoneId, uri) > 0) {
--                throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists in zone " + zoneId);
--            }
++                    throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists in zone " + zoneId);
++                }
              } else {
-                 //don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
-                 //shared network with same Vlan ID in the zone
-                 if (_networksDao.countByZoneUriAndGuestType(zoneId, uri, GuestType.Isolated) > 0 ||
-                         _networksDao.countByZoneUriAndGuestType(zoneId, uri, GuestType.Shared) > 0) {
-                     throw new InvalidParameterValueException("There is a isolated/shared network with vlan id: " + vlanId + " already exists " + "in zone " + zoneId);
+                 //don't allow to create Shared network with Vlan that already exists in the zone for Isolated networks
+                 if (_networksDao.countByZoneUriAndGuestType(zoneId, uri, GuestType.Isolated) > 0) {
+                     throw new InvalidParameterValueException("Isolated network with vlan " + vlanId + " already exists " +
+                             "in zone " + zoneId);
                  }
 -        }
++            }
          }
-         }
-         
+ 
          // If networkDomain is not specified, take it from the global configuration
-         if (areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
-             Map<Network.Capability, String> dnsCapabilities = getNetworkOfferingServiceCapabilities
+         if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
+             Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities
                      (_configMgr.getNetworkOffering(networkOfferingId), Service.Dns);
              String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
              if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
@@@ -3009,7 -1942,7 +1946,7 @@@
                      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', "
++                                        "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 \"-\"");
                      }
                  }
@@@ -3096,445 -2029,13 +2033,13 @@@
          return network;
      }
  
-     @Override
-     public List<? extends Network> searchForNetworks(ListNetworksCmd cmd) {
-         Long id = cmd.getId();
-         String keyword = cmd.getKeyword();
-         Long zoneId = cmd.getZoneId();
-         Account caller = UserContext.current().getCaller();
-         Long domainId = cmd.getDomainId();
-         String accountName = cmd.getAccountName();
-         String guestIpType = cmd.getGuestIpType();
-         String trafficType = cmd.getTrafficType();
-         Boolean isSystem = cmd.getIsSystem();
-         String aclType = cmd.getAclType();
-         Long projectId = cmd.getProjectId();
-         List<Long> permittedAccounts = new ArrayList<Long>();
-         String path = null;
-         Long physicalNetworkId = cmd.getPhysicalNetworkId();
-         List<String> supportedServicesStr = cmd.getSupportedServices();
-         Boolean restartRequired = cmd.getRestartRequired();
-         boolean listAll = cmd.listAll();
-         boolean isRecursive = cmd.isRecursive();
-         Boolean specifyIpRanges = cmd.getSpecifyIpRanges();
-         Long vpcId = cmd.getVpcId();
-         Boolean canUseForDeploy = cmd.canUseForDeploy();
-         Map<String, String> tags = cmd.getTags();
-         Boolean forVpc = cmd.getForVpc();
- 
-         // 1) default is system to false if not specified
-         // 2) reset parameter to false if it's specified by the regular user
-         if ((isSystem == null || caller.getType() == Account.ACCOUNT_TYPE_NORMAL) && id == null) {
-             isSystem = false;
-         }
- 
-         // Account/domainId parameters and isSystem are mutually exclusive
-         if (isSystem != null && isSystem && (accountName != null || domainId != null)) {
-             throw new InvalidParameterValueException("System network belongs to system, account and domainId parameters can't be specified");
-         }
- 
-         if (domainId != null) {
-             DomainVO domain = _domainDao.findById(domainId);
-             if (domain == null) {
-                 // see DomainVO.java
-                 throw new InvalidParameterValueException("Specified domain id doesn't exist in the system");
-             }
- 
-             _accountMgr.checkAccess(caller, domain);
-             if (accountName != null) {
-                 Account owner = _accountMgr.getActiveAccountByName(accountName, domainId);
-                 if (owner == null) {
-                     // see DomainVO.java
-                     throw new InvalidParameterValueException("Unable to find account " + accountName + " in specified domain");
-                 }
 -    
 +
-                 _accountMgr.checkAccess(caller, null, true, owner);
-                 permittedAccounts.add(owner.getId());
-             }
-         }
  
-         if (!_accountMgr.isAdmin(caller.getType()) || (!listAll && (projectId != null && projectId.longValue() != -1 && domainId == null))) {
-             permittedAccounts.add(caller.getId());
-             domainId = caller.getDomainId();
-         }
+     @Override
+     @DB
+     public boolean shutdownNetwork(long networkId, ReservationContext context, boolean cleanupElements) {
+         boolean result = false;
  
-         // set project information
-         boolean skipProjectNetworks = true;
-         if (projectId != null) {
-             if (projectId.longValue() == -1) {
-                 if (!_accountMgr.isAdmin(caller.getType())) {
-                 permittedAccounts.addAll(_projectMgr.listPermittedProjectAccounts(caller.getId()));
-                 }
-             } else {
-                 permittedAccounts.clear();
-                 Project project = _projectMgr.getProject(projectId);
-                 if (project == null) {                    
-                     throw new InvalidParameterValueException("Unable to find project by specified id");
-                 }
-                 if (!_projectMgr.canAccessProjectAccount(caller, project.getProjectAccountId())) {
-                     // getProject() returns type ProjectVO.
-                     InvalidParameterValueException ex = new InvalidParameterValueException("Account " + caller + " cannot access specified project id");
-                     ex.addProxyObject(project, projectId, "projectId");                    
-                     throw ex;
-                 }
-                 permittedAccounts.add(project.getProjectAccountId());
-             }
-             skipProjectNetworks = false;
-         }
- 
-         if (domainId != null) {
-             path = _domainDao.findById(domainId).getPath();
-         } else {
-         path = _domainDao.findById(caller.getDomainId()).getPath();
-         } 
-         
-         if (listAll && domainId == null) {
-             isRecursive = true;
-         }
- 
-         Filter searchFilter = new Filter(NetworkVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal());
-         SearchBuilder<NetworkVO> sb = _networksDao.createSearchBuilder();
-         
-         if (forVpc != null) {
-             if (forVpc) {
-                 sb.and("vpc", sb.entity().getVpcId(), Op.NNULL);
-             } else {
-                 sb.and("vpc", sb.entity().getVpcId(), Op.NULL);
-             }
-         }
- 
-         // Don't display networks created of system network offerings
-         SearchBuilder<NetworkOfferingVO> networkOfferingSearch = _networkOfferingDao.createSearchBuilder();
-         networkOfferingSearch.and("systemOnly", networkOfferingSearch.entity().isSystemOnly(), SearchCriteria.Op.EQ);
-         if (isSystem != null && isSystem) {
-             networkOfferingSearch.and("trafficType", networkOfferingSearch.entity().getTrafficType(), SearchCriteria.Op.EQ);
-         }
-         sb.join("networkOfferingSearch", networkOfferingSearch, sb.entity().getNetworkOfferingId(), networkOfferingSearch.entity().getId(), JoinBuilder.JoinType.INNER);
- 
-         SearchBuilder<DataCenterVO> zoneSearch = _dcDao.createSearchBuilder();
-         zoneSearch.and("networkType", zoneSearch.entity().getNetworkType(), SearchCriteria.Op.EQ);
-         sb.join("zoneSearch", zoneSearch, sb.entity().getDataCenterId(), zoneSearch.entity().getId(), JoinBuilder.JoinType.INNER);
-         sb.and("removed", sb.entity().getRemoved(), Op.NULL);
- 
-         if (tags != null && !tags.isEmpty()) {
-             SearchBuilder<ResourceTagVO> tagSearch = _resourceTagDao.createSearchBuilder();
-             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();
-             }
-             tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ);
-             sb.groupBy(sb.entity().getId());
-             sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER);
-         }
- 
-         if (permittedAccounts.isEmpty()) {
-             SearchBuilder<DomainVO> domainSearch = _domainDao.createSearchBuilder();
-             domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE);
-             sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER);
-         }
- 
- 
-             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);
- 
-         List<NetworkVO> networksToReturn = new ArrayList<NetworkVO>();
- 
-         if (isSystem == null || !isSystem) {
-             if (!permittedAccounts.isEmpty()) {
-                 //get account level networks
-                 networksToReturn.addAll(listAccountSpecificNetworks(
-                         buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, 
-                                 physicalNetworkId, aclType, skipProjectNetworks, restartRequired, specifyIpRanges, vpcId, tags), searchFilter,
-                         permittedAccounts));
-                 //get domain level networks
-                 if (domainId != null) {
-                     networksToReturn
-                     .addAll(listDomainLevelNetworks(
-                             buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType,
-                                     physicalNetworkId, aclType, true, restartRequired, specifyIpRanges, vpcId, tags), searchFilter,
-                                     domainId, false));
-                 }
-             } else {
-                 //add account specific networks
-                 networksToReturn.addAll(listAccountSpecificNetworksByDomainPath(
-                         buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, 
-                                 physicalNetworkId, aclType, skipProjectNetworks, restartRequired, specifyIpRanges, vpcId, tags), searchFilter, path,
-                         isRecursive));
-                 //add domain specific networks of domain + parent domains
-                 networksToReturn.addAll(listDomainSpecificNetworksByDomainPath(
-                         buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, 
-                                 physicalNetworkId, aclType, skipProjectNetworks, restartRequired, specifyIpRanges, vpcId, tags), searchFilter, path,
-                                 isRecursive));
-                 //add networks of subdomains
-                 if (domainId == null) {
-                     networksToReturn
-                     .addAll(listDomainLevelNetworks(
-                             buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType,
-                                     physicalNetworkId, aclType, true, restartRequired, specifyIpRanges, vpcId, tags), searchFilter,
-                                     caller.getDomainId(), true));
-                 }
-             }
-         } else {
-             networksToReturn = _networksDao.search(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId,
-                     guestIpType, trafficType, physicalNetworkId, null, skipProjectNetworks, restartRequired, specifyIpRanges, vpcId, tags),
-                     searchFilter);
-         }
- 
-         if (supportedServicesStr != null && !supportedServicesStr.isEmpty() && !networksToReturn.isEmpty()) {
-             List<NetworkVO> supportedNetworks = new ArrayList<NetworkVO>();
-             Service[] suppportedServices = new Service[supportedServicesStr.size()];
-             int i = 0;
-             for (String supportedServiceStr : supportedServicesStr) {
-                 Service service = Service.getService(supportedServiceStr);
-                 if (service == null) {
-                     throw new InvalidParameterValueException("Invalid service specified " + supportedServiceStr);
-                 } else {
-               

<TRUNCATED>
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/10d9c019/server/src/com/cloud/network/element/CloudZonesNetworkElement.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/10d9c019/server/src/com/cloud/network/element/VirtualRouterElement.java
----------------------------------------------------------------------


Mime
View raw message