cloudstack-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ahu...@apache.org
Subject [48/50] [abbrv] merge from master complete
Date Mon, 20 May 2013 18:48:03 GMT
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/05cb7342/plugins/deployment-planners/implicit-dedication/test/org/apache/cloudstack/implicitplanner/ImplicitPlannerTest.java
----------------------------------------------------------------------
diff --cc plugins/deployment-planners/implicit-dedication/test/org/apache/cloudstack/implicitplanner/ImplicitPlannerTest.java
index 0000000,4450760..83cc123
mode 000000,100644..100644
--- a/plugins/deployment-planners/implicit-dedication/test/org/apache/cloudstack/implicitplanner/ImplicitPlannerTest.java
+++ b/plugins/deployment-planners/implicit-dedication/test/org/apache/cloudstack/implicitplanner/ImplicitPlannerTest.java
@@@ -1,0 -1,586 +1,587 @@@
+ // 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 org.apache.cloudstack.implicitplanner;
+ 
 -import static org.junit.Assert.assertTrue;
+ import static org.junit.Assert.assertFalse;
++import static org.junit.Assert.assertTrue;
+ import static org.junit.Assert.fail;
+ import static org.mockito.Matchers.anyString;
+ import static org.mockito.Mockito.mock;
+ import static org.mockito.Mockito.when;
+ 
+ import java.io.IOException;
+ import java.util.ArrayList;
+ import java.util.HashMap;
+ import java.util.HashSet;
+ import java.util.List;
+ import java.util.Map;
+ import java.util.Set;
+ 
+ import javax.inject.Inject;
+ import javax.naming.ConfigurationException;
+ 
 -import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
 -import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
 -import org.apache.cloudstack.test.utils.SpringUtils;
+ import org.junit.Before;
+ import org.junit.BeforeClass;
+ import org.junit.Test;
+ import org.junit.runner.RunWith;
+ import org.mockito.Mockito;
+ import org.springframework.context.annotation.Bean;
+ import org.springframework.context.annotation.ComponentScan;
+ import org.springframework.context.annotation.ComponentScan.Filter;
+ import org.springframework.context.annotation.Configuration;
+ import org.springframework.context.annotation.FilterType;
+ import org.springframework.core.type.classreading.MetadataReader;
+ import org.springframework.core.type.classreading.MetadataReaderFactory;
+ import org.springframework.core.type.filter.TypeFilter;
+ import org.springframework.test.context.ContextConfiguration;
+ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+ import org.springframework.test.context.support.AnnotationConfigContextLoader;
+ 
++import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
++import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
++import org.apache.cloudstack.test.utils.SpringUtils;
++
+ import com.cloud.capacity.CapacityManager;
+ import com.cloud.capacity.CapacityVO;
+ import com.cloud.capacity.dao.CapacityDao;
+ import com.cloud.configuration.dao.ConfigurationDao;
+ import com.cloud.dc.ClusterDetailsDao;
+ import com.cloud.dc.DataCenterVO;
+ import com.cloud.dc.dao.ClusterDao;
+ import com.cloud.dc.dao.DataCenterDao;
+ import com.cloud.dc.dao.HostPodDao;
+ import com.cloud.deploy.DataCenterDeployment;
+ import com.cloud.deploy.DeploymentPlanner.ExcludeList;
+ import com.cloud.deploy.ImplicitDedicationPlanner;
+ import com.cloud.exception.InsufficientServerCapacityException;
+ import com.cloud.host.HostVO;
+ import com.cloud.host.dao.HostDao;
+ import com.cloud.resource.ResourceManager;
+ import com.cloud.service.ServiceOfferingVO;
+ import com.cloud.service.dao.ServiceOfferingDao;
+ import com.cloud.service.dao.ServiceOfferingDetailsDao;
+ import com.cloud.storage.StorageManager;
+ import com.cloud.storage.dao.DiskOfferingDao;
+ import com.cloud.storage.dao.GuestOSCategoryDao;
+ import com.cloud.storage.dao.GuestOSDao;
+ import com.cloud.storage.dao.StoragePoolHostDao;
+ import com.cloud.storage.dao.VolumeDao;
+ import com.cloud.user.Account;
+ import com.cloud.user.AccountManager;
+ import com.cloud.user.AccountVO;
+ import com.cloud.user.UserContext;
+ import com.cloud.utils.Pair;
+ import com.cloud.utils.component.ComponentContext;
+ import com.cloud.vm.UserVmVO;
+ import com.cloud.vm.VMInstanceVO;
+ import com.cloud.vm.VirtualMachineProfileImpl;
+ import com.cloud.vm.dao.UserVmDao;
+ import com.cloud.vm.dao.VMInstanceDao;
+ 
+ @RunWith(SpringJUnit4ClassRunner.class)
+ @ContextConfiguration(loader = AnnotationConfigContextLoader.class)
+ public class ImplicitPlannerTest {
+ 
+     @Inject
+     ImplicitDedicationPlanner planner = new ImplicitDedicationPlanner();
+     @Inject
+     HostDao hostDao;
+     @Inject
+     DataCenterDao dcDao;
+     @Inject
+     HostPodDao podDao;
+     @Inject
+     ClusterDao clusterDao;
+     @Inject
+     GuestOSDao guestOSDao;
+     @Inject
+     GuestOSCategoryDao guestOSCategoryDao;
+     @Inject
+     DiskOfferingDao diskOfferingDao;
+     @Inject
+     StoragePoolHostDao poolHostDao;
+     @Inject
+     UserVmDao vmDao;
+     @Inject
+     VMInstanceDao vmInstanceDao;
+     @Inject
+     VolumeDao volsDao;
+     @Inject
+     CapacityManager capacityMgr;
+     @Inject
+     ConfigurationDao configDao;
+     @Inject
+     PrimaryDataStoreDao storagePoolDao;
+     @Inject
+     CapacityDao capacityDao;
+     @Inject
+     AccountManager accountMgr;
+     @Inject
+     StorageManager storageMgr;
+     @Inject
+     DataStoreManager dataStoreMgr;
+     @Inject
+     ClusterDetailsDao clusterDetailsDao;
+     @Inject
+     ServiceOfferingDao serviceOfferingDao;
+     @Inject
+     ServiceOfferingDetailsDao serviceOfferingDetailsDao;
+     @Inject
+     ResourceManager resourceMgr;
+ 
+     private static long domainId = 5L;
+     long dataCenterId = 1L;
+     long accountId = 200L;
+     long offeringId = 12L;
+     int noOfCpusInOffering = 1;
+     int cpuSpeedInOffering = 500;
+     int ramInOffering = 512;
+     AccountVO acct = new AccountVO(accountId);
+ 
+     @BeforeClass
+     public static void setUp() throws ConfigurationException {
+     }
+ 
+     @Before
+     public void testSetUp() {
+         ComponentContext.initComponentsLifeCycle();
+ 
+         acct.setType(Account.ACCOUNT_TYPE_NORMAL);
+         acct.setAccountName("user1");
+         acct.setDomainId(domainId);
+         acct.setId(accountId);
+ 
+         UserContext.registerContext(1, acct, null, true);
+     }
+ 
+     @Test
+     public void checkWhenDcInAvoidList() throws InsufficientServerCapacityException {
+         DataCenterVO mockDc = mock(DataCenterVO.class);
+         ExcludeList avoids = mock(ExcludeList.class);
+         @SuppressWarnings("unchecked")
 -        VirtualMachineProfileImpl<VMInstanceVO> vmProfile = mock(VirtualMachineProfileImpl.class);
++        VirtualMachineProfileImpl vmProfile = mock(VirtualMachineProfileImpl.class);
+         VMInstanceVO vm = mock(VMInstanceVO.class);
+         DataCenterDeployment plan = mock(DataCenterDeployment.class);
+ 
+         when(avoids.shouldAvoid(mockDc)).thenReturn(true);
+         when(vmProfile.getVirtualMachine()).thenReturn(vm);
+         when(vm.getDataCenterId()).thenReturn(1L);
+         when(dcDao.findById(1L)).thenReturn(mockDc);
+ 
+         List<Long> clusterList = planner.orderClusters(vmProfile, plan, avoids);
+         assertTrue("Cluster list should be null/empty if the dc is in avoid list",
+                 (clusterList == null || clusterList.isEmpty()));
+     }
+ 
+     @Test
+     public void checkStrictModeWithCurrentAccountVmsPresent() throws InsufficientServerCapacityException {
+         @SuppressWarnings("unchecked")
 -        VirtualMachineProfileImpl<VMInstanceVO> vmProfile = mock(VirtualMachineProfileImpl.class);
++        VirtualMachineProfileImpl vmProfile = mock(VirtualMachineProfileImpl.class);
+         DataCenterDeployment plan = mock(DataCenterDeployment.class);
+         ExcludeList avoids = new ExcludeList();
+ 
+         initializeForTest(vmProfile, plan);
+ 
+         initializeForImplicitPlannerTest(false);
+ 
+         List<Long> clusterList = planner.orderClusters(vmProfile, plan, avoids);
+ 
+         // Validations.
+         // Check cluster 2 and 3 are not in the cluster list.
+         // Host 6 and 7 should also be in avoid list.
+         assertFalse("Cluster list should not be null/empty", (clusterList == null || clusterList.isEmpty()));
+         boolean foundNeededCluster = false;
+         for (Long cluster : clusterList) {
+             if (cluster != 1) {
+                 fail("Found a cluster that shouldn't have been present, cluster id : " + cluster);
+             }else {
+                 foundNeededCluster = true;
+             }
+         }
+         assertTrue("Didn't find cluster 1 in the list. It should have been present", foundNeededCluster);
+ 
+         Set<Long> hostsInAvoidList = avoids.getHostsToAvoid();
+         assertFalse("Host 5 shouldn't have be in the avoid list, but it is present", hostsInAvoidList.contains(5L));
+         Set<Long> hostsThatShouldBeInAvoidList = new HashSet<Long>();
+         hostsThatShouldBeInAvoidList.add(6L);
+         hostsThatShouldBeInAvoidList.add(7L);
+         assertTrue("Hosts 6 and 7 that should have been present were not found in avoid list" ,
+                 hostsInAvoidList.containsAll(hostsThatShouldBeInAvoidList));
+     }
+ 
+     @Test
+     public void checkStrictModeHostWithCurrentAccountVmsFull() throws InsufficientServerCapacityException {
+         @SuppressWarnings("unchecked")
 -        VirtualMachineProfileImpl<VMInstanceVO> vmProfile = mock(VirtualMachineProfileImpl.class);
++        VirtualMachineProfileImpl vmProfile = mock(VirtualMachineProfileImpl.class);
+         DataCenterDeployment plan = mock(DataCenterDeployment.class);
+         ExcludeList avoids = new ExcludeList();
+ 
+         initializeForTest(vmProfile, plan);
+ 
+         initializeForImplicitPlannerTest(false);
+ 
+         // Mark the host 5 with current account vms to be in avoid list.
+         avoids.addHost(5L);
+         List<Long> clusterList = planner.orderClusters(vmProfile, plan, avoids);
+ 
+         // Validations.
+         // Check cluster 1 and 3 are not in the cluster list.
+         // Host 5 and 7 should also be in avoid list.
+         assertFalse("Cluster list should not be null/empty", (clusterList == null || clusterList.isEmpty()));
+         boolean foundNeededCluster = false;
+         for (Long cluster : clusterList) {
+             if (cluster != 2) {
+                 fail("Found a cluster that shouldn't have been present, cluster id : " + cluster);
+             }else {
+                 foundNeededCluster = true;
+             }
+         }
+         assertTrue("Didn't find cluster 2 in the list. It should have been present", foundNeededCluster);
+ 
+         Set<Long> hostsInAvoidList = avoids.getHostsToAvoid();
+         assertFalse("Host 6 shouldn't have be in the avoid list, but it is present", hostsInAvoidList.contains(6L));
+         Set<Long> hostsThatShouldBeInAvoidList = new HashSet<Long>();
+         hostsThatShouldBeInAvoidList.add(5L);
+         hostsThatShouldBeInAvoidList.add(7L);
+         assertTrue("Hosts 5 and 7 that should have been present were not found in avoid list" ,
+                 hostsInAvoidList.containsAll(hostsThatShouldBeInAvoidList));
+     }
+ 
+     @Test
+     public void checkStrictModeNoHostsAvailable() throws InsufficientServerCapacityException {
+         @SuppressWarnings("unchecked")
 -        VirtualMachineProfileImpl<VMInstanceVO> vmProfile = mock(VirtualMachineProfileImpl.class);
++        VirtualMachineProfileImpl vmProfile = mock(VirtualMachineProfileImpl.class);
+         DataCenterDeployment plan = mock(DataCenterDeployment.class);
+         ExcludeList avoids = new ExcludeList();
+ 
+         initializeForTest(vmProfile, plan);
+ 
+         initializeForImplicitPlannerTest(false);
+ 
+         // Mark the host 5 and 6 to be in avoid list.
+         avoids.addHost(5L);
+         avoids.addHost(6L);
+         List<Long> clusterList = planner.orderClusters(vmProfile, plan, avoids);
+ 
+         // Validations.
+         // Check cluster list is empty.
+         assertTrue("Cluster list should not be null/empty", (clusterList == null || clusterList.isEmpty()));
+     }
+ 
+     @Test
+     public void checkPreferredModePreferredHostAvailable() throws InsufficientServerCapacityException {
+         @SuppressWarnings("unchecked")
 -        VirtualMachineProfileImpl<VMInstanceVO> vmProfile = mock(VirtualMachineProfileImpl.class);
++        VirtualMachineProfileImpl vmProfile = mock(VirtualMachineProfileImpl.class);
+         DataCenterDeployment plan = mock(DataCenterDeployment.class);
+         ExcludeList avoids = new ExcludeList();
+ 
+         initializeForTest(vmProfile, plan);
+ 
+         initializeForImplicitPlannerTest(true);
+ 
+         // Mark the host 5 and 6 to be in avoid list.
+         avoids.addHost(5L);
+         avoids.addHost(6L);
+         List<Long> clusterList = planner.orderClusters(vmProfile, plan, avoids);
+ 
+         // Validations.
+         // Check cluster 1 and 2 are not in the cluster list.
+         // Host 5 and 6 should also be in avoid list.
+         assertFalse("Cluster list should not be null/empty", (clusterList == null || clusterList.isEmpty()));
+         boolean foundNeededCluster = false;
+         for (Long cluster : clusterList) {
+             if (cluster != 3) {
+                 fail("Found a cluster that shouldn't have been present, cluster id : " + cluster);
+             } else {
+                 foundNeededCluster = true;
+             }
+         }
+         assertTrue("Didn't find cluster 3 in the list. It should have been present", foundNeededCluster);
+ 
+         Set<Long> hostsInAvoidList = avoids.getHostsToAvoid();
+         assertFalse("Host 7 shouldn't have be in the avoid list, but it is present", hostsInAvoidList.contains(7L));
+         Set<Long> hostsThatShouldBeInAvoidList = new HashSet<Long>();
+         hostsThatShouldBeInAvoidList.add(5L);
+         hostsThatShouldBeInAvoidList.add(6L);
+         assertTrue("Hosts 5 and 6 that should have been present were not found in avoid list" ,
+                 hostsInAvoidList.containsAll(hostsThatShouldBeInAvoidList));
+     }
+ 
+     @Test
+     public void checkPreferredModeNoHostsAvailable() throws InsufficientServerCapacityException {
+         @SuppressWarnings("unchecked")
 -        VirtualMachineProfileImpl<VMInstanceVO> vmProfile = mock(VirtualMachineProfileImpl.class);
++        VirtualMachineProfileImpl vmProfile = mock(VirtualMachineProfileImpl.class);
+         DataCenterDeployment plan = mock(DataCenterDeployment.class);
+         ExcludeList avoids = new ExcludeList();
+ 
+         initializeForTest(vmProfile, plan);
+ 
+         initializeForImplicitPlannerTest(false);
+ 
+         // Mark the host 5, 6 and 7 to be in avoid list.
+         avoids.addHost(5L);
+         avoids.addHost(6L);
+         avoids.addHost(7L);
+         List<Long> clusterList = planner.orderClusters(vmProfile, plan, avoids);
+ 
+         // Validations.
+         // Check cluster list is empty.
+         assertTrue("Cluster list should not be null/empty", (clusterList == null || clusterList.isEmpty()));
+     }
+ 
 -    private void initializeForTest(VirtualMachineProfileImpl<VMInstanceVO> vmProfile, DataCenterDeployment plan) {
++    private void initializeForTest(VirtualMachineProfileImpl vmProfile, DataCenterDeployment plan) {
+         DataCenterVO mockDc = mock(DataCenterVO.class);
+         VMInstanceVO vm = mock(VMInstanceVO.class);
+         UserVmVO userVm = mock(UserVmVO.class);
+         ServiceOfferingVO offering = mock(ServiceOfferingVO.class);
+ 
+         AccountVO account = mock(AccountVO.class);
+         when(account.getId()).thenReturn(accountId);
+         when(account.getAccountId()).thenReturn(accountId);
+         when(vmProfile.getOwner()).thenReturn(account);
+         when(vmProfile.getVirtualMachine()).thenReturn(vm);
+         when(vmProfile.getId()).thenReturn(12L);
+         when(vmDao.findById(12L)).thenReturn(userVm);
+         when(userVm.getAccountId()).thenReturn(accountId);
+ 
+         when(vm.getDataCenterId()).thenReturn(dataCenterId);
+         when(dcDao.findById(1L)).thenReturn(mockDc);
+         when(plan.getDataCenterId()).thenReturn(dataCenterId);
+         when(plan.getClusterId()).thenReturn(null);
+         when(plan.getPodId()).thenReturn(null);
+         when(configDao.getValue(anyString())).thenReturn("false").thenReturn("CPU");
+ 
+         // Mock offering details.
+         when(vmProfile.getServiceOffering()).thenReturn(offering);
+         when(offering.getId()).thenReturn(offeringId);
+         when(vmProfile.getServiceOfferingId()).thenReturn(offeringId);
+         when(offering.getCpu()).thenReturn(noOfCpusInOffering);
+         when(offering.getSpeed()).thenReturn(cpuSpeedInOffering);
+         when(offering.getRamSize()).thenReturn(ramInOffering);
+ 
+         List<Long> clustersWithEnoughCapacity = new ArrayList<Long>();
+         clustersWithEnoughCapacity.add(1L);
+         clustersWithEnoughCapacity.add(2L);
+         clustersWithEnoughCapacity.add(3L);
+         when(capacityDao.listClustersInZoneOrPodByHostCapacities(dataCenterId, noOfCpusInOffering * cpuSpeedInOffering,
+                 ramInOffering * 1024L * 1024L, CapacityVO.CAPACITY_TYPE_CPU, true)).thenReturn(clustersWithEnoughCapacity);
+ 
+         Map<Long, Double> clusterCapacityMap = new HashMap<Long, Double>();
+         clusterCapacityMap.put(1L, 2048D);
+         clusterCapacityMap.put(2L, 2048D);
+         clusterCapacityMap.put(3L, 2048D);
+         Pair<List<Long>, Map<Long, Double>> clustersOrderedByCapacity =
+                 new Pair<List<Long>, Map<Long, Double>>(clustersWithEnoughCapacity, clusterCapacityMap);
+         when(capacityDao.orderClustersByAggregateCapacity(dataCenterId, CapacityVO.CAPACITY_TYPE_CPU,
+                 true)).thenReturn(clustersOrderedByCapacity);
+ 
+         List<Long> disabledClusters = new ArrayList<Long>();
+         List<Long> clustersWithDisabledPods = new ArrayList<Long>();
+         when(clusterDao.listDisabledClusters(dataCenterId, null)).thenReturn(disabledClusters);
+         when(clusterDao.listClustersWithDisabledPods(dataCenterId)).thenReturn(clustersWithDisabledPods);
+     }
+ 
+     private void initializeForImplicitPlannerTest(boolean preferred) {
+         String plannerMode = new String("Strict");
+         if (preferred) {
+             plannerMode = new String("Preferred");
+         }
+ 
+         Map<String, String> details = new HashMap<String, String>();
+         details.put("ImplicitDedicationMode", plannerMode);
+         when(serviceOfferingDetailsDao.findDetails(offeringId)).thenReturn(details);
+ 
+         // Initialize hosts in clusters
+         HostVO host1 = mock(HostVO.class);
+         when(host1.getId()).thenReturn(5L);
+         HostVO host2 = mock(HostVO.class);
+         when(host2.getId()).thenReturn(6L);
+         HostVO host3 = mock(HostVO.class);
+         when(host3.getId()).thenReturn(7L);
+         List<HostVO> hostsInCluster1 = new ArrayList<HostVO>();
+         List<HostVO> hostsInCluster2 = new ArrayList<HostVO>();
+         List<HostVO> hostsInCluster3 = new ArrayList<HostVO>();
+         hostsInCluster1.add(host1);
+         hostsInCluster2.add(host2);
+         hostsInCluster3.add(host3);
+         when(resourceMgr.listAllHostsInCluster(1)).thenReturn(hostsInCluster1);
+         when(resourceMgr.listAllHostsInCluster(2)).thenReturn(hostsInCluster2);
+         when(resourceMgr.listAllHostsInCluster(3)).thenReturn(hostsInCluster3);
+ 
+         // Mock vms on each host.
+         long offeringIdForVmsOfThisAccount = 15L;
+         long offeringIdForVmsOfOtherAccount = 16L;
+         UserVmVO vm1 = mock(UserVmVO.class);
+         when(vm1.getAccountId()).thenReturn(accountId);
+         when(vm1.getServiceOfferingId()).thenReturn(offeringIdForVmsOfThisAccount);
+         UserVmVO vm2 = mock(UserVmVO.class);
+         when(vm2.getAccountId()).thenReturn(accountId);
+         when(vm2.getServiceOfferingId()).thenReturn(offeringIdForVmsOfThisAccount);
+         // Vm from different account
+         UserVmVO vm3 = mock(UserVmVO.class);
+         when(vm3.getAccountId()).thenReturn(201L);
+         when(vm3.getServiceOfferingId()).thenReturn(offeringIdForVmsOfOtherAccount);
+         List<UserVmVO> userVmsForHost1 = new ArrayList<UserVmVO>();
+         List<UserVmVO> userVmsForHost2 = new ArrayList<UserVmVO>();
+         List<UserVmVO> userVmsForHost3 = new ArrayList<UserVmVO>();
+         List<UserVmVO> stoppedVmsForHost = new ArrayList<UserVmVO>();
+         // Host 2 is empty.
+         userVmsForHost1.add(vm1);
+         userVmsForHost1.add(vm2);
+         userVmsForHost3.add(vm3);
+         when(vmDao.listUpByHostId(5L)).thenReturn(userVmsForHost1);
+         when(vmDao.listUpByHostId(6L)).thenReturn(userVmsForHost2);
+         when(vmDao.listUpByHostId(7L)).thenReturn(userVmsForHost3);
+         when(vmDao.listByLastHostId(5L)).thenReturn(stoppedVmsForHost);
+         when(vmDao.listByLastHostId(6L)).thenReturn(stoppedVmsForHost);
+         when(vmDao.listByLastHostId(7L)).thenReturn(stoppedVmsForHost);
+ 
+         // Mock the offering with which the vm was created.
+         ServiceOfferingVO offeringForVmOfThisAccount = mock(ServiceOfferingVO.class);
+         when(serviceOfferingDao.findByIdIncludingRemoved(offeringIdForVmsOfThisAccount)).thenReturn(offeringForVmOfThisAccount);
+         when(offeringForVmOfThisAccount.getDeploymentPlanner()).thenReturn(planner.getName());
+ 
+         ServiceOfferingVO offeringForVMOfOtherAccount = mock(ServiceOfferingVO.class);
+         when(serviceOfferingDao.findByIdIncludingRemoved(offeringIdForVmsOfOtherAccount)).thenReturn(offeringForVMOfOtherAccount);
+         when(offeringForVMOfOtherAccount.getDeploymentPlanner()).thenReturn("FirstFitPlanner");
+     }
+ 
+     @Configuration
+     @ComponentScan(basePackageClasses = { ImplicitDedicationPlanner.class },
+         includeFilters = {@Filter(value = TestConfiguration.Library.class, type = FilterType.CUSTOM)},
+         useDefaultFilters = false)
+     public static class TestConfiguration extends SpringUtils.CloudStackTestConfiguration {
+ 
+         @Bean
+         public HostDao hostDao() {
+             return Mockito.mock(HostDao.class);
+         }
+ 
+         @Bean
+         public DataCenterDao dcDao() {
+             return Mockito.mock(DataCenterDao.class);
+         }
+ 
+         @Bean
+         public HostPodDao hostPodDao() {
+             return Mockito.mock(HostPodDao.class);
+         }
+ 
+         @Bean
+         public ClusterDao clusterDao() {
+             return Mockito.mock(ClusterDao.class);
+         }
+ 
+         @Bean
+         public GuestOSDao guestOsDao() {
+             return Mockito.mock(GuestOSDao.class);
+         }
+ 
+         @Bean
+         public GuestOSCategoryDao guestOsCategoryDao() {
+             return Mockito.mock(GuestOSCategoryDao.class);
+         }
+ 
+         @Bean
+         public DiskOfferingDao diskOfferingDao() {
+             return Mockito.mock(DiskOfferingDao.class);
+         }
+ 
+         @Bean
+         public StoragePoolHostDao storagePoolHostDao() {
+             return Mockito.mock(StoragePoolHostDao.class);
+         }
+ 
+         @Bean
+         public UserVmDao userVmDao() {
+             return Mockito.mock(UserVmDao.class);
+         }
+ 
+         @Bean
+         public VMInstanceDao vmInstanceDao() {
+             return Mockito.mock(VMInstanceDao.class);
+         }
+ 
+         @Bean
+         public VolumeDao volumeDao() {
+             return Mockito.mock(VolumeDao.class);
+         }
+ 
+         @Bean
+         public CapacityManager capacityManager() {
+             return Mockito.mock(CapacityManager.class);
+         }
+ 
+         @Bean
+         public ConfigurationDao configurationDao() {
+             return Mockito.mock(ConfigurationDao.class);
+         }
+ 
+         @Bean
+         public PrimaryDataStoreDao primaryDataStoreDao() {
+             return Mockito.mock(PrimaryDataStoreDao.class);
+         }
+ 
+         @Bean
+         public CapacityDao capacityDao() {
+             return Mockito.mock(CapacityDao.class);
+         }
+ 
+         @Bean
+         public AccountManager accountManager() {
+             return Mockito.mock(AccountManager.class);
+         }
+ 
+         @Bean
+         public StorageManager storageManager() {
+             return Mockito.mock(StorageManager.class);
+         }
+ 
+         @Bean
+         public DataStoreManager dataStoreManager() {
+             return Mockito.mock(DataStoreManager.class);
+         }
+ 
+         @Bean
+         public ClusterDetailsDao clusterDetailsDao() {
+             return Mockito.mock(ClusterDetailsDao.class);
+         }
+ 
+         @Bean
+         public ServiceOfferingDao serviceOfferingDao() {
+             return Mockito.mock(ServiceOfferingDao.class);
+         }
+ 
+         @Bean
+         public ServiceOfferingDetailsDao serviceOfferingDetailsDao() {
+             return Mockito.mock(ServiceOfferingDetailsDao.class);
+         }
+ 
+         @Bean
+         public ResourceManager resourceManager() {
+             return Mockito.mock(ResourceManager.class);
+         }
+ 
+         public static class Library implements TypeFilter {
+             @Override
+             public boolean match(MetadataReader mdr, MetadataReaderFactory arg1) throws IOException {
+                 ComponentScan cs = TestConfiguration.class.getAnnotation(ComponentScan.class);
+                 return SpringUtils.includedInBasePackageClasses(mdr.getClassMetadata().getClassName(), cs);
+             }
+         }
+     }
+ }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/05cb7342/plugins/deployment-planners/user-concentrated-pod/src/com/cloud/deploy/UserConcentratedPodPlanner.java
----------------------------------------------------------------------
diff --cc plugins/deployment-planners/user-concentrated-pod/src/com/cloud/deploy/UserConcentratedPodPlanner.java
index dc58516,d917893..27ff5bc
--- a/plugins/deployment-planners/user-concentrated-pod/src/com/cloud/deploy/UserConcentratedPodPlanner.java
+++ b/plugins/deployment-planners/user-concentrated-pod/src/com/cloud/deploy/UserConcentratedPodPlanner.java
@@@ -24,18 -24,17 +24,16 @@@ import javax.ejb.Local
  
  import org.apache.log4j.Logger;
  
- import com.cloud.hypervisor.Hypervisor.HypervisorType;
  import com.cloud.utils.Pair;
  import com.cloud.vm.VirtualMachineProfile;
  
  @Local(value=DeploymentPlanner.class)
- public class UserConcentratedPodPlanner extends FirstFitPlanner implements DeploymentPlanner {
+ public class UserConcentratedPodPlanner extends FirstFitPlanner implements DeploymentClusterPlanner {
  
      private static final Logger s_logger = Logger.getLogger(UserConcentratedPodPlanner.class);
 -
 +    
      /**
 -     * This method should reorder the given list of Cluster Ids by applying any necessary heuristic
 +     * This method should reorder the given list of Cluster Ids by applying any necessary heuristic 
       * for this planner
       * For UserConcentratedPodPlanner we need to order the clusters in a zone across pods, by considering those pods first which have more number of VMs for this account
       * This reordering is not done incase the clusters within single pod are passed when the allocation is applied at pod-level.
@@@ -138,18 -137,7 +136,6 @@@
          }else{
              return podIdsByCapacity;
          }
 -
 +        
      }
--
-     @Override
-     public boolean canHandle(VirtualMachineProfile vm, DeploymentPlan plan, ExcludeList avoid) {
-         if(vm.getHypervisorType() != HypervisorType.BareMetal){
-             //check the allocation strategy
-             if (_allocationAlgorithm != null && (_allocationAlgorithm.equals(AllocationAlgorithm.userconcentratedpod_random.toString()) || _allocationAlgorithm.equals(AllocationAlgorithm.userconcentratedpod_firstfit.toString()))){
-                 return true;
-             }
-         }
-         return false;
-     }
- 
  }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/05cb7342/plugins/deployment-planners/user-dispersing/src/com/cloud/deploy/UserDispersingPlanner.java
----------------------------------------------------------------------
diff --cc plugins/deployment-planners/user-dispersing/src/com/cloud/deploy/UserDispersingPlanner.java
index 21d34a3,2b0b158..85c2bb9
--- a/plugins/deployment-planners/user-dispersing/src/com/cloud/deploy/UserDispersingPlanner.java
+++ b/plugins/deployment-planners/user-dispersing/src/com/cloud/deploy/UserDispersingPlanner.java
@@@ -29,10 -29,9 +29,8 @@@ import javax.naming.ConfigurationExcept
  import org.apache.log4j.Logger;
  
  import com.cloud.configuration.Config;
- import com.cloud.hypervisor.Hypervisor.HypervisorType;
  import com.cloud.utils.NumbersUtil;
  import com.cloud.utils.Pair;
--import com.cloud.vm.VirtualMachine;
  import com.cloud.vm.VirtualMachineProfile;
  
  @Local(value=DeploymentPlanner.class)

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/05cb7342/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpElement.java
----------------------------------------------------------------------
diff --cc plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpElement.java
index d5a839a,fdf8b63..e9d5499
--- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpElement.java
+++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpElement.java
@@@ -5,34 -5,22 +5,31 @@@
  // 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.
--// 
++//
  // Automatically generated by addcopyright.py at 01/29/2013
  package com.cloud.baremetal.networkservice;
  
 +import java.util.HashMap;
- import java.util.List;
 +import java.util.Map;
 +import java.util.Set;
 +
 +import javax.ejb.Local;
 +import javax.inject.Inject;
- import javax.naming.ConfigurationException;
 +
 +import org.apache.log4j.Logger;
 +
  import com.cloud.baremetal.database.BaremetalDhcpVO;
- import com.cloud.baremetal.database.BaremetalPxeVO;
- import com.cloud.dc.Pod;
  import com.cloud.dc.DataCenter.NetworkType;
+ import com.cloud.dc.Pod;
  import com.cloud.deploy.DeployDestination;
  import com.cloud.exception.ConcurrentOperationException;
  import com.cloud.exception.InsufficientCapacityException;
@@@ -56,13 -43,16 +52,12 @@@ import com.cloud.utils.db.SearchCriteri
  import com.cloud.utils.db.SearchCriteria2;
  import com.cloud.utils.db.SearchCriteriaService;
  import com.cloud.utils.db.Transaction;
 -import com.cloud.vm.*;
 +import com.cloud.vm.NicProfile;
 +import com.cloud.vm.NicVO;
 +import com.cloud.vm.ReservationContext;
- import com.cloud.vm.VirtualMachine;
  import com.cloud.vm.VirtualMachine.Type;
- import com.cloud.vm.dao.NicDao;
 +import com.cloud.vm.VirtualMachineProfile;
+ import com.cloud.vm.dao.NicDao;
 -import org.apache.log4j.Logger;
 -
 -import javax.ejb.Local;
 -import javax.inject.Inject;
 -import java.util.HashMap;
 -import java.util.Map;
 -import java.util.Set;
  
  @Local(value = NetworkElement.class)
  public class BaremetalDhcpElement extends AdapterBase implements DhcpServiceProvider {
@@@ -168,11 -158,22 +163,24 @@@
          return true;
      }
      
 -    public boolean addDhcpEntry(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest,
++    @Override
 +    public boolean addDhcpEntry(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest,
              ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException {
          if (vm.getHypervisorType() != HypervisorType.BareMetal || !canHandle(dest, network.getTrafficType(), network.getGuestType())) {
              return false;
          }
          return _dhcpMgr.addVirtualMachineIntoNetwork(network, nic, vm, dest, context);
      }
+ 
+     @Override
 -    public boolean configDhcpSupportForSubnet(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException {
++    public boolean configDhcpSupportForSubnet(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context)
++            throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException {
+         return false;  //To change body of implemented methods use File | Settings | File Templates.
+     }
+ 
+     @Override
+     public boolean removeDhcpSupportForSubnet(Network network) {
+         return false;  //To change body of implemented methods use File | Settings | File Templates.
+     }
+ 
  }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/05cb7342/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/05cb7342/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
----------------------------------------------------------------------
diff --cc plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
index 68dc7d1,be47754..05613a8
--- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
+++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
@@@ -1172,20 -1183,38 +1184,38 @@@ public class VmwareResource implements 
              NicTO nic = cmd.getNic();
              int ethDeviceNum = findRouterEthDeviceIndex(routerName, routerIp, nic.getMac());
              String args = "";
+             Pair<Boolean, String> result;
+ 
+             if (privateGw != null) {
+                 s_logger.debug("Private gateway configuration is set");
+                 args += " -d " + "eth" + ethDeviceNum;
+                 args += " -a " + sb.toString();
+                 result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null,
+                         "/opt/cloud/bin/vpc_privategw_acl.sh " + args);
+ 
+                 if (!result.first()) {
+                     String msg = "SetNetworkACLAnswer on domain router " + routerIp + " failed. message: " + result.second();
+                     s_logger.error(msg);
+                 }
+ 
+                 return new SetNetworkACLAnswer(cmd, false, results);
+             } else {
+                 args="";
 -                args += " -d " + "eth" + ethDeviceNum;
 -                args += " -i " + nic.getIp();
 -                args += " -m " + Long.toString(NetUtils.getCidrSize(nic.getNetmask()));
 -                args += " -a " + sb.toString();
 +            args += " -d " + "eth" + ethDeviceNum;
 +            args += " -i " + nic.getIp();
 +            args += " -m " + Long.toString(NetUtils.getCidrSize(nic.getNetmask()));
 +            args += " -a " + sb.toString();
  
-             Pair<Boolean, String> result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null,
+                 result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null,
 -                        "/opt/cloud/bin/vpc_acl.sh " + args);
 +                    "/opt/cloud/bin/vpc_acl.sh " + args);
  
 -                if (!result.first()) {
 -                    String msg = "SetNetworkACLAnswer on domain router " + routerIp + " failed. message: " + result.second();
 -                    s_logger.error(msg);
 +            if (!result.first()) {
 +                String msg = "SetNetworkACLAnswer on domain router " + routerIp + " failed. message: " + result.second();
 +                s_logger.error(msg);
  
 -                    return new SetNetworkACLAnswer(cmd, false, results);
 -                }
 +                return new SetNetworkACLAnswer(cmd, false, results);
 +            }
+             }
  
              return new SetNetworkACLAnswer(cmd, true, results);
          } catch (Exception e) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/05cb7342/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
----------------------------------------------------------------------
diff --cc plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
index 157f3d0,19444cc..a84635e
--- a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
+++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
@@@ -1461,7 -1490,56 +1491,56 @@@ public abstract class CitrixResourceBas
              }
          }
      }
 -    
 +
+     private Answer execute(PvlanSetupCommand cmd) {
+     	Connection conn = getConnection();
+     	
+     	String primaryPvlan = cmd.getPrimary();
+     	String isolatedPvlan = cmd.getIsolated();
+     	String op = cmd.getOp();
+     	String dhcpName = cmd.getDhcpName();
+     	String dhcpMac = cmd.getDhcpMac();
+     	String dhcpIp = cmd.getDhcpIp();
+     	String vmMac = cmd.getVmMac();
+     	String networkTag = cmd.getNetworkTag();
+     	
+     	XsLocalNetwork nw = null;
+     	String nwNameLabel = null;
+     	try {
+ 			nw = getNativeNetworkForTraffic(conn, TrafficType.Guest, networkTag);
+ 			nwNameLabel = nw.getNetwork().getNameLabel(conn);
+ 		} catch (XenAPIException e) {
+ 			s_logger.warn("Fail to get network", e);
+     		return new Answer(cmd, false, e.toString());
+ 		} catch (XmlRpcException e) {
+ 			s_logger.warn("Fail to get network", e);
+     		return new Answer(cmd, false, e.toString());
+ 		}
+     	
+     	String result = null;
+     	if (cmd.getType() == PvlanSetupCommand.Type.DHCP) {
+     		result = callHostPlugin(conn, "ovs-pvlan", "setup-pvlan-dhcp", "op", op, "nw-label", nwNameLabel,
+     				"primary-pvlan", primaryPvlan, "isolated-pvlan", isolatedPvlan, "dhcp-name", dhcpName,
+     				"dhcp-ip", dhcpIp, "dhcp-mac", dhcpMac);
+     		if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) {
+     			s_logger.warn("Failed to program pvlan for dhcp server with mac " + dhcpMac);
+     			return new Answer(cmd, false, result);
+     		} else {
+     			s_logger.info("Programmed pvlan for dhcp server with mac " + dhcpMac);
+     		}
+     	} else if (cmd.getType() == PvlanSetupCommand.Type.VM) {
+     		result = callHostPlugin(conn, "ovs-pvlan", "setup-pvlan-vm", "op", op, "nw-label", nwNameLabel,
+     				"primary-pvlan", primaryPvlan, "isolated-pvlan", isolatedPvlan, "vm-mac", vmMac);
+     		if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) {
+     			s_logger.warn("Failed to program pvlan for vm with mac " + vmMac);
+     			return new Answer(cmd, false, result);
+     		} else {
+     			s_logger.info("Programmed pvlan for vm with mac " + vmMac);
+     		}
+     	}
+     	return new Answer(cmd, true, result);
+     }
+ 
      @Override
      public StartAnswer execute(StartCommand cmd) {
          Connection conn = getConnection();
@@@ -8101,21 -8244,42 +8254,42 @@@
                  sb.append(aclRules[i]).append(',');
              }
  
+             if (privateGw != null) {
+                 s_logger.debug("Private gateway configuration is set");
+             }
              NicTO nic = cmd.getNic();
              VIF vif = getVifByMac(conn, router, nic.getMac());
+ 
+             if (privateGw != null) {
+                 s_logger.debug("Private gateway configuration is set");
+                 String args = "vpc_privategw_acl.sh " + routerIp;
+                 args += " -d " + "eth" + vif.getDevice(conn);
+                 args += " -a " + sb.toString();
+ 
+                 callResult = callHostPlugin(conn, "vmops", "routerProxy", "args", args);
+                 if (callResult == null || callResult.isEmpty()) {
+                     //FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails
+                     for (int i=0; i < results.length; i++) {
+                         results[i] = "Failed";
+                     }
+                     return new SetNetworkACLAnswer(cmd, false, results);
+                 }
+             } else {
 -                String args = "vpc_acl.sh " + routerIp;
 -                args += " -d " + "eth" + vif.getDevice(conn);
 -                args += " -i " + nic.getIp();
 -                args += " -m " + Long.toString(NetUtils.getCidrSize(nic.getNetmask()));
 -                args += " -a " + sb.toString();
 +            String args = "vpc_acl.sh " + routerIp;
 +            args += " -d " + "eth" + vif.getDevice(conn);
 +            args += " -i " + nic.getIp();
 +            args += " -m " + Long.toString(NetUtils.getCidrSize(nic.getNetmask()));
 +            args += " -a " + sb.toString();
+ 
 -                callResult = callHostPlugin(conn, "vmops", "routerProxy", "args", args);
 -                if (callResult == null || callResult.isEmpty()) {
 -                    //FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails
 -                    for (int i=0; i < results.length; i++) {
 -                        results[i] = "Failed";
 -                    }
 -                    return new SetNetworkACLAnswer(cmd, false, results);
 +            callResult = callHostPlugin(conn, "vmops", "routerProxy", "args", args);
 +            if (callResult == null || callResult.isEmpty()) {
 +                //FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails
 +                for (int i=0; i < results.length; i++) {
 +                    results[i] = "Failed";
                  }
 +                return new SetNetworkACLAnswer(cmd, false, results);
 +            }
+             }
              return new SetNetworkACLAnswer(cmd, true, results);
          } catch (Exception e) {
              String msg = "SetNetworkACL failed due to " + e.toString();

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/05cb7342/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java
----------------------------------------------------------------------
diff --cc plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java
index 6a8058d,d0a9771..78a5dd5
--- a/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java
+++ b/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java
@@@ -934,18 -950,9 +938,21 @@@ public class InternalLoadBalancerVMMana
              throw new InvalidParameterValueException("Can't find internal lb vm by id specified");
          }
          
+         //check permissions
+         _accountMgr.checkAccess(caller, null, true, internalLbVm);
+         
          return startInternalLbVm(internalLbVm, caller, callerUserId, null);
      }
 +
 +    @Override
 +    public void vmWorkStart(VmWork work) {
 +        // TODO Auto-generated method stub
 +
 +    }
 +
 +    @Override
 +    public void vmWorkStop(VmWork work) {
 +        // TODO Auto-generated method stub
 +
 +    }
  }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/05cb7342/plugins/network-elements/midonet/src/com/cloud/network/element/MidoNetElement.java
----------------------------------------------------------------------
diff --cc plugins/network-elements/midonet/src/com/cloud/network/element/MidoNetElement.java
index 8bec006,ab6a6de..5e63658
--- a/plugins/network-elements/midonet/src/com/cloud/network/element/MidoNetElement.java
+++ b/plugins/network-elements/midonet/src/com/cloud/network/element/MidoNetElement.java
@@@ -19,10 -19,7 +19,37 @@@
  
  package com.cloud.network.element;
  
- import com.cloud.network.*;
- import com.cloud.network.element.SimpleFirewallRule;
++import java.util.ArrayList;
++import java.util.HashMap;
++import java.util.List;
++import java.util.Map;
++import java.util.Set;
++import java.util.UUID;
++
++import javax.ejb.Local;
++import javax.inject.Inject;
++import javax.naming.ConfigurationException;
++import javax.ws.rs.core.MultivaluedMap;
++
++import org.apache.log4j.Logger;
++import org.springframework.stereotype.Component;
++
++import com.midokura.midonet.client.MidonetApi;
++import com.midokura.midonet.client.dto.DtoRule;
++import com.midokura.midonet.client.resource.Bridge;
++import com.midokura.midonet.client.resource.BridgePort;
++import com.midokura.midonet.client.resource.DhcpHost;
++import com.midokura.midonet.client.resource.DhcpSubnet;
++import com.midokura.midonet.client.resource.Port;
++import com.midokura.midonet.client.resource.ResourceCollection;
++import com.midokura.midonet.client.resource.Route;
++import com.midokura.midonet.client.resource.Router;
++import com.midokura.midonet.client.resource.RouterPort;
++import com.midokura.midonet.client.resource.Rule;
++import com.midokura.midonet.client.resource.RuleChain;
++import com.sun.jersey.core.util.MultivaluedMapImpl;
++
  import com.cloud.agent.api.to.FirewallRuleTO;
- import com.cloud.agent.api.to.NetworkACLTO;
  import com.cloud.agent.api.to.PortForwardingRuleTO;
  import com.cloud.configuration.Config;
  import com.cloud.configuration.dao.ConfigurationDao;
@@@ -34,39 -32,55 +62,28 @@@ import com.cloud.network.Network
  import com.cloud.network.Network.Capability;
  import com.cloud.network.Network.Provider;
  import com.cloud.network.Network.Service;
+ import com.cloud.network.NetworkModel;
+ import com.cloud.network.Networks;
+ import com.cloud.network.PhysicalNetworkServiceProvider;
+ import com.cloud.network.PublicIpAddress;
  import com.cloud.network.rules.FirewallRule;
- import com.cloud.network.rules.StaticNat;
  import com.cloud.network.rules.PortForwardingRule;
- import com.cloud.network.addr.PublicIp;
+ import com.cloud.network.rules.StaticNat;
+ import com.cloud.network.vpc.VpcManager;
  import com.cloud.offering.NetworkOffering;
+ import com.cloud.user.AccountManager;
++import com.cloud.user.AccountVO;
++import com.cloud.user.dao.AccountDao;
  import com.cloud.utils.Pair;
  import com.cloud.utils.component.AdapterBase;
  import com.cloud.utils.component.PluggableService;
  import com.cloud.utils.net.NetUtils;
- import com.cloud.vm.*;
 -import com.cloud.user.AccountVO;
 -import com.cloud.user.dao.AccountDao;
+ import com.cloud.vm.NicProfile;
+ import com.cloud.vm.NicVO;
+ import com.cloud.vm.ReservationContext;
+ import com.cloud.vm.VirtualMachine;
+ import com.cloud.vm.VirtualMachineProfile;
  import com.cloud.vm.dao.NicDao;
- import com.google.common.collect.*;
- import com.cloud.user.AccountManager;
--import com.midokura.midonet.client.MidonetApi;
--import com.midokura.midonet.client.dto.DtoRule;
- import com.midokura.midonet.client.resource.*;
- import com.sun.jersey.core.util.MultivaluedMapImpl;
- import org.apache.log4j.Logger;
- import com.cloud.network.vpc.PrivateGateway;
- import com.cloud.network.vpc.StaticRouteProfile;
- import com.cloud.network.vpc.Vpc;
- import com.cloud.network.vpc.VpcGateway;
- import com.cloud.network.vpc.VpcManager;
- import org.springframework.stereotype.Component;
- 
- import javax.ejb.Local;
- import javax.naming.ConfigurationException;
- import javax.ws.rs.core.MultivaluedMap;
- import javax.inject.Inject;
- import java.util.*;
- import java.lang.Class;
- import java.util.Map;
- import java.util.Set;
 -import com.midokura.midonet.client.resource.Bridge;
 -import com.midokura.midonet.client.resource.BridgePort;
 -import com.midokura.midonet.client.resource.DhcpHost;
 -import com.midokura.midonet.client.resource.DhcpSubnet;
 -import com.midokura.midonet.client.resource.Port;
 -import com.midokura.midonet.client.resource.ResourceCollection;
 -import com.midokura.midonet.client.resource.Route;
 -import com.midokura.midonet.client.resource.Router;
 -import com.midokura.midonet.client.resource.RouterPort;
 -import com.midokura.midonet.client.resource.Rule;
 -import com.midokura.midonet.client.resource.RuleChain;
 -import com.sun.jersey.core.util.MultivaluedMapImpl;
 -import org.apache.log4j.Logger;
 -import org.springframework.stereotype.Component;
 -
 -import javax.ejb.Local;
 -import javax.inject.Inject;
 -import javax.naming.ConfigurationException;
 -import javax.ws.rs.core.MultivaluedMap;
 -import java.util.ArrayList;
 -import java.util.HashMap;
 -import java.util.List;
 -import java.util.Map;
 -import java.util.Set;
 -import java.util.UUID;
  
  
  @Component
@@@ -124,8 -138,8 +141,8 @@@ public class MidoNetElement extends Ada
          this.api = api;
      }
  
-     public void setNtwkSrvcDao(NetworkServiceMapDao ntwkSrvcDao){
-         this._ntwkSrvcDao = ntwkSrvcDao;
+     public void setAccountDao(AccountDao aDao) {
 -        this._accountDao = aDao;
++        _accountDao = aDao;
      }
  
      @Override
@@@ -138,31 -152,34 +155,34 @@@
              throws ConfigurationException {
          super.configure(name, params);
  
--        String routerIdValue = (String) _configDao.getValue(Config.MidoNetProviderRouterId.key());
++        String routerIdValue = _configDao.getValue(Config.MidoNetProviderRouterId.key());
          if(routerIdValue != null)
              _providerRouterId = UUID.fromString(routerIdValue);
  
--        String value = (String) _configDao.getValue(Config.MidoNetAPIServerAddress.key());
++        String value = _configDao.getValue(Config.MidoNetAPIServerAddress.key());
  
          if (value == null) {
              throw new ConfigurationException(
                  "Could not find midonet API location in config");
          }
  
--        if (this.api == null) {
++        if (api == null) {
              s_logger.info("midonet API server address is  " + value);
              setMidonetApi(new MidonetApi(value));
--            this.api.enableLogging();
++            api.enableLogging();
          }
  
          return true;
      }
  
      public boolean midoInNetwork(Network network) {
-         for (String pname : _ntwkSrvcDao.getDistinctProviders(network.getId())) {
-             if (pname.equals(getProvider().getName())) {
+         if((network.getTrafficType() == Networks.TrafficType.Public) &&
+            (network.getBroadcastDomainType() == Networks.BroadcastDomainType.Mido)){
 -            return true;
 -        }
 +                return true;
 +            }
+         if((network.getTrafficType() == Networks.TrafficType.Guest) &&
+            (network.getBroadcastDomainType() == Networks.BroadcastDomainType.Mido)){
+             return true;
          }
          return false;
      }
@@@ -338,7 -360,7 +363,7 @@@
              throws ResourceUnavailableException {
  
          s_logger.debug("applyIps called with network: " + network.toString());
--        if (!this.midoInNetwork(network)) {
++        if (!midoInNetwork(network)) {
              return false;
          }
  
@@@ -374,7 -396,7 +399,7 @@@
          throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException {
  
          s_logger.debug("addDhcpEntry called with network: " + network.toString() + " nic: " + nic.toString() + " vm: " + vm.toString());
--        if (!this.midoInNetwork(network)) {
++        if (!midoInNetwork(network)) {
              return false;
          }
          if (vm.getType() != VirtualMachine.Type.User) {
@@@ -432,6 -454,16 +457,17 @@@
          return true;
      }
  
+     @Override
 -    public boolean configDhcpSupportForSubnet(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException {
++    public boolean configDhcpSupportForSubnet(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context)
++            throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException {
+         return false;  //To change body of implemented methods use File | Settings | File Templates.
+     }
+ 
+     @Override
+     public boolean removeDhcpSupportForSubnet(Network network) {
+         return false;  //To change body of implemented methods use File | Settings | File Templates.
+     }
+ 
      private void removeMidonetStaticNAT(RuleChain preFilter, RuleChain preNat, RuleChain postNat,
                                          String floatingIp, String fixedIp,
                                          Router providerRouter) {
@@@ -1441,14 -1488,13 +1492,13 @@@
          return netBridge;
      }
  
-     private Bridge getNetworkBridge(long networkID, long accountID){
+     private Bridge getNetworkBridge(long networkID, String accountUuid){
  
          MultivaluedMap qNetBridge = new MultivaluedMapImpl();
-         String accountIdStr = String.valueOf(accountID);
          String networkUUIDStr = String.valueOf(networkID);
-         qNetBridge.add("tenant_id", accountIdStr);
+         qNetBridge.add("tenant_id", accountUuid);
  
--        for (Bridge b : this. api.getBridges(qNetBridge)) {
++        for (Bridge b : api.getBridges(qNetBridge)) {
              if(b.getName().equals(networkUUIDStr)){
                  return b;
              }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/05cb7342/plugins/network-elements/midonet/src/com/cloud/network/guru/MidoNetGuestNetworkGuru.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/05cb7342/plugins/network-elements/midonet/src/com/cloud/network/guru/MidoNetPublicNetworkGuru.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/05cb7342/plugins/network-elements/midonet/test/com/cloud/network/element/MidoNetElementTest.java
----------------------------------------------------------------------
diff --cc plugins/network-elements/midonet/test/com/cloud/network/element/MidoNetElementTest.java
index 3763047,baf99b9..de07ba8
--- a/plugins/network-elements/midonet/test/com/cloud/network/element/MidoNetElementTest.java
+++ b/plugins/network-elements/midonet/test/com/cloud/network/element/MidoNetElementTest.java
@@@ -16,9 -16,10 +16,11 @@@
   * specific language governing permissions and limitations
   * under the License.
   */
 +package com.cloud.network.element;
  
  import com.cloud.network.element.MidoNetElement;
+ import com.cloud.user.AccountVO;
+ import com.cloud.user.dao.AccountDao;
  import junit.framework.TestCase;
  import static org.junit.Assert.assertEquals;
  import static org.mockito.Mockito.*;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/05cb7342/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerElement.java
----------------------------------------------------------------------
diff --cc plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerElement.java
index f31bbcf,850962d..0650ea2
--- a/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerElement.java
+++ b/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerElement.java
@@@ -950,21 -950,30 +950,30 @@@ public class NetscalerElement extends E
          return true;
      }
  
-     private ExternalLoadBalancerDeviceVO findGslbProvider(long zoneId) {
+     private ExternalLoadBalancerDeviceVO findGslbProvider(long zoneId, long physicalNetworkId) {
          List<PhysicalNetworkVO> pNtwks = _physicalNetworkDao.listByZoneAndTrafficType(zoneId, TrafficType.Guest);
-         if (pNtwks.isEmpty() || pNtwks.size() > 1) {
-             throw new InvalidParameterValueException("Unable to get physical network in zone id = " + zoneId);
-         }
+ 
+         if (pNtwks == null || pNtwks.isEmpty()) {
+             throw new InvalidParameterValueException("Unable to get physical network: " + physicalNetworkId +
+                     " in zone id = " + zoneId);
+         } else {
+             for (PhysicalNetwork physicalNetwork : pNtwks) {
+                 if (physicalNetwork.getId() == physicalNetworkId) {
 -                    PhysicalNetworkVO physNetwork = pNtwks.get(0);
 -                    ExternalLoadBalancerDeviceVO nsGslbProvider = _externalLoadBalancerDeviceDao.findGslbServiceProvider(
 -                            physNetwork.getId(), Provider.Netscaler.getName());
 -                    return nsGslbProvider;
 -                }
 +        PhysicalNetworkVO physNetwork = pNtwks.get(0);
 +        ExternalLoadBalancerDeviceVO nsGslbProvider = _externalLoadBalancerDeviceDao.findGslbServiceProvider(
 +                physNetwork.getId(), Provider.Netscaler.getName());
 +        return nsGslbProvider;
 +    }
+             }
+         }
+ 
+         return null;
+     }
  
      @Override
-     public boolean isServiceEnabledInZone(long zoneId) {
+     public boolean isServiceEnabledInZone(long zoneId, long physicalNetworkId) {
  
-         ExternalLoadBalancerDeviceVO nsGslbProvider = findGslbProvider(zoneId);
+         ExternalLoadBalancerDeviceVO nsGslbProvider = findGslbProvider(zoneId, physicalNetworkId);
          //return true if a NetScaler device is configured in the zone
          return (nsGslbProvider != null);
      }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/05cb7342/server/pom.xml
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/05cb7342/server/src/com/cloud/agent/manager/allocator/impl/FirstFitAllocator.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/agent/manager/allocator/impl/FirstFitAllocator.java
index 8fddd02,b6286aa..29ba837
--- a/server/src/com/cloud/agent/manager/allocator/impl/FirstFitAllocator.java
+++ b/server/src/com/cloud/agent/manager/allocator/impl/FirstFitAllocator.java
@@@ -168,7 -168,14 +168,14 @@@ public class FirstFitAllocator extends 
                  }
              }
          }
 -
 +        
+         // add all hosts that we are not considering to the avoid list
+         List<HostVO> allhostsInCluster = _hostDao.listAllUpAndEnabledNonHAHosts(type, clusterId, podId, dcId, null);
+         allhostsInCluster.removeAll(clusterHosts);
+         for (HostVO host : allhostsInCluster) {
+             avoid.addHost(host.getId());
+         }
+ 
          return allocateTo(plan, offering, template, avoid, clusterHosts, returnUpTo, considerReservedCapacity, account);
      }
  
@@@ -285,9 -292,10 +292,10 @@@
                  if (s_logger.isDebugEnabled()) {
                      s_logger.debug("Not using host " + host.getId() + "; numCpusGood: " + numCpusGood + "; cpuFreqGood: " + cpuFreqGood + ", host has capacity?" + hostHasCapacity);
                  }
+                 avoid.addHost(host.getId());
              }
          }
 -
 +        
          if (s_logger.isDebugEnabled()) {
              s_logger.debug("Host Allocator returning "+suitableHosts.size() +" suitable hosts");
          }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/05cb7342/server/src/com/cloud/api/ApiDBUtils.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/api/ApiDBUtils.java
index 5a86160,1afedac..08cad37
--- a/server/src/com/cloud/api/ApiDBUtils.java
+++ b/server/src/com/cloud/api/ApiDBUtils.java
@@@ -25,8 -25,21 +25,6 @@@ import java.util.Set
  import javax.annotation.PostConstruct;
  import javax.inject.Inject;
  
- import org.springframework.stereotype.Component;
--
 -import com.cloud.network.rules.LoadBalancer;
 -import com.cloud.network.vpc.NetworkACL;
 -import com.cloud.network.vpc.StaticRouteVO;
 -import com.cloud.network.vpc.VpcGatewayVO;
 -import com.cloud.network.vpc.VpcManager;
 -import com.cloud.network.vpc.VpcOffering;
 -import com.cloud.network.vpc.VpcProvisioningService;
 -import com.cloud.network.vpc.VpcVO;
 -import com.cloud.network.vpc.dao.NetworkACLDao;
 -import com.cloud.network.vpc.dao.StaticRouteDao;
 -import com.cloud.network.vpc.dao.VpcDao;
 -import com.cloud.network.vpc.dao.VpcGatewayDao;
 -import com.cloud.network.vpc.dao.VpcOfferingDao;
 -import com.cloud.region.ha.GlobalLoadBalancingRulesService;
  import org.apache.cloudstack.affinity.AffinityGroup;
  import org.apache.cloudstack.affinity.AffinityGroupResponse;
  import org.apache.cloudstack.affinity.dao.AffinityGroupDao;
@@@ -186,16 -202,6 +184,18 @@@ import com.cloud.network.security.Secur
  import com.cloud.network.security.SecurityGroupManager;
  import com.cloud.network.security.SecurityGroupVO;
  import com.cloud.network.security.dao.SecurityGroupDao;
++import com.cloud.network.vpc.NetworkACL;
 +import com.cloud.network.vpc.StaticRouteVO;
 +import com.cloud.network.vpc.VpcGatewayVO;
 +import com.cloud.network.vpc.VpcManager;
 +import com.cloud.network.vpc.VpcOffering;
 +import com.cloud.network.vpc.VpcProvisioningService;
 +import com.cloud.network.vpc.VpcVO;
++import com.cloud.network.vpc.dao.NetworkACLDao;
 +import com.cloud.network.vpc.dao.StaticRouteDao;
 +import com.cloud.network.vpc.dao.VpcDao;
 +import com.cloud.network.vpc.dao.VpcGatewayDao;
 +import com.cloud.network.vpc.dao.VpcOfferingDao;
  import com.cloud.offering.DiskOffering;
  import com.cloud.offering.NetworkOffering;
  import com.cloud.offering.ServiceOffering;
@@@ -287,7 -292,7 +287,6 @@@ import com.cloud.vm.dao.VMInstanceDao
  import com.cloud.vm.snapshot.VMSnapshot;
  import com.cloud.vm.snapshot.dao.VMSnapshotDao;
  
--@Component
  public class ApiDBUtils {
      private static ManagementServer _ms;
      static AsyncJobManager _asyncMgr;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/05cb7342/server/src/com/cloud/api/ApiDispatcher.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/05cb7342/server/src/com/cloud/api/ApiResponseHelper.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/api/ApiResponseHelper.java
index 0934655,49e36dc..65f8f91
--- a/server/src/com/cloud/api/ApiResponseHelper.java
+++ b/server/src/com/cloud/api/ApiResponseHelper.java
@@@ -229,10 -237,6 +230,12 @@@ import com.cloud.network.security.Secur
  import com.cloud.network.security.SecurityGroupVO;
  import com.cloud.network.security.SecurityRule;
  import com.cloud.network.security.SecurityRule.SecurityRuleType;
++import com.cloud.network.vpc.NetworkACL;
++import com.cloud.network.vpc.NetworkACLItem;
 +import com.cloud.network.vpc.PrivateGateway;
 +import com.cloud.network.vpc.StaticRoute;
 +import com.cloud.network.vpc.Vpc;
 +import com.cloud.network.vpc.VpcOffering;
  import com.cloud.offering.DiskOffering;
  import com.cloud.offering.NetworkOffering;
  import com.cloud.offering.NetworkOffering.Detail;
@@@ -3829,4 -3850,18 +3845,19 @@@ public class ApiResponseHelper implemen
          response.setObjectName("isolationmethod");
          return response;
      }
+ 
+ 
++    @Override
+     public NetworkACLResponse createNetworkACLResponse(NetworkACL networkACL) {
+         NetworkACLResponse response = new NetworkACLResponse();
+         response.setId(networkACL.getUuid());
+         response.setName(networkACL.getName());
+         response.setDescription(networkACL.getDescription());
+         Vpc vpc = ApiDBUtils.findVpcById(networkACL.getVpcId());
+         if(vpc != null){
+             response.setVpcId(vpc.getUuid());
+         }
+         response.setObjectName("networkacllist");
+         return response;
+     }
  }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/05cb7342/server/src/com/cloud/configuration/ConfigurationManager.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/05cb7342/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/configuration/ConfigurationManagerImpl.java
index 0535b1c,52d6176..b34c939
--- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
+++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
@@@ -138,7 -143,8 +142,8 @@@ import com.cloud.network.dao.PhysicalNe
  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.rules.LoadBalancerContainer.Scheme;
  import com.cloud.network.vpc.VpcManager;
  import com.cloud.offering.DiskOffering;
  import com.cloud.offering.NetworkOffering;
@@@ -184,13 -192,69 +191,17 @@@ import com.cloud.utils.db.SearchCriteri
  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;
 +import edu.emory.mathcs.backport.java.util.Arrays;
  
 -@Component
  @Local(value = { ConfigurationManager.class, ConfigurationService.class })
 -public class ConfigurationManagerImpl extends ManagerBase implements ConfigurationManager, ConfigurationService {
 +public class ConfigurationManagerImpl extends ManagerBase implements ConfigurationManager, ConfigurationService, ConfigRepo {
      public static final Logger s_logger = Logger.getLogger(ConfigurationManagerImpl.class.getName());
  
      @Inject
@@@ -1830,8 -1903,8 +1850,8 @@@
  
                  userNetwork.setBroadcastDomainType(broadcastDomainType);
                  userNetwork.setNetworkDomain(networkDomain);
 -                _networkMgr.setupNetwork(systemAccount, offering, userNetwork, plan, null, null, false, 
 +                _networkMgr.setupNetwork(systemAccount, offering, userNetwork, plan, null, null, false,
-                         Domain.ROOT_DOMAIN, null, null, null);
+                         Domain.ROOT_DOMAIN, null, null, null, true);
              }
          }
      }
@@@ -2414,44 -2509,30 +2456,30 @@@
                      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());
-                 if ( vlans != null && vlans.size() > 0 ) {
 -                VlanVO vlan = vlans.get(0);
 +                    VlanVO vlan = vlans.get(0);
+                 if ( vlans != null && vlans.size() > 0 ) {
                      if ( vlanId == null ) {
                          vlanId = vlan.getVlanTag();
-                     } else if ( vlan.getVlanTag() != vlanId ) {
+                     } else if (!vlan.getVlanTag().equals(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);
 -                }
 +                    }
+                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 (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");
          }
  
@@@ -2472,8 -2552,12 +2499,12 @@@
          Transaction txn = Transaction.currentTxn();
          txn.start();
  
 -        Vlan vlan = createVlanAndPublicIpRange(zoneId, networkId, physicalNetworkId, forVirtualNetwork, podId, startIP, 
 +        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();
  
@@@ -2539,8 -2681,10 +2628,10 @@@
              if (uri != null) {
                  String[] vlan = uri.toString().split("vlan:\\/\\/");
                  networkVlanId = vlan[1];
+                 //For pvlan
+                 networkVlanId = networkVlanId.split("-")[0];
              }
 -
 +            
              if (vlanId != null) {
                  // if vlan is specified, throw an error if it's not equal to network's vlanId
                  if (networkVlanId != null && !networkVlanId.equalsIgnoreCase(vlanId)) {
@@@ -2699,22 -2843,8 +2790,8 @@@
              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) {
          	ipRange = startIP;
          	if (endIP != null) {
@@@ -2762,14 -2894,14 +2841,14 @@@
  
      @Override
      @DB
 -    public boolean deleteVlanAndPublicIpRange(long userId, long vlanDbId, Account caller)  {
 +    public boolean deleteVlanAndPublicIpRange(long userId, long vlanDbId, Account caller) {
-         VlanVO vlan = _vlanDao.findById(vlanDbId);
-         if (vlan == null) {
+         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;
@@@ -2815,9 -2947,7 +2894,7 @@@
                      }
                  } finally {
                      _vlanDao.releaseFromLockTable(vlanDbId);
 -                } 
 +                }
-             } else {
-                 throw new InvalidParameterValueException("The IP range can't be deleted because it has allocated public IP addresses.");
              }
          }
  
@@@ -2835,14 -2961,114 +2908,114 @@@
                              ip.getSystem(), ip.getClass().getName(), ip.getUuid());
                  }
              }
- 
-             // Delete the VLAN
-             return _vlanDao.expunge(vlanDbId);
+             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 {
 +        } 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;
 -                                    }
 +            return false;
 +        }
+                                     _vlanDao.expunge(vlanDbId);
+                                     txn.commit();
+                                     txn.close();
+                                 }
+                             }
+                         }
 -                    }
++    }
+                 }
+ 
+             }
+         }
+        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)


Mime
View raw message