cloudstack-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From kous...@apache.org
Subject [2/3] CLOUDSTACK-702: Multiple ip ranges in different subnets.
Date Mon, 13 May 2013 11:38:56 GMT
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/052c24c4/scripts/vm/hypervisor/xenserver/vmops
----------------------------------------------------------------------
diff --git a/scripts/vm/hypervisor/xenserver/vmops b/scripts/vm/hypervisor/xenserver/vmops
index 30b5300..66cde4f 100755
--- a/scripts/vm/hypervisor/xenserver/vmops
+++ b/scripts/vm/hypervisor/xenserver/vmops
@@ -355,7 +355,47 @@ def setLoadBalancerRule(session, args):
         txt = '' 
 
     return txt
-    
+@echo
+def configdnsmasq(session, args):
+    routerip = args['routerip']
+    filepath = args['filepath']
+    target   = "root@"+routerip
+    try:
+       util.pread2(['ssh','-p','3922','-q','-o','StrictHostKeyChecking=no','-i','/root/.ssh/id_rsa.cloud',target,'/root/dnsmasq.sh',filepath])
+       txt='success'
+    except:
+       util.SMlog("failed to config dnsmasq server")
+       txt=''
+    return txt
+
+@echo
+def createipAlias(session, args):
+    args = args['args']
+    cmd = args.split(' ')
+    cmd.insert(0, "/opt/xensource/bin/createipAlias.sh")
+    cmd.insert(0, "bin/bash")
+    try:
+       txt=util.pread2(cmd)
+       txt='success'
+    except:
+       util.SMlog("failed to create ip alias on router vm")
+       txt=''
+    return txt
+
+@echo
+def deleteipAlias(session, args):
+    args = args['args']
+    cmd = args.split(' ')
+    cmd.insert(0, "/opt/xensource/bin/deleteipAlias.sh")
+    cmd.insert(0, "bin/bash")
+    try:
+       txt=util.pread2(cmd)
+       txt='success'
+    except:
+       util.SMlog("failed to create ip alias on router vm")
+       txt=''
+    return txt
+
 @echo
 def createFile(session, args):
     file_path = args['filepath']
@@ -1672,6 +1712,9 @@ if __name__ == "__main__":
                             "destroy_network_rules_for_vm":destroy_network_rules_for_vm, 
                             "default_network_rules_systemvm":default_network_rules_systemvm, 
                             "network_rules_vmSecondaryIp":network_rules_vmSecondaryIp,
+                            "createipAlias":createipAlias,
+                            "configdnsmasq":configdnsmasq,
+                            "deleteipAlias":deleteipAlias,
                             "get_rule_logs_for_vms":get_rule_logs_for_vms, 
 			    "add_to_VCPUs_params_live":add_to_VCPUs_params_live,
                             "setLinkLocalIP":setLinkLocalIP,

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/052c24c4/scripts/vm/hypervisor/xenserver/xcpserver/patch
----------------------------------------------------------------------
diff --git a/scripts/vm/hypervisor/xenserver/xcpserver/patch b/scripts/vm/hypervisor/xenserver/xcpserver/patch
index b7961bb..bfecd0c 100644
--- a/scripts/vm/hypervisor/xenserver/xcpserver/patch
+++ b/scripts/vm/hypervisor/xenserver/xcpserver/patch
@@ -40,6 +40,8 @@ make_migratable.sh=..,0755,/opt/xensource/bin
 setup_iscsi.sh=..,0755,/opt/xensource/bin
 pingtest.sh=../../..,0755,/opt/xensource/bin
 dhcp_entry.sh=../../../../network/domr/,0755,/opt/xensource/bin
+createipAlias.sh=../../..,0755,/opt/xensource/bin
+deleteipAlias.sh=../../..,0755,/opt/xensource/bin
 router_proxy.sh=../../../../network/domr/,0755,/opt/xensource/bin
 vm_data.sh=../../../../network/domr/,0755,/opt/xensource/bin
 save_password_to_domr.sh=../../../../network/domr/,0755,/opt/xensource/bin

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/052c24c4/scripts/vm/hypervisor/xenserver/xenserver56/patch
----------------------------------------------------------------------
diff --git a/scripts/vm/hypervisor/xenserver/xenserver56/patch b/scripts/vm/hypervisor/xenserver/xenserver56/patch
index 36dba3d..1be14ea 100644
--- a/scripts/vm/hypervisor/xenserver/xenserver56/patch
+++ b/scripts/vm/hypervisor/xenserver/xenserver56/patch
@@ -38,6 +38,8 @@ make_migratable.sh=..,0755,/opt/xensource/bin
 setup_iscsi.sh=..,0755,/opt/xensource/bin
 cloud-setup-bonding.sh=..,0755,/opt/xensource/bin
 pingtest.sh=../../..,0755,/opt/xensource/bin
+createipAlias.sh=../../..,0755,/opt/xensource/bin
+deleteipAlias.sh=../../..,0755,/opt/xensource/bin
 dhcp_entry.sh=../../../../network/domr/,0755,/opt/xensource/bin
 vm_data.sh=../../../../network/domr/,0755,/opt/xensource/bin
 save_password_to_domr.sh=../../../../network/domr/,0755,/opt/xensource/bin

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/052c24c4/scripts/vm/hypervisor/xenserver/xenserver56fp1/patch
----------------------------------------------------------------------
diff --git a/scripts/vm/hypervisor/xenserver/xenserver56fp1/patch b/scripts/vm/hypervisor/xenserver/xenserver56fp1/patch
index d20e60f..dd31e44 100644
--- a/scripts/vm/hypervisor/xenserver/xenserver56fp1/patch
+++ b/scripts/vm/hypervisor/xenserver/xenserver56fp1/patch
@@ -37,6 +37,8 @@ setupxenserver.sh=..,0755,/opt/xensource/bin
 make_migratable.sh=..,0755,/opt/xensource/bin
 setup_iscsi.sh=..,0755,/opt/xensource/bin
 pingtest.sh=../../..,0755,/opt/xensource/bin
+createipAlias.sh=../../..,0755,/opt/xensource/bin
+deleteipAlias.sh=../../..,0755,/opt/xensource/bin
 dhcp_entry.sh=../../../../network/domr/,0755,/opt/xensource/bin
 vm_data.sh=../../../../network/domr/,0755,/opt/xensource/bin
 save_password_to_domr.sh=../../../../network/domr/,0755,/opt/xensource/bin

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/052c24c4/scripts/vm/hypervisor/xenserver/xenserver60/patch
----------------------------------------------------------------------
diff --git a/scripts/vm/hypervisor/xenserver/xenserver60/patch b/scripts/vm/hypervisor/xenserver/xenserver60/patch
index c9125f4..787f474 100644
--- a/scripts/vm/hypervisor/xenserver/xenserver60/patch
+++ b/scripts/vm/hypervisor/xenserver/xenserver60/patch
@@ -40,6 +40,8 @@ id_rsa.cloud=../../../systemvm,0600,/root/.ssh
 network_info.sh=..,0755,/opt/xensource/bin
 setupxenserver.sh=..,0755,/opt/xensource/bin
 make_migratable.sh=..,0755,/opt/xensource/bin
+createipAlias.sh=../../..,0755,/opt/xensource/bin
+deleteipAlias.sh=../../..,0755,/opt/xensource/bin
 setup_iscsi.sh=..,0755,/opt/xensource/bin
 pingtest.sh=../../..,0755,/opt/xensource/bin
 dhcp_entry.sh=../../../../network/domr/,0755,/opt/xensource/bin

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/052c24c4/server/src/com/cloud/configuration/ConfigurationManager.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/configuration/ConfigurationManager.java b/server/src/com/cloud/configuration/ConfigurationManager.java
index d2f8319..b73e71d 100755
--- a/server/src/com/cloud/configuration/ConfigurationManager.java
+++ b/server/src/com/cloud/configuration/ConfigurationManager.java
@@ -150,8 +150,6 @@ public interface ConfigurationManager extends ConfigurationService, Manager {
      */
     boolean deleteVlanAndPublicIpRange(long userId, long vlanDbId, Account caller);
 
-    boolean releasePublicIpRange(long userId, long vlanDbId, Account caller);
-
     /**
      * Converts a comma separated list of tags to a List
      * 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/052c24c4/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
index fdc0ffb..ce2493c 100755
--- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
+++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
@@ -80,7 +80,20 @@ import com.cloud.api.ApiDBUtils;
 import com.cloud.capacity.dao.CapacityDao;
 import com.cloud.configuration.Resource.ResourceType;
 import com.cloud.configuration.dao.ConfigurationDao;
+import com.cloud.dc.AccountVlanMapVO;
+import com.cloud.dc.ClusterDetailsDao;
+import com.cloud.dc.ClusterDetailsVO;
+import com.cloud.dc.ClusterVO;
+import com.cloud.dc.DataCenter;
 import com.cloud.dc.DataCenter.NetworkType;
+import com.cloud.dc.DataCenterIpAddressVO;
+import com.cloud.dc.DataCenterLinkLocalIpAddressVO;
+import com.cloud.dc.DataCenterVO;
+import com.cloud.dc.DcDetailVO;
+import com.cloud.dc.HostPodVO;
+import com.cloud.dc.Pod;
+import com.cloud.dc.PodVlanMapVO;
+import com.cloud.dc.Vlan;
 import com.cloud.dc.Vlan.VlanType;
 import com.cloud.dc.VlanVO;
 import com.cloud.dc.dao.AccountVlanMapDao;
@@ -99,14 +112,18 @@ import com.cloud.domain.DomainVO;
 import com.cloud.domain.dao.DomainDao;
 import com.cloud.event.ActionEvent;
 import com.cloud.event.EventTypes;
+import com.cloud.event.UsageEventUtils;
 import com.cloud.exception.ConcurrentOperationException;
+import com.cloud.exception.InsufficientAddressCapacityException;
 import com.cloud.exception.InsufficientCapacityException;
 import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.exception.MissingParameterValueException;
 import com.cloud.exception.PermissionDeniedException;
 import com.cloud.exception.ResourceAllocationException;
 import com.cloud.exception.ResourceUnavailableException;
 import com.cloud.host.HostVO;
 import com.cloud.hypervisor.Hypervisor.HypervisorType;
+import com.cloud.network.IpAddress;
 import com.cloud.network.Network;
 import com.cloud.network.Network.Capability;
 import com.cloud.network.Network.GuestType;
@@ -118,6 +135,7 @@ import com.cloud.network.NetworkService;
 import com.cloud.network.Networks.BroadcastDomainType;
 import com.cloud.network.Networks.TrafficType;
 import com.cloud.network.PhysicalNetwork;
+import com.cloud.network.addr.PublicIp;
 import com.cloud.network.dao.FirewallRulesDao;
 import com.cloud.network.dao.IPAddressDao;
 import com.cloud.network.dao.IPAddressVO;
@@ -128,6 +146,7 @@ import com.cloud.network.dao.PhysicalNetworkTrafficTypeDao;
 import com.cloud.network.dao.PhysicalNetworkTrafficTypeVO;
 import com.cloud.network.dao.PhysicalNetworkVO;
 import com.cloud.network.rules.LoadBalancerContainer.Scheme;
+import com.cloud.network.element.DhcpServiceProvider;
 import com.cloud.network.vpc.VpcManager;
 import com.cloud.offering.DiskOffering;
 import com.cloud.offering.NetworkOffering;
@@ -154,6 +173,14 @@ import com.cloud.storage.s3.S3Manager;
 import com.cloud.storage.secondary.SecondaryStorageVmManager;
 import com.cloud.storage.swift.SwiftManager;
 import com.cloud.test.IPRangeConfig;
+import com.cloud.user.Account;
+import com.cloud.user.AccountDetailVO;
+import com.cloud.user.AccountDetailsDao;
+import com.cloud.user.AccountManager;
+import com.cloud.user.AccountVO;
+import com.cloud.user.ResourceLimitService;
+import com.cloud.user.User;
+import com.cloud.user.UserContext;
 import com.cloud.user.dao.AccountDao;
 import com.cloud.utils.NumbersUtil;
 import com.cloud.utils.StringUtils;
@@ -165,10 +192,65 @@ import com.cloud.utils.db.SearchCriteria;
 import com.cloud.utils.db.Transaction;
 import com.cloud.utils.exception.CloudRuntimeException;
 import com.cloud.utils.net.NetUtils;
+import com.cloud.vm.NicIpAlias;
 import com.cloud.vm.VirtualMachine;
 import com.cloud.vm.dao.NicDao;
-
+import com.cloud.vm.dao.NicIpAliasDao;
+import com.cloud.vm.dao.NicIpAliasVO;
+import com.cloud.vm.dao.NicSecondaryIpDao;
 import edu.emory.mathcs.backport.java.util.Arrays;
+import org.apache.cloudstack.acl.SecurityChecker;
+import org.apache.cloudstack.api.ApiConstants.LDAPParams;
+import org.apache.cloudstack.api.command.admin.config.UpdateCfgCmd;
+import org.apache.cloudstack.api.command.admin.ldap.LDAPConfigCmd;
+import org.apache.cloudstack.api.command.admin.ldap.LDAPRemoveCmd;
+import org.apache.cloudstack.api.command.admin.network.CreateNetworkOfferingCmd;
+import org.apache.cloudstack.api.command.admin.network.DeleteNetworkOfferingCmd;
+import org.apache.cloudstack.api.command.admin.network.UpdateNetworkOfferingCmd;
+import org.apache.cloudstack.api.command.admin.offering.CreateDiskOfferingCmd;
+import org.apache.cloudstack.api.command.admin.offering.CreateServiceOfferingCmd;
+import org.apache.cloudstack.api.command.admin.offering.DeleteDiskOfferingCmd;
+import org.apache.cloudstack.api.command.admin.offering.DeleteServiceOfferingCmd;
+import org.apache.cloudstack.api.command.admin.offering.UpdateDiskOfferingCmd;
+import org.apache.cloudstack.api.command.admin.offering.UpdateServiceOfferingCmd;
+import org.apache.cloudstack.api.command.admin.pod.DeletePodCmd;
+import org.apache.cloudstack.api.command.admin.pod.UpdatePodCmd;
+import org.apache.cloudstack.api.command.admin.vlan.CreateVlanIpRangeCmd;
+import org.apache.cloudstack.api.command.admin.vlan.DedicatePublicIpRangeCmd;
+import org.apache.cloudstack.api.command.admin.vlan.DeleteVlanIpRangeCmd;
+import org.apache.cloudstack.api.command.admin.vlan.ReleasePublicIpRangeCmd;
+import org.apache.cloudstack.api.command.admin.zone.CreateZoneCmd;
+import org.apache.cloudstack.api.command.admin.zone.DeleteZoneCmd;
+import org.apache.cloudstack.api.command.admin.zone.UpdateZoneCmd;
+import org.apache.cloudstack.api.command.user.network.ListNetworkOfferingsCmd;
+import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
+import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailVO;
+import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailsDao;
+import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
+import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
+
+import javax.ejb.Local;
+import javax.inject.Inject;
+import javax.naming.ConfigurationException;
+import javax.naming.Context;
+import javax.naming.NamingException;
+import javax.naming.directory.DirContext;
+import javax.naming.directory.InitialDirContext;
+import java.net.URI;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
 
 @Component
 @Local(value = { ConfigurationManager.class, ConfigurationService.class })
@@ -259,6 +341,10 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
     AccountDetailsDao _accountDetailsDao;
     @Inject
     PrimaryDataStoreDao _storagePoolDao;
+    @Inject
+    NicSecondaryIpDao _nicSecondaryIpDao;
+    @Inject
+    NicIpAliasDao _nicIpAliasDao;
 
     // FIXME - why don't we have interface for DataCenterLinkLocalIpAddressDao?
     @Inject protected DataCenterLinkLocalIpAddressDao _LinkLocalIpAllocDao;
@@ -2226,8 +2312,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
         Long podId = cmd.getPodId();
         String startIP = cmd.getStartIp();
         String endIP = cmd.getEndIp();
-        String vlanGateway = cmd.getGateway();
-        String vlanNetmask = cmd.getNetmask();
+        String newVlanGateway = cmd.getGateway();
+        String newVlanNetmask = cmd.getNetmask();
         Long userId = UserContext.current().getCallerUserId();
         String vlanId = cmd.getVlan();
         Boolean forVirtualNetwork = cmd.isForVirtualNetwork();
@@ -2385,6 +2471,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
             }
         }
 
+        boolean sameSubnet=false;
         // Can add vlan range only to the network which allows it
         if (!network.getSpecifyIpRanges()) {
             throw new InvalidParameterValueException("Network " + network + " doesn't support adding ip ranges");
@@ -2396,44 +2483,30 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
                     throw new InvalidParameterValueException("Can execute createVLANIpRanges on shared guest network, but type of this guest network "
                             + network.getId() + " is " + network.getGuestType());
                 }
+
                 List<VlanVO> vlans = _vlanDao.listVlansByNetworkId(network.getId());
+                VlanVO vlan = vlans.get(0);
                 if ( vlans != null && vlans.size() > 0 ) {
-                    VlanVO vlan = vlans.get(0);
                     if ( vlanId == null ) {
                         vlanId = vlan.getVlanTag();
                     } else if ( vlan.getVlanTag() != vlanId ) {
                         throw new InvalidParameterValueException("there is already one vlan " + vlan.getVlanTag() + " on network :" +
                                 + network.getId() + ", only one vlan is allowed on guest network");
                     }
-                    if (ipv4) {
-                        vlanGateway = vlan.getVlanGateway();
-                        vlanNetmask = vlan.getVlanNetmask();
-                        // Check if ip addresses are in network range
-                        if (!NetUtils.sameSubnet(startIP, vlanGateway, vlanNetmask)) {
-                            throw new InvalidParameterValueException("Start ip is not in vlan range!");
-                        }
-                        if (!NetUtils.sameSubnet(endIP, vlanGateway, vlanNetmask)) {
-                            throw new InvalidParameterValueException("End ip is not in vlan range!");
-                        }
-                    }
-                    if (ipv6) {
-                        if (ip6Gateway != null && !ip6Gateway.equals(network.getIp6Gateway())) {
-                            throw new InvalidParameterValueException("The input gateway " + ip6Gateway + " is not same as network gateway " + network.getIp6Gateway());
-                        }
-                        if (ip6Cidr != null && !ip6Cidr.equals(network.getIp6Cidr())) {
-                            throw new InvalidParameterValueException("The input cidr " + ip6Cidr + " is not same as network ciddr " + network.getIp6Cidr());
-                        }
-                        ip6Gateway = network.getIp6Gateway();
-                        ip6Cidr = network.getIp6Cidr();
-                        _networkModel.checkIp6Parameters(startIPv6, endIPv6, ip6Gateway, ip6Cidr);
-                    }
                 }
-            } else if (network.getTrafficType() == TrafficType.Management) {
-                throw new InvalidParameterValueException("Cannot execute createVLANIpRanges on management network");
+               sameSubnet=validateIpRange(startIP, endIP, newVlanGateway, newVlanNetmask, vlans, ipv4, ipv6, ip6Gateway, ip6Cidr,startIPv6, endIPv6, network);
+
             }
+
+        } else if (network.getTrafficType() == TrafficType.Management) {
+                      throw new InvalidParameterValueException("Cannot execute createVLANIpRanges on management network");
+        }
+        else if (zone.getNetworkType() == NetworkType.Basic){
+                 List<VlanVO> vlans = _vlanDao.listVlansByNetworkId(network.getId());
+                 sameSubnet=validateIpRange(startIP,endIP,newVlanGateway, newVlanNetmask, vlans, ipv4, ipv6, ip6Gateway, ip6Cidr, startIPv6, endIPv6, network);
         }
 
-        if (zoneId == null || (ipv4 && (vlanGateway == null || vlanNetmask == null)) || (ipv6 && (ip6Gateway == null || ip6Cidr == null))) {
+        if (zoneId == null || (ipv4 && (newVlanGateway == null || newVlanNetmask == null)) || (ipv6 && (ip6Gateway == null || ip6Cidr == null))) {
             throw new InvalidParameterValueException("Gateway, netmask and zoneId have to be passed in for virtual and direct untagged networks");
         }
 
@@ -2446,7 +2519,6 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
                 _resourceLimitMgr.checkResourceLimit(vlanOwner, ResourceType.public_ip, accountIpRange);
             }
         }
-
         // Check if the IP range overlaps with the private ip
         if (ipv4) {
         	checkOverlapPrivateIpRange(zoneId, startIP, endIP);
@@ -2455,13 +2527,75 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
         txn.start();
 
         Vlan vlan = createVlanAndPublicIpRange(zoneId, networkId, physicalNetworkId, forVirtualNetwork, podId, startIP, 
-                endIP, vlanGateway, vlanNetmask, vlanId, vlanOwner, startIPv6, endIPv6, ip6Gateway, ip6Cidr);
+                endIP, newVlanGateway, newVlanNetmask, vlanId, vlanOwner, startIPv6, endIPv6, ip6Gateway, ip6Cidr);
+        //create an entry in the nic_secondary table. This will be the new gateway that will be configured on the corresponding routervm.
+        if (sameSubnet == false) {
+           s_logger.info("adding a new subnet to the network "+network.getId());
+        }
 
         txn.commit();
 
         return vlan;
     }
 
+    public boolean validateIpRange(String startIP, String endIP, String newVlanGateway, String newVlanNetmask, List<VlanVO> vlans, boolean ipv4, boolean ipv6, String ip6Gateway, String ip6Cidr, String startIPv6, String endIPv6, Network network) {
+        String vlanGateway;
+        String vlanNetmask;
+        boolean sameSubnet = false;
+        if ( vlans != null && vlans.size() > 0 ) {
+
+            for (VlanVO vlan : vlans) {
+                if (ipv4) {
+                    vlanGateway = vlan.getVlanGateway();
+                    vlanNetmask = vlan.getVlanNetmask();
+                    // Check if ip addresses are in network range
+                    if (!NetUtils.sameSubnet(startIP, vlanGateway, vlanNetmask)) {
+                        if (!NetUtils.sameSubnet(endIP, vlanGateway, vlanNetmask)) {
+                                // check if the the new subnet is not a superset of the existing subnets.
+                                if (NetUtils.isNetworkAWithinNetworkB(NetUtils.getCidrFromGatewayAndNetmask(vlanGateway,vlanNetmask), NetUtils.ipAndNetMaskToCidr(startIP, newVlanNetmask))){
+                                    throw new InvalidParameterValueException ("The new subnet is a superset of the existing subnet");
+                                }
+                                // check if the new subnet is not a subset of the existing subnet.
+                                if (NetUtils.isNetworkAWithinNetworkB(NetUtils.ipAndNetMaskToCidr(startIP, newVlanNetmask), NetUtils.getCidrFromGatewayAndNetmask(vlanGateway,vlanNetmask))){
+                                    throw  new InvalidParameterValueException("The new subnet is a subset of the existing subnet");
+                                }
+                        }
+                    } else if (NetUtils.sameSubnet(endIP, vlanGateway, vlanNetmask)){
+                        // trying to add to the same subnet.
+                        sameSubnet = true;
+                        if (newVlanGateway == null) {
+                            newVlanGateway = vlanGateway;
+                        }
+                        if (!newVlanGateway.equals(vlanGateway)){
+                            throw new InvalidParameterValueException("The gateway of the ip range is not same as the gateway of the subnet.");
+                        }
+                        break;
+                    }
+                    else {
+                        throw new InvalidParameterValueException("Start ip and End ip is not in vlan range!");
+                    }
+                }
+                if (ipv6) {
+                    if (ip6Gateway != null && !ip6Gateway.equals(network.getIp6Gateway())) {
+                       throw new InvalidParameterValueException("The input gateway " + ip6Gateway + " is not same as network gateway " + network.getIp6Gateway());
+                    }
+                    if (ip6Cidr != null && !ip6Cidr.equals(network.getIp6Cidr())) {
+                       throw new InvalidParameterValueException("The input cidr " + ip6Cidr + " is not same as network ciddr " + network.getIp6Cidr());
+                    }
+                    ip6Gateway = network.getIp6Gateway();
+                    ip6Cidr = network.getIp6Cidr();
+                    _networkModel.checkIp6Parameters(startIPv6, endIPv6, ip6Gateway, ip6Cidr);
+                }
+            }
+            if (sameSubnet == false) {
+                if (newVlanGateway ==null)  {
+                    throw  new MissingParameterValueException("The gateway for the new subnet is not specified.");
+                }
+            }
+        }
+        return  sameSubnet;
+    }
+
     @Override
     @DB
     public Vlan createVlanAndPublicIpRange(long zoneId, long networkId, long physicalNetworkId, boolean forVirtualNetwork, Long podId, 
@@ -2681,20 +2815,6 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
             throw new InvalidParameterValueException("The VLAN tag " + vlanId + " is already being used for the guest network in zone " + zone.getName());
         }
 
-        // For untagged vlan check if vlan per pod already exists. If yes,
-        // verify that new vlan range has the same netmask and gateway
-        if (zone.getNetworkType() == NetworkType.Basic && vlanId.equalsIgnoreCase(Vlan.UNTAGGED) && podId != null) {
-            List<VlanVO> podVlans = _vlanDao.listVlansForPodByType(podId, VlanType.DirectAttached);
-            if (podVlans != null && !podVlans.isEmpty()) {
-                VlanVO podVlan = podVlans.get(0);
-                if (!podVlan.getVlanNetmask().equals(vlanNetmask)) {
-                    throw new InvalidParameterValueException("Vlan netmask is different from the netmask of Untagged vlan id=" + podVlan.getId() + " existing in the pod " + podId);
-                } else if (!podVlan.getVlanGateway().equals(vlanGateway)) {
-                    throw new InvalidParameterValueException("Vlan gateway is different from the gateway of Untagged vlan id=" + podVlan.getId() + " existing in the pod " + podId);
-                }
-            }
-        }
-
         String ipRange = null;
         
         if (ipv4) {
@@ -2744,28 +2864,28 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
 
     @Override
     @DB
-    public boolean deleteVlanAndPublicIpRange(long userId, long vlanDbId, Account caller) {
-        VlanVO vlan = _vlanDao.findById(vlanDbId);
-        if (vlan == null) {
+    public boolean deleteVlanAndPublicIpRange(long userId, long vlanDbId, Account caller)  {
+        VlanVO vlanRange = _vlanDao.findById(vlanDbId);
+        if (vlanRange == null) {
             throw new InvalidParameterValueException("Please specify a valid IP range id.");
         }
         
         boolean isAccountSpecific = false;
-        List<AccountVlanMapVO> acctVln = _accountVlanMapDao.listAccountVlanMapsByVlan(vlan.getId());
+        List<AccountVlanMapVO> acctVln = _accountVlanMapDao.listAccountVlanMapsByVlan(vlanRange.getId());
         // Check for account wide pool. It will have an entry for account_vlan_map.
         if (acctVln != null && !acctVln.isEmpty()) {
             isAccountSpecific = true;
         }
 
         // Check if the VLAN has any allocated public IPs
-        long allocIpCount = _publicIpAddressDao.countIPs(vlan.getDataCenterId(), vlanDbId, true);
+        long allocIpCount = _publicIpAddressDao.countIPs(vlanRange.getDataCenterId(), vlanDbId, true);
         List<IPAddressVO> ips = _publicIpAddressDao.listByVlanId(vlanDbId);
         boolean success = true;
         if (allocIpCount > 0) {
             if (isAccountSpecific) { 
                 try {
-                    vlan = _vlanDao.acquireInLockTable(vlanDbId, 30);
-                    if (vlan == null) {
+                    vlanRange = _vlanDao.acquireInLockTable(vlanDbId, 30);
+                    if (vlanRange == null) {
                         throw new CloudRuntimeException("Unable to acquire vlan configuration: " + vlanDbId);
                     }
 
@@ -2798,33 +2918,127 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
                 } finally {
                     _vlanDao.releaseFromLockTable(vlanDbId);
                 } 
-            } else {
-                throw new InvalidParameterValueException("The IP range can't be deleted because it has allocated public IP addresses.");
             }
         }
 
         if (success) {
             // Delete all public IPs in the VLAN
-            if (!deletePublicIPRange(vlanDbId)) {
-                return false;
-            }
-
             // if ip range is dedicated to an account generate usage events for release of every ip in the range
             if(isAccountSpecific) {
                 for (IPAddressVO ip : ips) {
                     UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NET_IP_RELEASE, acctVln.get(0).getId(),
-                            ip.getDataCenterId(), ip.getId(), ip.getAddress().toString(), ip.isSourceNat(), vlan.getVlanType().toString(),
+                            ip.getDataCenterId(), ip.getId(), ip.getAddress().toString(), ip.isSourceNat(), vlanRange.getVlanType().toString(),
                             ip.getSystem(), ip.getClass().getName(), ip.getUuid());
                 }
             }
+            if (_networkModel.areServicesSupportedInNetwork(vlanRange.getNetworkId(), Service.Dhcp)) {
+                Network network = _networkDao.findById(vlanRange.getNetworkId());
+                DhcpServiceProvider dhcpServiceProvider = _networkMgr.getDhcpServiceProvider(network);
+                if (!dhcpServiceProvider.getProvider().getName().equalsIgnoreCase(Provider.VirtualRouter.getName())) {
+                    if (!deletePublicIPRange(vlanDbId)) {
+                        return false;
+                    }
+                    _vlanDao.expunge(vlanDbId);
+                    return  true;
+                }
+                //search if the vlan has any allocated ips.
+                boolean aliasIpBelongsToThisVlan = false;
+                long freeIpsInsubnet = 0;
+                NicIpAliasVO ipAlias = null;
+                allocIpCount = _publicIpAddressDao.countIPs(vlanRange.getDataCenterId(), vlanDbId, true);
+                if (allocIpCount > 1) {
+                    throw  new InvalidParameterValueException ("cannot delete this range as some of the vlans are in use.");
+                }
+                if (allocIpCount == 0){
+                    //remove the vlan range.
+                    if (!deletePublicIPRange(vlanDbId)) {
+                        return false;
+                    }
+                    _vlanDao.expunge(vlanDbId);
+                    return true;
+                }
+                //check if this allocated ip is being used as an ipAlias on the router.
+                ipAlias = _nicIpAliasDao.findByGatewayAndNetworkIdAndState(vlanRange.getVlanGateway(), vlanRange.getNetworkId(),  NicIpAlias.state.active);
+                //check if this ip belongs to this vlan and is allocated.
+                IPAddressVO ip = _publicIpAddressDao.findByIpAndVlanId(ipAlias.getIp4Address(), vlanDbId);
+                if (ip != null && ip.getState() == IpAddress.State.Allocated) {
+                    aliasIpBelongsToThisVlan =true;
+                    //check if there any other vlan ranges in the same subnet having free ips
+                    List<VlanVO> vlanRanges = _vlanDao.listVlansByNetworkIdAndGateway(vlanRange.getNetworkId(), vlanRange.getVlanGateway());
+                    //if there is no other vlanrage in this subnet. free the ip and delete the vlan.
+                    if (vlanRanges.size() == 1){
+                        boolean result = dhcpServiceProvider.removeDhcpSupportForSubnet(network);
+                        if (result == false) {
+                            s_logger.debug("Failed to delete the vlan range as we could not free the ip used to provide the dhcp service.");
+                        }
+                        else {
+                            _publicIpAddressDao.unassignIpAddress(ip.getId());
+                            if (!deletePublicIPRange(vlanDbId)) {
+                                return false;
+                            }
+                            _vlanDao.expunge(vlanDbId);
+                            _nicIpAliasDao.expunge(ipAlias.getId());
+                        }
+                    } else {
+                        // if there are more vlans in the subnet check if there are free ips.
+                        List<Long> vlanDbIdList = new ArrayList<Long>();
+                        for (VlanVO vlanrange : vlanRanges) {
+                            if (vlanrange.getId() != vlanDbId) {
+                                vlanDbIdList.add(vlanrange.getId());
+                            }
+                        }
+                        s_logger.info("vlan Range"+vlanRange.getId()+" id being deleted, one of the Ips in this range is used to provide the dhcp service, trying to free this ip and allocate a new one.");
+                        for (VlanVO vlanrange : vlanRanges) {
+                            if (vlanrange.getId() != vlanDbId) {
+                                freeIpsInsubnet =  _publicIpAddressDao.countFreeIpsInVlan(vlanrange.getId());
+                                if (freeIpsInsubnet > 0){
+                                    //assign one free ip to the router for creating ip Alias.
+                                    Transaction txn = Transaction.currentTxn();
+                                    //changing the state to revoked so that removeDhcpSupport for subnet sses it.
+                                    ipAlias.setState(NicIpAlias.state.revoked);
+                                    _nicIpAliasDao.update(ipAlias.getId(), ipAlias);
+                                    boolean result = false;
+                                    try {
+                                        PublicIp routerPublicIP = _networkMgr.assignPublicIpAddressFromVlans(network.getDataCenterId(), null, caller, Vlan.VlanType.DirectAttached, vlanDbIdList, network.getId(), null, false);
+                                        s_logger.info("creating a db entry for the new ip alias.");
+                                        NicIpAliasVO newipAlias = new NicIpAliasVO(ipAlias.getNicId(), routerPublicIP.getAddress().addr(), ipAlias.getVmId(), ipAlias.getAccountId(), network.getDomainId(), network.getId(), ipAlias.getGateway(), ipAlias.getNetmask());
+                                        newipAlias.setAliasCount(routerPublicIP.getIpMacAddress());
+                                        _nicIpAliasDao.persist(newipAlias);
+                                        //we revoke all the rules and apply all the rules as a part of the removedhcp config. so the new ip will get configured when we delete the old ip.
+
+                                    }
+                                    catch (InsufficientAddressCapacityException e) {
+                                        txn.rollback();
+                                        txn.close();
+                                        throw new InvalidParameterValueException("cannot delete  vlan range"+ vlanRange.getId()+"one of the ips in this range is benig used to provide dhcp service. Cannot use some other ip as there are no free ips in this subnet");
+                                    }
+                                    s_logger.info("removing the old ip alias on router");
+                                    result = dhcpServiceProvider.removeDhcpSupportForSubnet(network);
+                                    if (result == false) {
+                                        s_logger.debug("could't delete the ip alias on the router");
+                                        txn.rollback();
+                                        txn.close();
+                                        return false;
+                                    }
+                                    _publicIpAddressDao.unassignIpAddress(ip.getId());
+                                    if (!deletePublicIPRange(vlanDbId)) {
+                                        return false;
+                                    }
+                                    _vlanDao.expunge(vlanDbId);
+                                    txn.commit();
+                                    txn.close();
+                                }
+                            }
+                        }
+                    }
+                }
 
-            // Delete the VLAN
-            return _vlanDao.expunge(vlanDbId);
-        } else {
-            return false;
+            }
         }
+       throw new InvalidParameterValueException("One of the ips in the range is used to provide Dhcp service to this subnet. cannot delete this range as ");
     }
 
+
     @Override
     @DB
     @ActionEvent(eventType = EventTypes.EVENT_VLAN_IP_RANGE_DEDICATE, eventDescription = "dedicating vlan ip range", async = false)
@@ -2924,7 +3138,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
         return releasePublicIpRange(vlanDbId, UserContext.current().getCallerUserId(), UserContext.current().getCaller());
     }
 
-    @Override
+
     @DB
     public boolean releasePublicIpRange(long vlanDbId, long userId, Account caller) {
         VlanVO vlan = _vlanDao.findById(vlanDbId);
@@ -3295,7 +3509,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
 
     @Override
     @ActionEvent(eventType = EventTypes.EVENT_VLAN_IP_RANGE_DELETE, eventDescription = "deleting vlan ip range", async = false)
-    public boolean deleteVlanIpRange(DeleteVlanIpRangeCmd cmd) {
+    public boolean deleteVlanIpRange(DeleteVlanIpRangeCmd cmd)  {
         Long vlanDbId = cmd.getId();
 
         VlanVO vlan = _vlanDao.findById(vlanDbId);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/052c24c4/server/src/com/cloud/network/NetworkManager.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/NetworkManager.java b/server/src/com/cloud/network/NetworkManager.java
index 34a092a..72e3954 100755
--- a/server/src/com/cloud/network/NetworkManager.java
+++ b/server/src/com/cloud/network/NetworkManager.java
@@ -19,6 +19,7 @@ package com.cloud.network;
 import java.util.List;
 import java.util.Map;
 
+import com.cloud.network.element.DhcpServiceProvider;
 import org.apache.cloudstack.acl.ControlledEntity.ACLType;
 
 import com.cloud.dc.DataCenter;
@@ -349,4 +350,7 @@ public interface NetworkManager  {
 
     NicVO savePlaceholderNic(Network network, String ip4Address, Type vmType);
 
+    DhcpServiceProvider getDhcpServiceProvider(Network network);
+
+    PublicIp assignPublicIpAddressFromVlans(long dcId, Long podId, Account owner, VlanType type, List<Long> vlanDbIds, Long networkId, String requestedIp, boolean isSystem) throws InsufficientAddressCapacityException;
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/052c24c4/server/src/com/cloud/network/NetworkManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java
index 29c04ed..b99e934 100755
--- a/server/src/com/cloud/network/NetworkManagerImpl.java
+++ b/server/src/com/cloud/network/NetworkManagerImpl.java
@@ -275,6 +275,10 @@ public class NetworkManagerImpl extends ManagerBase implements NetworkManager, L
         return fetchNewPublicIp(dcId, podId, null, owner, type, networkId, false, true, requestedIp, isSystem, null);
     }
 
+    @Override
+    public PublicIp assignPublicIpAddressFromVlans(long dcId, Long podId, Account owner, VlanType type, List<Long> vlanDbIds, Long networkId, String requestedIp, boolean isSystem) throws InsufficientAddressCapacityException {
+        return fetchNewPublicIp(dcId, podId, vlanDbIds , owner, type, networkId, false, true, requestedIp, isSystem, null);
+    }
     @DB
     public PublicIp fetchNewPublicIp(long dcId, Long podId, List<Long> vlanDbIds, Account owner, VlanType vlanUse,
             Long guestNetworkId, boolean sourceNat, boolean assign, String requestedIp, boolean isSystem, Long vpcId)
@@ -1607,7 +1611,7 @@ public class NetworkManagerImpl extends ManagerBase implements NetworkManager, L
         }
     }
 
-    protected void prepareElement(NetworkElement element, NetworkVO network,
+    protected boolean prepareElement(NetworkElement element, NetworkVO network,
             NicProfile profile, VirtualMachineProfile<? extends VMInstanceVO> vmProfile,
             DeployDestination dest, ReservationContext context) throws InsufficientCapacityException,
             ConcurrentOperationException, ResourceUnavailableException {
@@ -1617,6 +1621,9 @@ public class NetworkManagerImpl extends ManagerBase implements NetworkManager, L
                     _networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.Dhcp, element.getProvider()) &&
                     element instanceof DhcpServiceProvider) {
                 DhcpServiceProvider sp = (DhcpServiceProvider) element;
+                if (!sp.configDhcpSupportForSubnet(network, profile, vmProfile, dest, context)) {
+                     return false;
+                }
                 sp.addDhcpEntry(network, profile, vmProfile, dest, context);
             }
             if (_networkModel.areServicesSupportedInNetwork(network.getId(), Service.UserData) &&
@@ -1626,6 +1633,7 @@ public class NetworkManagerImpl extends ManagerBase implements NetworkManager, L
                 sp.addPasswordAndUserdata(network, profile, vmProfile, dest, context);
             }
         }
+        return true;
     }
 
     @DB
@@ -1728,7 +1736,9 @@ public class NetworkManagerImpl extends ManagerBase implements NetworkManager, L
             if (s_logger.isDebugEnabled()) {
                 s_logger.debug("Asking " + element.getName() + " to prepare for " + nic);
             }
-            prepareElement(element, network, profile, vmProfile, dest, context);
+            if(!prepareElement(element, network, profile, vmProfile, dest, context)) {
+                throw new InsufficientAddressCapacityException("unable to configure the dhcp service, due to insufficiant address capacity",Network.class, network.getId());
+            }
         }
 
         profile.setSecurityGroupEnabled(_networkModel.isSecurityGroupSupportedInNetwork(network));
@@ -1987,7 +1997,7 @@ public class NetworkManagerImpl extends ManagerBase implements NetworkManager, L
                 if ( _networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
                     throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
                 }
-                if ( _networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SecurityGroup)) {
+                if (!( _networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SecurityGroup))) {
                     throw new InvalidParameterValueException("network must have SecurityGroup provider in security group enabled zone");
                 }
             }
@@ -2851,6 +2861,20 @@ public class NetworkManagerImpl extends ManagerBase implements NetworkManager, L
         return (UserDataServiceProvider)_networkModel.getElementImplementingProvider(SSHKeyProvider);
     }
 
+    @Override
+    public DhcpServiceProvider getDhcpServiceProvider(Network network) {
+        String DhcpProvider = _ntwkSrvcDao.getProviderForServiceInNetwork(network.getId(), Service.UserData);
+
+        if (DhcpProvider == null) {
+            s_logger.debug("Network " + network + " doesn't support service " + Service.Dhcp.getName());
+            return null;
+        }
+
+        return (DhcpServiceProvider)_networkModel.getElementImplementingProvider(DhcpProvider);
+
+    }
+
+
     protected boolean isSharedNetworkWithServices(Network network) {
         assert(network != null);
         DataCenter zone = _configMgr.getZone(network.getDataCenterId());

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/052c24c4/server/src/com/cloud/network/addr/PublicIp.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/addr/PublicIp.java b/server/src/com/cloud/network/addr/PublicIp.java
index 25e9d30..c753b49 100644
--- a/server/src/com/cloud/network/addr/PublicIp.java
+++ b/server/src/com/cloud/network/addr/PublicIp.java
@@ -219,4 +219,8 @@ public class PublicIp implements PublicIpAddress {
     public String getVmIp() {
         return _addr.getVmIp();
     }
+
+    public Long getIpMacAddress() {
+        return  _addr.getMacAddress();
+    }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/052c24c4/server/src/com/cloud/network/element/VirtualRouterElement.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/element/VirtualRouterElement.java b/server/src/com/cloud/network/element/VirtualRouterElement.java
index 28473cc..d66373b 100755
--- a/server/src/com/cloud/network/element/VirtualRouterElement.java
+++ b/server/src/com/cloud/network/element/VirtualRouterElement.java
@@ -54,6 +54,7 @@ import com.cloud.network.RemoteAccessVpn;
 import com.cloud.network.VirtualRouterProvider;
 import com.cloud.network.VirtualRouterProvider.VirtualRouterProviderType;
 import com.cloud.network.VpnUser;
+import com.cloud.network.dao.IPAddressDao;
 import com.cloud.network.dao.LoadBalancerDao;
 import com.cloud.network.dao.NetworkDao;
 import com.cloud.network.dao.VirtualRouterProviderDao;
@@ -89,6 +90,18 @@ import com.cloud.vm.VirtualMachineProfile;
 import com.cloud.vm.dao.DomainRouterDao;
 import com.cloud.vm.dao.UserVmDao;
 import com.google.gson.Gson;
+import org.apache.cloudstack.api.command.admin.router.ConfigureVirtualRouterElementCmd;
+import org.apache.cloudstack.api.command.admin.router.CreateVirtualRouterElementCmd;
+import org.apache.cloudstack.api.command.admin.router.ListVirtualRouterElementsCmd;
+import org.apache.log4j.Logger;
+
+import javax.ejb.Local;
+import javax.inject.Inject;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
 
 @Local(value = {NetworkElement.class, FirewallServiceProvider.class, 
 		        DhcpServiceProvider.class, UserDataServiceProvider.class, 
@@ -130,6 +143,8 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
     ConfigurationDao _configDao;
     @Inject
     VirtualRouterProviderDao _vrProviderDao;
+    @Inject
+    IPAddressDao _ipAddressDao;
 
     protected boolean canHandle(Network network, Service service) {
         Long physicalNetworkId = _networkMgr.getPhysicalNetworkId(network);
@@ -826,6 +841,50 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
     }
 
     @Override
+    public  boolean configDhcpSupportForSubnet(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm,
+                                               DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException {
+        if (canHandle(network, Service.Dhcp)) {
+            if (vm.getType() != VirtualMachine.Type.User) {
+                return false;
+            }
+            @SuppressWarnings("unchecked")
+            VirtualMachineProfile<UserVm> uservm = (VirtualMachineProfile<UserVm>) vm;
+
+            List<DomainRouterVO> routers = getRouters(network, dest);
+
+            if ((routers == null) || (routers.size() == 0)) {
+                throw new ResourceUnavailableException("Can't find at least one router!", DataCenter.class, network.getDataCenterId());
+            }
+
+            return _routerMgr.configDhcpForSubnet(network, nic, uservm, dest, routers);
+        }
+        return false;
+    }
+
+    @Override
+    public boolean removeDhcpSupportForSubnet(Network network) {
+        if (canHandle(network, Service.Dhcp)) {
+            List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER);
+           try {
+               if ((routers == null) || (routers.size() == 0)) {
+                   throw new ResourceUnavailableException("Can't find at least one router!", DataCenter.class, network.getDataCenterId());
+               }
+           }
+           catch (ResourceUnavailableException e) {
+               s_logger.debug("could not find any router on this network");
+           }
+           try {
+                return _routerMgr.removeDhcpSupportForSubnet(network, routers);
+           }
+           catch (ResourceUnavailableException e) {
+                s_logger.debug("Router resource unavailable ");
+           }
+
+        }
+        return false;
+    }
+
+    @Override
     public boolean addDhcpEntry(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, 
             DeployDestination dest, ReservationContext context)
             throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/052c24c4/server/src/com/cloud/network/router/VirtualNetworkApplianceManager.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManager.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManager.java
index fcf650f..a80c560 100644
--- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManager.java
+++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManager.java
@@ -16,9 +16,6 @@
 // under the License.
 package com.cloud.network.router;
 
-import java.util.List;
-import java.util.Map;
-
 import com.cloud.deploy.DeployDestination;
 import com.cloud.exception.ConcurrentOperationException;
 import com.cloud.exception.InsufficientCapacityException;
@@ -39,6 +36,9 @@ import com.cloud.vm.DomainRouterVO;
 import com.cloud.vm.NicProfile;
 import com.cloud.vm.VirtualMachineProfile;
 
+import java.util.List;
+import java.util.Map;
+
 /**
  * NetworkManager manages the network for the different end users.
  *
@@ -107,4 +107,9 @@ public interface VirtualNetworkApplianceManager extends Manager, VirtualNetworkA
 
     boolean applyLoadBalancingRules(Network network, List<? extends LoadBalancingRule> rules, List<? extends VirtualRouter> routers) throws ResourceUnavailableException;
 
-}
+
+    boolean configDhcpForSubnet(Network network, NicProfile nic, VirtualMachineProfile<UserVm> uservm, DeployDestination dest, List<DomainRouterVO> routers) throws ResourceUnavailableException ;
+
+    boolean removeDhcpSupportForSubnet(Network network, List<DomainRouterVO> routers) throws ResourceUnavailableException;
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/052c24c4/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
index e3dd06b..f6057e8 100755
--- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
+++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
@@ -17,34 +17,6 @@
 
 package com.cloud.network.router;
 
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TimeZone;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.TimeUnit;
-
-import javax.ejb.Local;
-import javax.inject.Inject;
-import javax.naming.ConfigurationException;
-
-import com.cloud.server.ConfigurationServer;
-import org.apache.cloudstack.api.command.admin.router.UpgradeRouterCmd;
-import org.apache.log4j.Logger;
-import org.springframework.stereotype.Component;
-
 import com.cloud.agent.AgentManager;
 import com.cloud.agent.AgentManager.OnError;
 import com.cloud.agent.Listener;
@@ -66,7 +38,11 @@ import com.cloud.agent.api.StartupCommand;
 import com.cloud.agent.api.StopAnswer;
 import com.cloud.agent.api.check.CheckSshAnswer;
 import com.cloud.agent.api.check.CheckSshCommand;
+import com.cloud.agent.api.routing.CreateIpAliasCommand;
+import com.cloud.agent.api.routing.DeleteIpAliasCommand;
 import com.cloud.agent.api.routing.DhcpEntryCommand;
+import com.cloud.agent.api.routing.DnsMasqConfigCommand;
+import com.cloud.agent.api.routing.IpAliasTO;
 import com.cloud.agent.api.routing.IpAssocCommand;
 import com.cloud.agent.api.routing.LoadBalancerConfigCommand;
 import com.cloud.agent.api.routing.NetworkElementCommand;
@@ -78,6 +54,7 @@ import com.cloud.agent.api.routing.SetPortForwardingRulesVpcCommand;
 import com.cloud.agent.api.routing.SetStaticNatRulesCommand;
 import com.cloud.agent.api.routing.VmDataCommand;
 import com.cloud.agent.api.routing.VpnUsersCfgCommand;
+import com.cloud.agent.api.to.DnsmasqTO;
 import com.cloud.agent.api.to.FirewallRuleTO;
 import com.cloud.agent.api.to.IpAddressTO;
 import com.cloud.agent.api.to.LoadBalancerTO;
@@ -100,6 +77,8 @@ import com.cloud.dc.DataCenter.NetworkType;
 import com.cloud.dc.DataCenterVO;
 import com.cloud.dc.HostPodVO;
 import com.cloud.dc.Pod;
+import com.cloud.dc.Vlan;
+import com.cloud.dc.VlanVO;
 import com.cloud.dc.dao.ClusterDao;
 import com.cloud.dc.dao.DataCenterDao;
 import com.cloud.dc.dao.HostPodDao;
@@ -185,6 +164,7 @@ import com.cloud.offering.NetworkOffering;
 import com.cloud.offering.ServiceOffering;
 import com.cloud.offerings.dao.NetworkOfferingDao;
 import com.cloud.resource.ResourceManager;
+import com.cloud.server.ConfigurationServer;
 import com.cloud.service.ServiceOfferingVO;
 import com.cloud.service.dao.ServiceOfferingDao;
 import com.cloud.storage.GuestOSVO;
@@ -224,6 +204,7 @@ import com.cloud.utils.net.MacAddress;
 import com.cloud.utils.net.NetUtils;
 import com.cloud.vm.DomainRouterVO;
 import com.cloud.vm.Nic;
+import com.cloud.vm.NicIpAlias;
 import com.cloud.vm.NicProfile;
 import com.cloud.vm.NicVO;
 import com.cloud.vm.ReservationContext;
@@ -239,9 +220,36 @@ import com.cloud.vm.VirtualMachineProfile;
 import com.cloud.vm.VirtualMachineProfile.Param;
 import com.cloud.vm.dao.DomainRouterDao;
 import com.cloud.vm.dao.NicDao;
+import com.cloud.vm.dao.NicIpAliasDao;
+import com.cloud.vm.dao.NicIpAliasVO;
 import com.cloud.vm.dao.UserVmDao;
 import com.cloud.vm.dao.UserVmDetailsDao;
 import com.cloud.vm.dao.VMInstanceDao;
+import org.apache.cloudstack.api.command.admin.router.UpgradeRouterCmd;
+import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
+
+import javax.ejb.Local;
+import javax.inject.Inject;
+import javax.naming.ConfigurationException;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TimeZone;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
 
 /**
  * VirtualNetworkApplianceManagerImpl manages the different types of virtual network appliances available in the Cloud Stack.
@@ -320,6 +328,8 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
     @Inject
     NicDao _nicDao;
     @Inject
+    NicIpAliasDao _nicIpAliasDao;
+    @Inject
     VolumeDao _volumeDao = null;
     @Inject
     UserVmDetailsDao _vmDetailsDao;
@@ -2431,6 +2441,23 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
                     createApplyLoadBalancingRulesCommands(lbRules, router, cmds, guestNetworkId);
             }
         }
+        //Reapply dhcp and dns configuration.
+        if (_networkModel.isProviderSupportServiceInNetwork(guestNetworkId, Service.Dhcp, provider)) {
+            List<NicIpAliasVO> revokedIpAliasVOs = _nicIpAliasDao.listByNetworkIdAndState(guestNetworkId, NicIpAlias.state.revoked);
+            s_logger.debug("Found" + revokedIpAliasVOs.size() + "ip Aliases to apply on the router as a part of dhco configuration");
+            List<IpAliasTO> revokedIpAliasTOs = new ArrayList<IpAliasTO>();
+            for (NicIpAliasVO revokedAliasVO : revokedIpAliasVOs) {
+                revokedIpAliasTOs.add(new IpAliasTO(revokedAliasVO.getIp4Address(), revokedAliasVO.getNetmask(), revokedAliasVO.getAliasCount().toString()));
+            }
+            List<NicIpAliasVO> aliasVOs = _nicIpAliasDao.listByNetworkIdAndState(guestNetworkId, NicIpAlias.state.active);
+            s_logger.debug("Found" + aliasVOs.size() + "ip Aliases to apply on the router as a part of dhco configuration");
+            List<IpAliasTO> activeIpAliasTOs = new ArrayList<IpAliasTO>();
+            for (NicIpAliasVO aliasVO : aliasVOs) {
+                   activeIpAliasTOs.add(new IpAliasTO(aliasVO.getIp4Address(), aliasVO.getNetmask(), aliasVO.getAliasCount().toString()));
+            }
+            createDeleteIpAliasCommand(router, revokedIpAliasTOs, activeIpAliasTOs, guestNetworkId, cmds);
+
+        }
     }
 
     protected void finalizeIpAssocForNetwork(Commands cmds, VirtualRouter router, Provider provider, 
@@ -2672,7 +2699,129 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
             throw new CloudRuntimeException("Unable to stop " + router, e);
         }
     }
-    
+
+    @Override
+    public boolean configDhcpForSubnet(Network network, final NicProfile nic, VirtualMachineProfile<UserVm> profile, DeployDestination dest, List<DomainRouterVO> routers) throws ResourceUnavailableException {
+        _userVmDao.loadDetails((UserVmVO) profile.getVirtualMachine());
+
+        final VirtualMachineProfile<UserVm> updatedProfile = profile;
+        final boolean isZoneBasic = (dest.getDataCenter().getNetworkType() == NetworkType.Basic);
+        final Long podId = isZoneBasic ? dest.getPod().getId() : null;
+
+        //Asuming we have only one router per network For Now.
+        DomainRouterVO router = routers.get(0);
+        if (router.getState() != State.Running) {
+            s_logger.warn("Failed to add/remove VPN users: router not in running state");
+            throw new ResourceUnavailableException("Unable to assign ip addresses, domR is not in right state " +
+                    router.getState(), DataCenter.class, network.getDataCenterId());
+        }
+        //check if this is not the primary subnet.
+
+
+        //check if the the ip Alias is configured on the virtualrouter.
+        UserVm vm = updatedProfile.getVirtualMachine();
+        NicVO domr_guest_nic = _nicDao.findByInstanceIdAndIpAddressAndVmtype(router.getId(), _nicDao.getIpAddress(nic.getNetworkId(), router.getId()), VirtualMachine.Type.DomainRouter);
+        //check if the router ip address and the vm ip address belong to same subnet.
+        //if they do not belong to same netwoek check for the alias ips. if not create one.
+        // This should happen only in case of Basic and Advanced SG enabled networks.
+        if (!NetUtils.sameSubnet(domr_guest_nic.getIp4Address(), nic.getIp4Address(), nic.getNetmask())){
+            List<NicIpAliasVO> aliasIps = _nicIpAliasDao.listByNetworkIdAndState(domr_guest_nic.getNetworkId(), NicIpAlias.state.active);
+            boolean ipInVmsubnet =false;
+            for (NicIpAliasVO alias : aliasIps) {
+                //check if any of the alias ips belongs to the Vm's subnet.
+                if (NetUtils.sameSubnet(alias.getIp4Address(),nic.getIp4Address(),nic.getNetmask())){
+                    ipInVmsubnet = true;
+                    break;
+                }
+            }
+            PublicIp routerPublicIP = null;
+            String routerAliasIp =null;
+            DataCenter dc = _dcDao.findById(router.getDataCenterId());
+            if (ipInVmsubnet == false) {
+                try {
+                    if (network.getTrafficType() == TrafficType.Guest && network.getGuestType() == GuestType.Shared) {
+                        Pod pod = _podDao.findById(vm.getPodIdToDeployIn());
+                        Account caller = UserContext.current().getCaller();
+                        List<VlanVO> vlanList = _vlanDao.listVlansByNetworkIdAndGateway(network.getId(), nic.getGateway());
+                        List<Long>   vlanDbIdList = new ArrayList<Long>();
+                        for (VlanVO vlan : vlanList) {
+                            vlanDbIdList.add(vlan.getId());
+                        }
+                        routerPublicIP = _networkMgr.assignPublicIpAddressFromVlans(router.getDataCenterId(), vm.getPodIdToDeployIn(), caller, Vlan.VlanType.DirectAttached, vlanDbIdList, nic.getNetworkId(), null, false);
+                        routerAliasIp = routerPublicIP.getAddress().addr();
+                    }
+                }
+                catch (InsufficientAddressCapacityException e){
+                    s_logger.info(e.getMessage());
+                    s_logger.info("unable to configure dhcp for this VM.");
+                    return false;
+                }
+                //this means we did not create a ip alis on the router.
+                NicIpAliasVO alias = new NicIpAliasVO(domr_guest_nic.getId(), routerAliasIp, router.getId(), UserContext.current().getAccountId(), network.getDomainId(), nic.getNetworkId(),nic.getGateway(), nic.getNetmask());
+                alias.setAliasCount((routerPublicIP.getIpMacAddress()));
+                _nicIpAliasDao.persist(alias);
+                List<IpAliasTO> ipaliasTo = new ArrayList<IpAliasTO>();
+                ipaliasTo.add(new IpAliasTO(routerAliasIp, alias.getNetmask(), alias.getAliasCount().toString()));
+                Commands cmds = new Commands(OnError.Stop);
+                createIpAlias(router, ipaliasTo, alias.getNetworkId(), cmds);
+                //also add the required configuration to the dnsmasq for supporting dhcp and dns on the new ip.
+                configDnsMasq(router, network, cmds);
+                boolean result = sendCommandsToRouter(router, cmds);
+                if (result == false) {
+                    NicIpAliasVO ipAliasVO = _nicIpAliasDao.findByInstanceIdAndNetworkId(network.getId(), router.getId());
+                    _nicIpAliasDao.expunge(ipAliasVO.getId());
+                    _ipAddressDao.unassignIpAddress(routerPublicIP.getId());
+                    throw new CloudRuntimeException("failed to configure ip alias on the router as a part of dhcp config");
+                }
+            }
+            return true;
+        }
+        return true;
+    }
+
+    @Override
+    public boolean removeDhcpSupportForSubnet(Network network,  List<DomainRouterVO> routers) throws ResourceUnavailableException {
+        if (routers == null || routers.isEmpty()) {
+            s_logger.warn("Failed to add/remove VPN users: no router found for account and zone");
+            throw new ResourceUnavailableException("Unable to assign ip addresses, domR doesn't exist for network " +
+                    network.getId(), DataCenter.class, network.getDataCenterId());
+        }
+
+        boolean agentResults = true;
+
+        for (DomainRouterVO router : routers) {
+            if (router.getState() != State.Running) {
+                s_logger.warn("Failed to add/remove VPN users: router not in running state");
+                throw new ResourceUnavailableException("Unable to assign ip addresses, domR is not in right state " +
+                        router.getState(), DataCenter.class, network.getDataCenterId());
+            }
+
+            Commands cmds = new Commands(OnError.Continue);
+            List<NicIpAliasVO> revokedIpAliasVOs = _nicIpAliasDao.listByNetworkIdAndState(network.getId(), NicIpAlias.state.revoked);
+            s_logger.debug("Found" + revokedIpAliasVOs.size() + "ip Aliases to apply on the router as a part of dhco configuration");
+            List<IpAliasTO> revokedIpAliasTOs = new ArrayList<IpAliasTO>();
+            for (NicIpAliasVO revokedAliasVO : revokedIpAliasVOs) {
+                revokedIpAliasTOs.add(new IpAliasTO(revokedAliasVO.getIp4Address(), revokedAliasVO.getNetmask(), revokedAliasVO.getAliasCount().toString()));
+            }
+            List<NicIpAliasVO> aliasVOs = _nicIpAliasDao.listByNetworkIdAndState(network.getId(), NicIpAlias.state.active);
+            s_logger.debug("Found" + aliasVOs.size() + "ip Aliases to apply on the router as a part of dhco configuration");
+            List<IpAliasTO> activeIpAliasTOs = new ArrayList<IpAliasTO>();
+            for (NicIpAliasVO aliasVO : aliasVOs) {
+                activeIpAliasTOs.add(new IpAliasTO(aliasVO.getIp4Address(), aliasVO.getNetmask(), aliasVO.getAliasCount().toString()));
+            }
+            createDeleteIpAliasCommand(router, revokedIpAliasTOs, activeIpAliasTOs, network.getId(), cmds);
+            configDnsMasq(router, network, cmds);
+            boolean result = sendCommandsToRouter(router, cmds);
+            if (result) {
+                for (NicIpAliasVO revokedAliasVO : revokedIpAliasVOs) {
+                    _nicIpAliasDao.expunge(revokedAliasVO.getId());
+                }
+            }
+        }
+        return  false;
+    }
+
+
     @Override
     public boolean applyDhcpEntry(Network network, final NicProfile nic, VirtualMachineProfile<UserVm> profile, 
             DeployDestination dest, List<DomainRouterVO> routers)
@@ -2705,7 +2854,19 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
         });
     }
 
-    private String findDefaultDnsIp(long userVmId) {
+    private void createDeleteIpAliasCommand(DomainRouterVO router, List<IpAliasTO> deleteIpAliasTOs, List<IpAliasTO> createIpAliasTos, long networkId, Commands cmds) {
+        String routerip = getRouterIpInNetwork(networkId, router.getId());
+        DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
+        DeleteIpAliasCommand deleteIpaliasCmd = new DeleteIpAliasCommand(routerip, deleteIpAliasTOs, createIpAliasTos);
+        deleteIpaliasCmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, getRouterControlIp(router.getId()));
+        deleteIpaliasCmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
+        deleteIpaliasCmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP,routerip);
+        deleteIpaliasCmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
+
+        cmds.addCommand("deleteIpalias", deleteIpaliasCmd);
+    }
+
+    private NicVO findDefaultDnsIp(long userVmId) {
         NicVO defaultNic = _nicDao.findDefaultNicForVM(userVmId);
         
         //check if DNS provider is the domR
@@ -2728,12 +2889,12 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
         } else{
             domrDefaultNic = _nicDao.findByNetworkIdAndType(defaultNic.getNetworkId(), VirtualMachine.Type.DomainRouter);
         }
-        return domrDefaultNic.getIp4Address();
+        return domrDefaultNic;
     }
 
-    private String findGatewayIp(long userVmId) {
+    private NicVO findGatewayIp(long userVmId) {
         NicVO defaultNic = _nicDao.findDefaultNicForVM(userVmId);
-        return defaultNic.getGateway();
+        return defaultNic;
      }
 
     @Override
@@ -3159,7 +3320,8 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
     private void createDhcpEntryCommand(VirtualRouter router, UserVm vm, NicVO nic, Commands cmds) {
         DhcpEntryCommand dhcpCommand = new DhcpEntryCommand(nic.getMacAddress(), nic.getIp4Address(), vm.getHostName(), nic.getIp6Address());
         DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
-        String gatewayIp = findGatewayIp(vm.getId());
+        Nic defaultNic = findGatewayIp(vm.getId());
+        String gatewayIp = defaultNic.getGateway();
         boolean needGateway = true;
         if (gatewayIp != null && !gatewayIp.equals(nic.getGateway())) {
             needGateway = false;
@@ -3178,7 +3340,12 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
         }
         dhcpCommand.setDefaultRouter(gatewayIp);
         dhcpCommand.setIp6Gateway(nic.getIp6Gateway());
-        dhcpCommand.setDefaultDns(findDefaultDnsIp(vm.getId()));
+        String ipaddress=null;
+        NicVO domrDefaultNic =  findDefaultDnsIp(vm.getId());
+        if (domrDefaultNic != null){
+            ipaddress  = domrDefaultNic.getIp4Address();
+        }
+        dhcpCommand.setDefaultDns(ipaddress);
         dhcpCommand.setDuid(NetUtils.getDuidLL(nic.getMacAddress()));
         dhcpCommand.setDefault(nic.isDefaultNic());
 
@@ -3190,6 +3357,42 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
         cmds.addCommand("dhcp", dhcpCommand);
     }
 
+    private void configDnsMasq(VirtualRouter router, Network network, Commands cmds) {
+        DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
+        List<NicIpAliasVO> ipAliasVOList = _nicIpAliasDao.getAliasIpForVm(router.getId());
+        List<DnsmasqTO> ipList = new ArrayList<DnsmasqTO>();
+
+        NicVO router_guest_ip = _nicDao.findByNtwkIdAndInstanceId(network.getId(), router.getId());
+        ipList.add(new DnsmasqTO(router_guest_ip.getIp4Address(),router_guest_ip.getGateway(),router_guest_ip.getNetmask()));
+        for (NicIpAliasVO ipAliasVO : ipAliasVOList) {
+             DnsmasqTO dnsmasqTO = new DnsmasqTO(ipAliasVO.getStartIpOfSubnet(), ipAliasVO.getGateway(), ipAliasVO.getNetmask());
+             ipList.add(dnsmasqTO);
+        }
+        DataCenterVO dcvo = _dcDao.findById(router.getDataCenterId());
+        DnsMasqConfigCommand dnsMasqConfigCmd = new DnsMasqConfigCommand(network.getNetworkDomain(),ipList, dcvo.getDns1(), dcvo.getDns2(), dcvo.getInternalDns1(), dcvo.getInternalDns2());
+        dnsMasqConfigCmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, getRouterControlIp(router.getId()));
+        dnsMasqConfigCmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
+        dnsMasqConfigCmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, getRouterIpInNetwork(network.getId(), router.getId()));
+        dnsMasqConfigCmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
+
+        cmds.addCommand("dhcpConfig" ,dnsMasqConfigCmd);
+        //To change body of created methods use File | Settings | File Templates.
+    }
+
+
+    private void createIpAlias(VirtualRouter router, List<IpAliasTO> ipAliasTOs, Long networkid, Commands cmds) {
+
+        String routerip = getRouterIpInNetwork(networkid, router.getId());
+        DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
+        CreateIpAliasCommand ipaliasCmd = new CreateIpAliasCommand(routerip, ipAliasTOs);
+        ipaliasCmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, getRouterControlIp(router.getId()));
+        ipaliasCmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
+        ipaliasCmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP,routerip);
+        ipaliasCmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
+
+        cmds.addCommand("ipalias", ipaliasCmd);
+    }
+
     private void createDhcpEntryCommandsForVMs(DomainRouterVO router, Commands cmds, long guestNetworkId) {
         List<UserVmVO> vms = _userVmDao.listByNetworkIdAndStates(guestNetworkId, State.Running, State.Migrating, State.Stopping);
         DataCenterVO dc = _dcDao.findById(router.getDataCenterId());

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/052c24c4/server/src/com/cloud/vm/dao/NicIpAliasDao.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/vm/dao/NicIpAliasDao.java b/server/src/com/cloud/vm/dao/NicIpAliasDao.java
new file mode 100644
index 0000000..f1e4b8e
--- /dev/null
+++ b/server/src/com/cloud/vm/dao/NicIpAliasDao.java
@@ -0,0 +1,61 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+package com.cloud.vm.dao;
+
+import java.util.List;
+import com.cloud.utils.db.GenericDao;
+import com.cloud.vm.NicIpAlias;
+
+public interface NicIpAliasDao extends GenericDao<NicIpAliasVO, Long> {
+    List<NicIpAliasVO> listByVmId(long instanceId);
+
+    List<String> listAliasIpAddressInNetwork(long networkConfigId);
+    List<NicIpAliasVO> listByNetworkId(long networkId);
+
+    NicIpAliasVO findByInstanceIdAndNetworkId(long networkId, long instanceId);
+
+    NicIpAliasVO findByIp4AddressAndNetworkId(String ip4Address, long networkId);
+
+    /**
+     * @param networkId
+     * @param instanceId
+     * @return
+     */
+
+    List<NicIpAliasVO> getAliasIpForVm(long vmId);
+
+    List<NicIpAliasVO> listByNicId(long nicId);
+
+    List<NicIpAliasVO> listByNicIdAndVmid(long nicId, long vmId);
+
+    NicIpAliasVO findByIp4AddressAndNicId(String ip4Address, long nicId);
+
+    NicIpAliasVO findByIp4AddressAndNetworkIdAndInstanceId(long networkId,
+                                                               Long vmId, String vmIp);
+
+    List<String> getAliasIpAddressesForNic(long nicId);
+
+    Integer countAliasIps(long NicId);
+
+    public NicIpAliasVO findByIp4AddressAndVmId(String ip4Address, long vmId);
+
+    NicIpAliasVO findByGatewayAndNetworkIdAndState(String gateway, long networkId, NicIpAlias.state state);
+
+    List<NicIpAliasVO> listByNetworkIdAndState(long networkId, NicIpAlias.state state);
+
+    List<NicIpAliasVO> listByNetworkIdAndAliasIpAndState(long networkId, String aliasIpOfSubnet, NicIpAlias.state state);
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/052c24c4/server/src/com/cloud/vm/dao/NicIpAliasDaoImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/vm/dao/NicIpAliasDaoImpl.java b/server/src/com/cloud/vm/dao/NicIpAliasDaoImpl.java
new file mode 100644
index 0000000..e6c52a2
--- /dev/null
+++ b/server/src/com/cloud/vm/dao/NicIpAliasDaoImpl.java
@@ -0,0 +1,186 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+package com.cloud.vm.dao;
+
+import com.cloud.utils.db.GenericDaoBase;
+import com.cloud.utils.db.GenericSearchBuilder;
+import com.cloud.utils.db.SearchBuilder;
+import com.cloud.utils.db.SearchCriteria;
+import com.cloud.utils.db.SearchCriteria.Func;
+import com.cloud.utils.db.SearchCriteria.Op;
+import com.cloud.vm.NicIpAlias;
+import org.springframework.stereotype.Component;
+
+import javax.ejb.Local;
+import java.util.ArrayList;
+import java.util.List;
+
+
+@Component
+@Local(value=NicIpAliasDao.class)
+public class NicIpAliasDaoImpl extends GenericDaoBase<NicIpAliasVO, Long> implements NicIpAliasDao {
+    private final SearchBuilder<NicIpAliasVO> AllFieldsSearch;
+    private final GenericSearchBuilder<NicIpAliasVO, String> IpSearch;
+
+    protected NicIpAliasDaoImpl() {
+        super();
+        AllFieldsSearch = createSearchBuilder();
+        AllFieldsSearch.and("instanceId", AllFieldsSearch.entity().getVmId(), Op.EQ);
+        AllFieldsSearch.and("network", AllFieldsSearch.entity().getNetworkId(), Op.EQ);
+        AllFieldsSearch.and("address", AllFieldsSearch.entity().getIp4Address(), Op.EQ);
+        AllFieldsSearch.and("nicId", AllFieldsSearch.entity().getNicId(), Op.EQ);
+        AllFieldsSearch.and("gateway", AllFieldsSearch.entity().getGateway(), Op.EQ);
+        AllFieldsSearch.and("state", AllFieldsSearch.entity().getState(), Op.EQ);
+        AllFieldsSearch.done();
+
+        IpSearch = createSearchBuilder(String.class);
+        IpSearch.select(null, Func.DISTINCT, IpSearch.entity().getIp4Address());
+        IpSearch.and("network", IpSearch.entity().getNetworkId(), Op.EQ);
+        IpSearch.and("address", IpSearch.entity().getIp4Address(), Op.NNULL);
+        IpSearch.done();
+    }
+
+    @Override
+    public List<NicIpAliasVO> listByVmId(long instanceId) {
+        SearchCriteria<NicIpAliasVO> sc = AllFieldsSearch.create();
+        sc.setParameters("instanceId", instanceId);
+        return listBy(sc);
+    }
+
+    @Override
+    public List<NicIpAliasVO> listByNicId(long nicId) {
+        SearchCriteria<NicIpAliasVO> sc = AllFieldsSearch.create();
+        sc.setParameters("nicId", nicId);
+        return listBy(sc);
+    }
+
+    @Override
+    public List<String> listAliasIpAddressInNetwork(long networkId) {
+        SearchCriteria<String> sc = IpSearch.create();
+        sc.setParameters("network", networkId);
+        return customSearch(sc, null);
+    }
+
+    @Override
+    public List<NicIpAliasVO> listByNetworkId(long networkId) {
+        SearchCriteria<NicIpAliasVO> sc = AllFieldsSearch.create();
+        sc.setParameters("network", networkId);
+        return listBy(sc);
+    }
+
+
+    @Override
+    public List<NicIpAliasVO> listByNetworkIdAndState(long networkId, NicIpAlias.state state) {
+        SearchCriteria<NicIpAliasVO> sc = AllFieldsSearch.create();
+        sc.setParameters("network", networkId);
+        sc.setParameters("state", state);
+        return listBy(sc);
+    }
+
+    @Override
+    public List<NicIpAliasVO> listByNetworkIdAndAliasIpAndState(long networkId, String aliasIpOfSubnet, NicIpAlias.state state) {
+        SearchCriteria<NicIpAliasVO> sc = AllFieldsSearch.create();
+        sc.setParameters("network", networkId);
+        sc.setParameters("address", aliasIpOfSubnet);
+        sc.setParameters("state", state);
+        return listBy(sc);
+    }
+
+    @Override
+    public List<NicIpAliasVO> listByNicIdAndVmid(long nicId, long vmId) {
+        SearchCriteria<NicIpAliasVO> sc = AllFieldsSearch.create();
+        sc.setParameters("nicId", nicId);
+        sc.setParameters("instanceId", vmId);
+        return listBy(sc);
+    }
+
+    @Override
+    public List<NicIpAliasVO> getAliasIpForVm(long vmId) {
+        SearchCriteria<NicIpAliasVO> sc = AllFieldsSearch.create();
+        sc.setParameters("instanceId", vmId);
+        sc.setParameters("state", NicIpAlias.state.active);
+        return listBy(sc);
+    }
+
+    @Override
+    public List<String> getAliasIpAddressesForNic(long nicId) {
+        SearchCriteria<NicIpAliasVO> sc = AllFieldsSearch.create();
+        sc.setParameters("nicId", nicId);
+        List<NicIpAliasVO> results = search(sc, null);
+        List<String> ips = new ArrayList<String>(results.size());
+        for (NicIpAliasVO result : results) {
+            ips.add(result.getIp4Address());
+        }
+        return ips;
+    }
+
+    @Override
+    public NicIpAliasVO findByInstanceIdAndNetworkId(long networkId, long instanceId) {
+        SearchCriteria<NicIpAliasVO> sc = AllFieldsSearch.create();
+        sc.setParameters("network", networkId);
+        sc.setParameters("instanceId", instanceId);
+        sc.setParameters("state", NicIpAlias.state.active);
+        return findOneBy(sc);
+    }
+
+    @Override
+    public NicIpAliasVO findByIp4AddressAndNetworkId(String ip4Address, long networkId) {
+        return null;  //To change body of implemented methods use File | Settings | File Templates.
+    }
+
+    @Override
+    public NicIpAliasVO findByGatewayAndNetworkIdAndState(String gateway, long networkId, NicIpAlias.state state) {
+        SearchCriteria<NicIpAliasVO> sc = AllFieldsSearch.create();
+        sc.setParameters("gateway", gateway);
+        sc.setParameters("network", networkId);
+        sc.setParameters("state", state);
+        return findOneBy(sc);
+    }
+
+    @Override
+    public NicIpAliasVO findByIp4AddressAndVmId(String ip4Address, long vmId) {
+        SearchCriteria<NicIpAliasVO> sc = AllFieldsSearch.create();
+        sc.setParameters("address", ip4Address);
+        sc.setParameters("instanceId", vmId);
+        return findOneBy(sc);
+    }
+    @Override
+    public NicIpAliasVO findByIp4AddressAndNicId(String ip4Address, long nicId) {
+        SearchCriteria<NicIpAliasVO> sc = AllFieldsSearch.create();
+        sc.setParameters("address", ip4Address);
+        sc.setParameters("nicId", nicId);
+        return findOneBy(sc);
+    }
+
+    @Override
+    public NicIpAliasVO findByIp4AddressAndNetworkIdAndInstanceId(
+            long networkId, Long vmId, String vmIp) {
+        SearchCriteria<NicIpAliasVO> sc = AllFieldsSearch.create();
+        sc.setParameters("network", networkId);
+        sc.setParameters("instanceId", vmId);
+        sc.setParameters("address", vmIp);
+        return findOneBy(sc);
+    }
+
+    @Override
+    public Integer countAliasIps(long id) {
+        SearchCriteria<NicIpAliasVO> sc = AllFieldsSearch.create();
+        sc.setParameters("instanceId",id);
+        List<NicIpAliasVO> list = listBy(sc);
+        return list.size();
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/052c24c4/server/src/com/cloud/vm/dao/NicIpAliasVO.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/vm/dao/NicIpAliasVO.java b/server/src/com/cloud/vm/dao/NicIpAliasVO.java
new file mode 100644
index 0000000..4ed89d8
--- /dev/null
+++ b/server/src/com/cloud/vm/dao/NicIpAliasVO.java
@@ -0,0 +1,226 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+package com.cloud.vm.dao;
+
+import com.cloud.utils.db.GenericDao;
+import com.cloud.utils.net.NetUtils;
+import com.cloud.vm.NicIpAlias;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.EnumType;
+import javax.persistence.Enumerated;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+import java.util.Date;
+import java.util.UUID;
+
+@Entity
+@Table(name = "nic_ip_alias")
+public class NicIpAliasVO implements NicIpAlias  {
+
+    public NicIpAliasVO(Long nicId, String ipaddr, Long vmId,
+                        Long accountId, Long domainId, Long networkId, String gateway, String netmask) {
+        this.nicId = nicId;
+        this.vmId = vmId;
+        this.ip4Address = ipaddr;
+        this.accountId = accountId;
+        this.domainId = domainId;
+        this.networkId = networkId;
+        this.netmask =netmask;
+        this.gateway = gateway;
+        this.state = NicIpAlias.state.active;
+        String cidr = NetUtils.getCidrFromGatewayAndNetmask(gateway, netmask);
+        String[] cidrPair = cidr.split("\\/");
+        String cidrAddress = cidrPair[0];
+        long cidrSize = Long.parseLong(cidrPair[1]);
+        this.startIpOfSubnet = NetUtils.getIpRangeStartIpFromCidr(cidrAddress, cidrSize);
+    }
+
+    protected NicIpAliasVO() {
+    }
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id")
+    long id;
+
+    @Column(name = "nic_Id")
+    long nicId;
+
+    @Column(name="domain_id", updatable=false)
+    long domainId;
+
+    @Column(name="account_id", updatable=false)
+    private Long accountId;
+
+    @Column(name = "ip4_address")
+    String ip4Address;
+
+    @Column(name = "ip6_address")
+    String ip6Address;
+
+    @Column(name = "netmask")
+    String netmask;
+
+    @Column(name = "network_id")
+    long networkId;
+
+    @Column(name = GenericDao.CREATED_COLUMN)
+    Date created;
+
+    @Column(name = "uuid")
+    String uuid = UUID.randomUUID().toString();
+
+    @Column(name = "vmId")
+    Long vmId;
+
+    @Column(name = "alias_count")
+    Long aliasCount;
+
+    @Column(name = "gateway")
+    String gateway;
+
+    @Column(name= "state")
+    @Enumerated(value=EnumType.STRING)
+    NicIpAlias.state state;
+
+    @Column(name = "start_ip_of_subnet")
+    String startIpOfSubnet;
+
+
+
+
+    public long getId() {
+        return id;
+    }
+
+    public void setId(long id) {
+        this.id = id;
+    }
+
+    public long getNicId() {
+        return nicId;
+    }
+
+    public void setNicId(long nicId) {
+        this.nicId = nicId;
+    }
+
+    public long getDomainId() {
+        return domainId;
+    }
+
+    public void setDomainId(Long domainId) {
+        this.domainId = domainId;
+    }
+
+    public long getAccountId() {
+        return accountId;
+    }
+
+    public void setAccountId(Long accountId) {
+        this.accountId = accountId;
+    }
+
+    public String getIp4Address() {
+        return ip4Address;
+    }
+
+    public void setIp4Address(String ip4Address) {
+        this.ip4Address = ip4Address;
+    }
+
+    public String getIp6Address() {
+        return ip6Address;
+    }
+
+    public void setIp6Address(String ip6Address) {
+        this.ip6Address = ip6Address;
+    }
+
+    public long getNetworkId() {
+        return networkId;
+    }
+
+    public void setNetworkId(long networkId) {
+        this.networkId = networkId;
+    }
+
+    public Date getCreated() {
+        return created;
+    }
+
+    public void setCreated(Date created) {
+        this.created = created;
+    }
+
+    public String getUuid() {
+        return uuid;
+    }
+
+    public void setUuid(String uuid) {
+        this.uuid = uuid;
+    }
+
+    public long getVmId() {
+        return vmId;
+    }
+
+    public void setVmId(Long vmId) {
+        this.vmId = vmId;
+    }
+
+    public Long getAliasCount() {
+        return aliasCount;
+    }
+
+    public void setAliasCount(long count) {
+        this.aliasCount = count;
+    }
+
+    public void setNetmask(String netmask){
+        this.netmask = netmask;
+    }
+
+    public  String getNetmask() {
+        return netmask;
+    }
+
+    public  String getGateway() {
+        return  gateway;
+    }
+
+    public void setGateway(String gateway) {
+          this.gateway = gateway;
+    }
+
+    public NicIpAlias.state getState() {
+        return state;
+    }
+
+    public void setState(NicIpAlias.state state) {
+        this.state = state;
+    }
+
+    public String getStartIpOfSubnet() {
+        return startIpOfSubnet;
+    }
+
+}


Mime
View raw message