cloudstack-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ahu...@apache.org
Subject [18/50] [abbrv] CLOUDSTACK-747: Internal LB between VPC tiers support
Date Tue, 14 May 2013 00:42:41 GMT
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2660a6b7/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbelement/InternalLbElementServiceTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbelement/InternalLbElementServiceTest.java b/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbelement/InternalLbElementServiceTest.java
new file mode 100644
index 0000000..f0e951c
--- /dev/null
+++ b/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbelement/InternalLbElementServiceTest.java
@@ -0,0 +1,190 @@
+// 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.internallbelement;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import javax.inject.Inject;
+
+import org.apache.cloudstack.network.element.InternalLoadBalancerElementService;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mockito;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.network.VirtualRouterProvider;
+import com.cloud.network.VirtualRouterProvider.VirtualRouterProviderType;
+import com.cloud.network.dao.PhysicalNetworkServiceProviderDao;
+import com.cloud.network.dao.PhysicalNetworkServiceProviderVO;
+import com.cloud.network.dao.VirtualRouterProviderDao;
+import com.cloud.network.element.VirtualRouterProviderVO;
+import com.cloud.user.AccountManager;
+import com.cloud.utils.component.ComponentContext;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(locations="classpath:/lb_element.xml")
+public class InternalLbElementServiceTest {
+    //The interface to test
+    @Inject InternalLoadBalancerElementService _lbElSvc;
+    
+    //Mocked interfaces
+    @Inject AccountManager _accountMgr;
+    @Inject VirtualRouterProviderDao _vrProviderDao;
+    @Inject PhysicalNetworkServiceProviderDao _pNtwkProviderDao;
+    
+    long validElId = 1L;
+    long nonExistingElId = 2L;
+    long invalidElId = 3L; //not of VirtualRouterProviderType
+    
+    long validProviderId = 1L;
+    long nonExistingProviderId = 2L;
+    long invalidProviderId = 3L;
+        
+
+    @Before
+    public void setUp() {
+        
+        ComponentContext.initComponentsLifeCycle();
+        VirtualRouterProviderVO validElement = new VirtualRouterProviderVO(1, VirtualRouterProviderType.InternalLbVm);
+        VirtualRouterProviderVO invalidElement = new VirtualRouterProviderVO(1, VirtualRouterProviderType.VirtualRouter);
+        
+        Mockito.when(_vrProviderDao.findById(validElId)).thenReturn(validElement);
+        Mockito.when(_vrProviderDao.findById(invalidElId)).thenReturn(invalidElement);
+        
+        Mockito.when(_vrProviderDao.persist(validElement)).thenReturn(validElement);
+        
+        Mockito.when(_vrProviderDao.findByNspIdAndType(validProviderId, VirtualRouterProviderType.InternalLbVm)).thenReturn(validElement);
+        
+        PhysicalNetworkServiceProviderVO validProvider = new PhysicalNetworkServiceProviderVO(1, "InternalLoadBalancerElement");
+        PhysicalNetworkServiceProviderVO invalidProvider = new PhysicalNetworkServiceProviderVO(1, "Invalid name!");
+
+        Mockito.when(_pNtwkProviderDao.findById(validProviderId)).thenReturn(validProvider);
+        Mockito.when(_pNtwkProviderDao.findById(invalidProviderId)).thenReturn(invalidProvider);
+        
+        Mockito.when(_vrProviderDao.persist(Mockito.any(VirtualRouterProviderVO.class))).thenReturn(validElement); 
+    }
+    
+    //TESTS FOR getInternalLoadBalancerElement METHOD
+    
+    
+    @Test (expected = InvalidParameterValueException.class)
+    public void findNonExistingVm() {
+        String expectedExcText = null;
+        try {
+            _lbElSvc.getInternalLoadBalancerElement(nonExistingElId); 
+        } catch (InvalidParameterValueException e) {
+            expectedExcText = e.getMessage();
+            throw e;
+        } finally {
+            assertEquals("Test failed. The non-existing intenral lb provider was found"
+        + expectedExcText, expectedExcText, "Unable to find InternalLoadBalancerElementService by id");
+        }
+    }
+    
+    
+    @Test (expected = InvalidParameterValueException.class)
+    public void findInvalidVm() {
+        String expectedExcText = null;
+        try {
+            _lbElSvc.getInternalLoadBalancerElement(invalidElId); 
+        } catch (InvalidParameterValueException e) {
+            expectedExcText = e.getMessage();
+            throw e;
+        } finally {
+            assertEquals("Test failed. The non-existing intenral lb provider was found"
+                    + expectedExcText, expectedExcText, "Unable to find InternalLoadBalancerElementService by id");
+        }
+    }
+    
+    
+    @Test
+    public void findValidVm() {
+        VirtualRouterProvider provider = null;
+        try {
+            provider = _lbElSvc.getInternalLoadBalancerElement(validElId); 
+        } finally {
+            assertNotNull("Test failed. Couldn't find the VR provider by the valid id",provider); 
+        }
+    }
+    
+    
+    //TESTS FOR configureInternalLoadBalancerElement METHOD
+    
+    @Test (expected = InvalidParameterValueException.class)
+    public void configureNonExistingVm() {
+        
+        _lbElSvc.configureInternalLoadBalancerElement(nonExistingElId, true); 
+        
+    }
+    
+    
+    @Test (expected = InvalidParameterValueException.class)
+    public void ConfigureInvalidVm() {
+        _lbElSvc.configureInternalLoadBalancerElement(invalidElId, true);    
+    }
+    
+    
+    @Test
+    public void enableProvider() {
+        VirtualRouterProvider provider = null;
+        try {
+            provider = _lbElSvc.configureInternalLoadBalancerElement(validElId, true); 
+        } finally {
+            assertNotNull("Test failed. Couldn't find the VR provider by the valid id ",provider);
+            assertTrue("Test failed. The provider wasn't eanbled ", provider.isEnabled()); 
+        }
+    }
+    
+    @Test
+    public void disableProvider() {
+        VirtualRouterProvider provider = null;
+        try {
+            provider = _lbElSvc.configureInternalLoadBalancerElement(validElId, false); 
+        } finally {
+            assertNotNull("Test failed. Couldn't find the VR provider by the valid id ",provider);
+            assertFalse("Test failed. The provider wasn't disabled ", provider.isEnabled()); 
+        }
+    } 
+    
+    //TESTS FOR addInternalLoadBalancerElement METHOD
+    
+    @Test (expected = InvalidParameterValueException.class)
+    public void addToNonExistingProvider() {
+        
+        _lbElSvc.addInternalLoadBalancerElement(nonExistingProviderId); 
+        
+    }
+    
+    @Test (expected = InvalidParameterValueException.class)
+    public void addToInvalidProvider() {
+        _lbElSvc.addInternalLoadBalancerElement(invalidProviderId);   
+    }
+    
+    @Test
+    public void addToExistingProvider() {
+        _lbElSvc.addInternalLoadBalancerElement(validProviderId);
+    }
+
+}
+
+

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2660a6b7/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbelement/InternalLbElementTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbelement/InternalLbElementTest.java b/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbelement/InternalLbElementTest.java
new file mode 100644
index 0000000..f19612f
--- /dev/null
+++ b/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbelement/InternalLbElementTest.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 org.apache.cloudstack.internallbelement;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+
+import javax.inject.Inject;
+
+import org.apache.cloudstack.lb.ApplicationLoadBalancerRuleVO;
+import org.apache.cloudstack.network.element.InternalLoadBalancerElement;
+import org.apache.cloudstack.network.lb.InternalLoadBalancerVMManager;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mockito;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import com.cloud.agent.api.to.LoadBalancerTO;
+import com.cloud.configuration.ConfigurationManager;
+import com.cloud.dc.DataCenter.NetworkType;
+import com.cloud.dc.DataCenterVO;
+import com.cloud.exception.ResourceUnavailableException;
+import com.cloud.network.Network.Provider;
+import com.cloud.network.Network.Service;
+import com.cloud.network.VirtualRouterProvider.VirtualRouterProviderType;
+import com.cloud.network.addr.PublicIp;
+import com.cloud.network.dao.NetworkVO;
+import com.cloud.network.dao.PhysicalNetworkServiceProviderDao;
+import com.cloud.network.dao.PhysicalNetworkServiceProviderVO;
+import com.cloud.network.dao.VirtualRouterProviderDao;
+import com.cloud.network.element.VirtualRouterProviderVO;
+import com.cloud.network.lb.LoadBalancingRule;
+import com.cloud.network.rules.FirewallRule;
+import com.cloud.network.rules.LoadBalancerContainer.Scheme;
+import com.cloud.user.AccountManager;
+import com.cloud.utils.component.ComponentContext;
+import com.cloud.utils.net.Ip;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(locations="classpath:/lb_element.xml")
+public class InternalLbElementTest {
+    //The class to test
+    @Inject InternalLoadBalancerElement _lbEl;
+    
+    //Mocked interfaces
+    @Inject AccountManager _accountMgr;
+    @Inject VirtualRouterProviderDao _vrProviderDao;
+    @Inject PhysicalNetworkServiceProviderDao _pNtwkProviderDao;
+    @Inject InternalLoadBalancerVMManager _internalLbMgr;
+    @Inject ConfigurationManager _configMgr;
+    
+    long validElId = 1L;
+    long nonExistingElId = 2L;
+    long invalidElId = 3L; //not of VirtualRouterProviderType
+    long notEnabledElId = 4L;
+    
+    long validProviderId = 1L;
+    long nonExistingProviderId = 2L;
+    long invalidProviderId = 3L;
+        
+
+    @Before
+    public void setUp() {
+        
+        ComponentContext.initComponentsLifeCycle();
+        VirtualRouterProviderVO validElement = new VirtualRouterProviderVO(1, VirtualRouterProviderType.InternalLbVm);
+        validElement.setEnabled(true);
+        VirtualRouterProviderVO invalidElement = new VirtualRouterProviderVO(1, VirtualRouterProviderType.VirtualRouter);
+        VirtualRouterProviderVO notEnabledElement = new VirtualRouterProviderVO(1, VirtualRouterProviderType.InternalLbVm);
+ 
+        Mockito.when(_vrProviderDao.findByNspIdAndType(validElId, VirtualRouterProviderType.InternalLbVm)).thenReturn(validElement);
+        Mockito.when(_vrProviderDao.findByNspIdAndType(invalidElId, VirtualRouterProviderType.InternalLbVm)).thenReturn(invalidElement);
+        Mockito.when(_vrProviderDao.findByNspIdAndType(notEnabledElId, VirtualRouterProviderType.InternalLbVm)).thenReturn(notEnabledElement);
+
+        Mockito.when(_vrProviderDao.persist(validElement)).thenReturn(validElement);
+        
+        Mockito.when(_vrProviderDao.findByNspIdAndType(validProviderId, VirtualRouterProviderType.InternalLbVm)).thenReturn(validElement);
+        
+        PhysicalNetworkServiceProviderVO validProvider = new PhysicalNetworkServiceProviderVO(1, "InternalLoadBalancerElement");
+        PhysicalNetworkServiceProviderVO invalidProvider = new PhysicalNetworkServiceProviderVO(1, "Invalid name!");
+
+        Mockito.when(_pNtwkProviderDao.findById(validProviderId)).thenReturn(validProvider);
+        Mockito.when(_pNtwkProviderDao.findById(invalidProviderId)).thenReturn(invalidProvider);
+        
+        Mockito.when(_vrProviderDao.persist(Mockito.any(VirtualRouterProviderVO.class))).thenReturn(validElement);
+        
+        DataCenterVO dc = new DataCenterVO
+                (1L, null, null, null, null, null, null, null, null, null, NetworkType.Advanced, null, null);
+        Mockito.when(_configMgr.getZone(Mockito.anyLong())).thenReturn(dc);
+    }
+    
+    //TEST FOR getProvider() method
+    
+    @Test 
+    public void verifyProviderName() {  
+       Provider pr = _lbEl.getProvider();
+       assertEquals("Wrong provider is returned", pr.getName(), Provider.InternalLbVm.getName());
+    }
+    
+    //TEST FOR isReady() METHOD
+    
+    @Test 
+    public void verifyValidProviderState() {
+       PhysicalNetworkServiceProviderVO provider = new PhysicalNetworkServiceProviderVO();
+       provider = setId(provider, validElId);
+       boolean isReady = _lbEl.isReady(provider);
+       assertTrue("Valid provider is returned as not ready", isReady);
+    }
+    
+    
+    @Test 
+    public void verifyNonExistingProviderState() {
+       PhysicalNetworkServiceProviderVO provider = new PhysicalNetworkServiceProviderVO();
+       provider = setId(provider, nonExistingElId);
+       boolean isReady = _lbEl.isReady(provider);
+       assertFalse("Non existing provider is returned as ready", isReady);
+    }
+    
+    
+    @Test 
+    public void verifyInvalidProviderState() {
+       PhysicalNetworkServiceProviderVO provider = new PhysicalNetworkServiceProviderVO();
+       provider = setId(provider, invalidElId);
+       boolean isReady = _lbEl.isReady(provider);
+       assertFalse("Not valid provider is returned as ready", isReady);
+    }
+    
+    @Test 
+    public void verifyNotEnabledProviderState() {
+       PhysicalNetworkServiceProviderVO provider = new PhysicalNetworkServiceProviderVO();
+       provider = setId(provider, notEnabledElId);
+       boolean isReady = _lbEl.isReady(provider);
+       assertFalse("Not enabled provider is returned as ready", isReady);
+    }
+    
+    //TEST FOR canEnableIndividualServices METHOD
+    @Test 
+    public void verifyCanEnableIndividualSvc() {  
+       boolean result = _lbEl.canEnableIndividualServices();
+       assertTrue("Wrong value is returned by canEnableIndividualSvc", result);
+    }
+    
+    //TEST FOR verifyServicesCombination METHOD
+    @Test 
+    public void verifyServicesCombination() {  
+       boolean result = _lbEl.verifyServicesCombination(new HashSet<Service>());
+       assertTrue("Wrong value is returned by verifyServicesCombination", result);
+    }
+    
+    
+    //TEST FOR applyIps METHOD
+    @Test 
+    public void verifyApplyIps() throws ResourceUnavailableException {
+       List<PublicIp> ips = new ArrayList<PublicIp>();
+       boolean result = _lbEl.applyIps(new NetworkVO(), ips, new HashSet<Service>());
+       assertTrue("Wrong value is returned by applyIps method", result);
+    }
+    
+    
+    //TEST FOR updateHealthChecks METHOD
+    @Test 
+    public void verifyUpdateHealthChecks() throws ResourceUnavailableException {
+       List<LoadBalancerTO> check = _lbEl.updateHealthChecks(new NetworkVO(), new ArrayList<LoadBalancingRule>());
+       assertNull("Wrong value is returned by updateHealthChecks method", check);
+    }
+    
+    //TEST FOR validateLBRule METHOD
+    @Test 
+    public void verifyValidateLBRule() throws ResourceUnavailableException {
+        ApplicationLoadBalancerRuleVO lb = new ApplicationLoadBalancerRuleVO(null, null, 22, 22, "roundrobin",
+                1L, 1L, 1L, new Ip("10.10.10.1"), 1L, Scheme.Internal);
+        lb.setState(FirewallRule.State.Add);
+        
+        LoadBalancingRule rule = new LoadBalancingRule(lb, null,
+                null, null, new Ip("10.10.10.1"));
+        
+        
+        boolean result = _lbEl.validateLBRule(new NetworkVO(), rule);
+        assertTrue("Wrong value is returned by validateLBRule method", result);
+    }
+    
+    
+    private static PhysicalNetworkServiceProviderVO setId(PhysicalNetworkServiceProviderVO vo, long id) {
+        PhysicalNetworkServiceProviderVO voToReturn = vo;
+        Class<?> c = voToReturn.getClass();
+        try {
+            Field f = c.getDeclaredField("id");
+            f.setAccessible(true);
+            f.setLong(voToReturn, id);
+        } catch (NoSuchFieldException ex) {
+           return null;
+        } catch (IllegalAccessException ex) {
+            return null;
+        }
+        
+        return voToReturn;
+    }
+    
+    
+    
+}
+
+

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2660a6b7/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbvmmgr/InternalLBVMManagerTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbvmmgr/InternalLBVMManagerTest.java b/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbvmmgr/InternalLBVMManagerTest.java
new file mode 100644
index 0000000..a19a82e
--- /dev/null
+++ b/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbvmmgr/InternalLBVMManagerTest.java
@@ -0,0 +1,388 @@
+// 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.internallbvmmgr;
+
+import java.lang.reflect.Field;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.inject.Inject;
+
+import junit.framework.TestCase;
+
+import org.apache.cloudstack.lb.ApplicationLoadBalancerRuleVO;
+import org.apache.cloudstack.network.lb.InternalLoadBalancerVMManager;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mockito;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import com.cloud.agent.AgentManager;
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.manager.Commands;
+import com.cloud.dc.DataCenter.NetworkType;
+import com.cloud.dc.DataCenterVO;
+import com.cloud.dc.dao.DataCenterDao;
+import com.cloud.exception.AgentUnavailableException;
+import com.cloud.exception.ConcurrentOperationException;
+import com.cloud.exception.OperationTimedoutException;
+import com.cloud.exception.ResourceUnavailableException;
+import com.cloud.hypervisor.Hypervisor.HypervisorType;
+import com.cloud.network.NetworkModel;
+import com.cloud.network.dao.NetworkVO;
+import com.cloud.network.lb.LoadBalancingRule;
+import com.cloud.network.router.VirtualRouter;
+import com.cloud.network.router.VirtualRouter.Role;
+import com.cloud.network.rules.FirewallRule;
+import com.cloud.network.rules.LoadBalancerContainer.Scheme;
+import com.cloud.service.ServiceOfferingVO;
+import com.cloud.service.dao.ServiceOfferingDao;
+import com.cloud.user.Account;
+import com.cloud.user.AccountManager;
+import com.cloud.user.AccountVO;
+import com.cloud.user.User;
+import com.cloud.utils.component.ComponentContext;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.utils.net.Ip;
+import com.cloud.vm.DomainRouterVO;
+import com.cloud.vm.NicProfile;
+import com.cloud.vm.NicVO;
+import com.cloud.vm.VirtualMachine;
+import com.cloud.vm.VirtualMachine.State;
+import com.cloud.vm.VirtualMachineManager;
+import com.cloud.vm.dao.DomainRouterDao;
+import com.cloud.vm.dao.NicDao;
+
+/**
+ * Set of unittests for InternalLoadBalancerVMManager
+ *
+ */
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(locations="classpath:/lb_mgr.xml")
+public class InternalLBVMManagerTest extends TestCase {
+    //The interface to test
+    @Inject InternalLoadBalancerVMManager _lbVmMgr;
+    
+    //Mocked interfaces
+    @Inject AccountManager _accountMgr;
+    @Inject ServiceOfferingDao _svcOffDao;
+    @Inject DomainRouterDao _domainRouterDao;
+    @Inject NicDao _nicDao;
+    @Inject AgentManager _agentMgr;
+    @Inject NetworkModel _ntwkModel;
+    @Inject VirtualMachineManager _itMgr;
+    @Inject DataCenterDao _dcDao;
+    
+    long validNtwkId = 1L;
+    long invalidNtwkId = 2L;
+    String requestedIp = "10.1.1.1";
+    DomainRouterVO vm = null;
+    NetworkVO ntwk = createNetwork();
+    long validVmId = 1L;
+    long invalidVmId = 2L;
+    
+    @Before
+    public void setUp() {
+        //mock system offering creation as it's used by configure() method called by initComponentsLifeCycle
+        Mockito.when(_accountMgr.getAccount(1L)).thenReturn(new AccountVO());
+        ServiceOfferingVO off = new ServiceOfferingVO("alena", 1, 1,
+                1, 1, 1, false, "alena", false, false, null, false, VirtualMachine.Type.InternalLoadBalancerVm, false);
+        off = setId(off, 1);
+        Mockito.when(_svcOffDao.persistSystemServiceOffering(Mockito.any(ServiceOfferingVO.class))).thenReturn(off);
+        
+        ComponentContext.initComponentsLifeCycle();
+        
+        vm = new DomainRouterVO(1L,off.getId(),1,"alena",1,HypervisorType.XenServer,1,1,1,
+                false, 0,false,null,false,false,
+                VirtualMachine.Type.InternalLoadBalancerVm, null);
+        vm.setRole(Role.INTERNAL_LB_VM);
+        vm = setId(vm, 1);
+        vm.setPrivateIpAddress("10.2.2.2");
+        NicVO nic = new NicVO("somereserver", 1L, 1L, VirtualMachine.Type.InternalLoadBalancerVm);
+        nic.setIp4Address(requestedIp);
+        
+        List<DomainRouterVO> emptyList = new ArrayList<DomainRouterVO>();
+        List<DomainRouterVO> nonEmptyList = new ArrayList<DomainRouterVO>();
+        nonEmptyList.add(vm);
+        
+        Mockito.when(_domainRouterDao.listByNetworkAndRole(invalidNtwkId, Role.INTERNAL_LB_VM)).thenReturn(emptyList);
+        Mockito.when(_domainRouterDao.listByNetworkAndRole(validNtwkId, Role.INTERNAL_LB_VM)).thenReturn(nonEmptyList);
+        
+        Mockito.when(_nicDao.findByNtwkIdAndInstanceId(validNtwkId, 1)).thenReturn(nic);
+        Mockito.when(_nicDao.findByNtwkIdAndInstanceId(invalidNtwkId, 1)).thenReturn(nic);
+
+        Answer answer= new Answer(null, true, null);
+        Answer[] answers = new Answer[1];
+        answers[0] = answer;
+        
+        try {
+            Mockito.when(_agentMgr.send(Mockito.anyLong(), Mockito.any(Commands.class))).thenReturn(answers);
+        } catch (AgentUnavailableException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } catch (OperationTimedoutException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+        
+        createNetwork();
+        Mockito.when(_ntwkModel.getNetwork(Mockito.anyLong())).thenReturn(ntwk);
+
+        
+        Mockito.when(_itMgr.toNicTO(Mockito.any(NicProfile.class), Mockito.any(HypervisorType.class))).thenReturn(null);
+        Mockito.when(_domainRouterDao.findById(Mockito.anyLong())).thenReturn(vm);
+        DataCenterVO dc = new DataCenterVO
+                (1L, null, null, null, null, null, null, null, null, null, NetworkType.Advanced, null, null);
+        Mockito.when(_dcDao.findById(Mockito.anyLong())).thenReturn(dc);
+        
+        
+        try {
+            Mockito.when(_itMgr.expunge(Mockito.any(DomainRouterVO.class), Mockito.any(User.class), Mockito.any(Account.class))).thenReturn(true);
+        } catch (ResourceUnavailableException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } 
+        
+        Mockito.when(_domainRouterDao.findById(validVmId)).thenReturn(vm);
+        Mockito.when(_domainRouterDao.findById(invalidVmId)).thenReturn(null);
+
+    }
+
+    protected NetworkVO createNetwork() {
+        ntwk = new NetworkVO();
+        try {
+            ntwk.setBroadcastUri(new URI("somevlan"));
+        } catch (URISyntaxException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+        ntwk = setId(ntwk, 1L);
+        return ntwk;
+    }
+    
+    //TESTS FOR findInternalLbVms METHOD
+    
+    @Test
+    public void findInternalLbVmsForInvalidNetwork() {
+        List<? extends VirtualRouter> vms = _lbVmMgr.findInternalLbVms(invalidNtwkId, new Ip(requestedIp));
+        assertTrue("Non empty vm list was returned for invalid network id", vms.isEmpty());
+    }
+    
+    @Test
+    public void findInternalLbVmsForValidNetwork() {
+        List<? extends VirtualRouter> vms = _lbVmMgr.findInternalLbVms(validNtwkId, new Ip(requestedIp));
+        assertTrue("Empty vm list was returned for valid network id", !vms.isEmpty());
+    }
+    
+    
+    //TESTS FOR applyLoadBalancingRules METHOD
+    @Test
+    public void applyEmptyRulesSet() {
+        boolean result = false;
+        List<DomainRouterVO> vms = new ArrayList<DomainRouterVO>();
+        try {
+            result = _lbVmMgr.applyLoadBalancingRules(new NetworkVO(), new ArrayList<LoadBalancingRule>(), vms);
+        } catch (ResourceUnavailableException e) {
+
+        } finally {
+            assertTrue("Got failure when tried to apply empty list of rules", result);
+        }
+    }
+    
+    @Test (expected = CloudRuntimeException.class)
+    public void applyWithEmptyVmsSet() {
+        boolean result = false;
+        List<DomainRouterVO> vms = new ArrayList<DomainRouterVO>();
+        List<LoadBalancingRule> rules = new ArrayList<LoadBalancingRule>();
+        LoadBalancingRule rule = new LoadBalancingRule(null, null,
+                null, null, null);
+        
+        rules.add(rule);
+        try {
+            result = _lbVmMgr.applyLoadBalancingRules(new NetworkVO(), rules, vms);
+        } catch (ResourceUnavailableException e) {
+        } finally {
+            assertFalse("Got success when tried to apply with the empty internal lb vm list", result);
+        }
+    }
+    
+    @Test (expected = ResourceUnavailableException.class)
+    public void applyToVmInStartingState() throws ResourceUnavailableException {
+        boolean result = false;
+        List<DomainRouterVO> vms = new ArrayList<DomainRouterVO>();
+        vm.setState(State.Starting);
+        vms.add(vm);
+        
+        List<LoadBalancingRule> rules = new ArrayList<LoadBalancingRule>();
+        LoadBalancingRule rule = new LoadBalancingRule(null, null,
+                null, null, null);
+        
+        rules.add(rule);
+        try {
+            result = _lbVmMgr.applyLoadBalancingRules(new NetworkVO(), rules, vms);
+        } finally {
+            assertFalse("Rules were applied to vm in Starting state", result);
+        }
+    }
+    
+    
+    @Test
+    public void applyToVmInStoppedState() throws ResourceUnavailableException {
+        boolean result = false;
+        List<DomainRouterVO> vms = new ArrayList<DomainRouterVO>();
+        vm.setState(State.Stopped);
+        vms.add(vm);
+        
+        List<LoadBalancingRule> rules = new ArrayList<LoadBalancingRule>();
+        LoadBalancingRule rule = new LoadBalancingRule(null, null,
+                null, null, null);
+        
+        rules.add(rule);
+        try {
+            result = _lbVmMgr.applyLoadBalancingRules(new NetworkVO(), rules, vms);
+        } finally {
+            assertTrue("Rules failed to apply to vm in Stopped state", result);
+        }
+    }
+    
+    
+    @Test
+    public void applyToVmInStoppingState() throws ResourceUnavailableException {
+        boolean result = false;
+        List<DomainRouterVO> vms = new ArrayList<DomainRouterVO>();
+        vm.setState(State.Stopping);
+        vms.add(vm);
+        
+        List<LoadBalancingRule> rules = new ArrayList<LoadBalancingRule>();
+        LoadBalancingRule rule = new LoadBalancingRule(null, null,
+                null, null, null);
+        
+        rules.add(rule);
+        try {
+            result = _lbVmMgr.applyLoadBalancingRules(new NetworkVO(), rules, vms);
+        } finally {
+            assertTrue("Rules failed to apply to vm in Stopping state", result);
+        }
+    }
+    
+    
+    @Test
+    public void applyToVmInRunningState() throws ResourceUnavailableException {
+        boolean result = false;
+        List<DomainRouterVO> vms = new ArrayList<DomainRouterVO>();
+        vm.setState(State.Running);
+        vms.add(vm);
+        
+        List<LoadBalancingRule> rules = new ArrayList<LoadBalancingRule>();
+        ApplicationLoadBalancerRuleVO lb = new ApplicationLoadBalancerRuleVO(null, null, 22, 22, "roundrobin",
+                1L, 1L, 1L, new Ip(requestedIp), 1L, Scheme.Internal);
+        lb.setState(FirewallRule.State.Add);
+        
+        LoadBalancingRule rule = new LoadBalancingRule(lb, null,
+                null, null, new Ip(requestedIp));
+        
+        rules.add(rule);
+        
+        ntwk.getId();
+        
+        try {
+            result = _lbVmMgr.applyLoadBalancingRules(ntwk, rules, vms);
+        } finally {
+            assertTrue("Rules failed to apply to vm in Running state", result);
+        }
+    }
+    
+    
+    //TESTS FOR destroyInternalLbVm METHOD
+    @Test
+    public void destroyNonExistingVM() throws ResourceUnavailableException, ConcurrentOperationException {
+        boolean result = false;
+        
+        try {
+             result = _lbVmMgr.destroyInternalLbVm(invalidVmId, new AccountVO(), 1L);
+        } finally {
+            assertTrue("Failed to destroy non-existing vm", result);
+        }
+    }
+    
+    @Test
+    public void destroyExistingVM() throws ResourceUnavailableException, ConcurrentOperationException {
+        boolean result = false;
+        
+        try {
+             result = _lbVmMgr.destroyInternalLbVm(validVmId, new AccountVO(), 1L);
+        } finally {
+            assertTrue("Failed to destroy valid vm", result);
+        }
+    }
+    
+    
+    private static ServiceOfferingVO setId(ServiceOfferingVO vo, long id) {
+        ServiceOfferingVO voToReturn = vo;
+        Class<?> c = voToReturn.getClass();
+        try {
+            Field f = c.getSuperclass().getDeclaredField("id");
+            f.setAccessible(true);
+            f.setLong(voToReturn, id);
+        } catch (NoSuchFieldException ex) {
+           return null;
+        } catch (IllegalAccessException ex) {
+            return null;
+        }
+        
+        return voToReturn;
+    }
+    
+    
+    private static NetworkVO setId(NetworkVO vo, long id) {
+        NetworkVO voToReturn = vo;
+        Class<?> c = voToReturn.getClass();
+        try {
+            Field f = c.getDeclaredField("id");
+            f.setAccessible(true);
+            f.setLong(voToReturn, id);
+        } catch (NoSuchFieldException ex) {
+           return null;
+        } catch (IllegalAccessException ex) {
+            return null;
+        }
+        
+        return voToReturn;
+    }
+    
+    private static DomainRouterVO setId(DomainRouterVO vo, long id) {
+        DomainRouterVO voToReturn = vo;
+        Class<?> c = voToReturn.getClass();
+        try {
+            Field f = c.getSuperclass().getDeclaredField("id");
+            f.setAccessible(true);
+            f.setLong(voToReturn, id);
+        } catch (NoSuchFieldException ex) {
+           return null;
+        } catch (IllegalAccessException ex) {
+            return null;
+        }
+        
+        return voToReturn;
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2660a6b7/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbvmmgr/InternalLBVMServiceTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbvmmgr/InternalLBVMServiceTest.java b/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbvmmgr/InternalLBVMServiceTest.java
new file mode 100644
index 0000000..75f54fa
--- /dev/null
+++ b/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbvmmgr/InternalLBVMServiceTest.java
@@ -0,0 +1,291 @@
+// 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.internallbvmmgr;
+
+import java.lang.reflect.Field;
+import java.util.Map;
+
+import javax.inject.Inject;
+
+import junit.framework.TestCase;
+
+import org.apache.cloudstack.network.lb.InternalLoadBalancerVMService;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mockito;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import com.cloud.deploy.DeploymentPlan;
+import com.cloud.exception.ConcurrentOperationException;
+import com.cloud.exception.InsufficientCapacityException;
+import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.exception.OperationTimedoutException;
+import com.cloud.exception.ResourceUnavailableException;
+import com.cloud.exception.StorageUnavailableException;
+import com.cloud.hypervisor.Hypervisor.HypervisorType;
+import com.cloud.network.router.VirtualRouter;
+import com.cloud.network.router.VirtualRouter.Role;
+import com.cloud.service.ServiceOfferingVO;
+import com.cloud.service.dao.ServiceOfferingDao;
+import com.cloud.user.Account;
+import com.cloud.user.AccountManager;
+import com.cloud.user.AccountVO;
+import com.cloud.user.User;
+import com.cloud.utils.component.ComponentContext;
+import com.cloud.vm.DomainRouterVO;
+import com.cloud.vm.VirtualMachine;
+import com.cloud.vm.VirtualMachineManager;
+import com.cloud.vm.dao.DomainRouterDao;
+
+/**
+ * Set of unittests for InternalLoadBalancerVMService
+ *
+ */
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(locations="classpath:/lb_svc.xml")
+@SuppressWarnings("unchecked")
+public class InternalLBVMServiceTest extends TestCase {
+    //The interface to test
+    @Inject InternalLoadBalancerVMService _lbVmSvc;
+    
+    //Mocked interfaces
+    @Inject AccountManager _accountMgr;
+    @Inject ServiceOfferingDao _svcOffDao;
+    @Inject DomainRouterDao _domainRouterDao;
+    @Inject VirtualMachineManager _itMgr;
+    
+    long validVmId = 1L;
+    long nonExistingVmId = 2L;
+    long nonInternalLbVmId = 3L;
+    
+    @Before
+    public void setUp() {
+        //mock system offering creation as it's used by configure() method called by initComponentsLifeCycle
+        Mockito.when(_accountMgr.getAccount(1L)).thenReturn(new AccountVO());
+        ServiceOfferingVO off = new ServiceOfferingVO("alena", 1, 1,
+                1, 1, 1, false, "alena", false, false, null, false, VirtualMachine.Type.InternalLoadBalancerVm, false);
+        off = setId(off, 1);
+        Mockito.when(_svcOffDao.persistSystemServiceOffering(Mockito.any(ServiceOfferingVO.class))).thenReturn(off);
+        
+        ComponentContext.initComponentsLifeCycle();
+        
+        DomainRouterVO validVm = new DomainRouterVO(validVmId,off.getId(),1,"alena",1,HypervisorType.XenServer,1,1,1,
+                false, 0,false,null,false,false,
+                VirtualMachine.Type.InternalLoadBalancerVm, null);
+        validVm.setRole(Role.INTERNAL_LB_VM);
+        DomainRouterVO nonInternalLbVm = new DomainRouterVO(validVmId,off.getId(),1,"alena",1,HypervisorType.XenServer,1,1,1,
+                false, 0,false,null,false,false,
+                VirtualMachine.Type.DomainRouter, null);
+        nonInternalLbVm.setRole(Role.VIRTUAL_ROUTER);
+        
+        Mockito.when(_domainRouterDao.findById(validVmId)).thenReturn(validVm);
+        Mockito.when(_domainRouterDao.findById(nonExistingVmId)).thenReturn(null);
+        Mockito.when(_domainRouterDao.findById(nonInternalLbVmId)).thenReturn(nonInternalLbVm);
+        
+        try {
+            Mockito.when(_itMgr.start(Mockito.any(DomainRouterVO.class),
+                    Mockito.any(Map.class), Mockito.any(User.class), Mockito.any(Account.class), Mockito.any(DeploymentPlan.class))).thenReturn(validVm);
+        } catch (InsufficientCapacityException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } catch (ResourceUnavailableException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+        
+        try {
+            Mockito.when(_itMgr.advanceStop(Mockito.any(DomainRouterVO.class), Mockito.any(Boolean.class), Mockito.any(User.class), Mockito.any(Account.class))).thenReturn(true);
+        } catch (ResourceUnavailableException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } catch (OperationTimedoutException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } catch (ConcurrentOperationException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+
+    }
+    
+    //TESTS FOR START COMMAND
+    
+    
+    @Test (expected = InvalidParameterValueException.class)
+    public void startNonExistingVm() {
+        String expectedExcText = null;
+        try {
+            _lbVmSvc.startInternalLbVm(nonExistingVmId, _accountMgr.getAccount(1L), 1L);
+        } catch (StorageUnavailableException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } catch (InsufficientCapacityException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } catch (ConcurrentOperationException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } catch (ResourceUnavailableException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } catch (InvalidParameterValueException e) {
+            expectedExcText = e.getMessage();
+            throw e;
+        } finally {
+            assertEquals("Test failed. The non-existing internal lb vm was attempted to start"
+        + expectedExcText, expectedExcText, "Can't find internal lb vm by id specified");
+        }
+    }
+    
+    @Test (expected = InvalidParameterValueException.class)
+    public void startNonInternalLbVmVm() {
+        String expectedExcText = null;
+        try {
+            _lbVmSvc.startInternalLbVm(nonInternalLbVmId, _accountMgr.getAccount(1L), 1L);
+        } catch (StorageUnavailableException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } catch (InsufficientCapacityException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } catch (ConcurrentOperationException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } catch (ResourceUnavailableException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }catch (InvalidParameterValueException e) {
+            expectedExcText = e.getMessage();
+            throw e;
+        } finally {
+            assertEquals("Test failed. The existing vm of not Internal lb vm type was attempted to start"
+        + expectedExcText, expectedExcText, "Can't find internal lb vm by id specified");
+        }
+    }
+    
+    @Test
+    public void startValidLbVmVm() {
+        VirtualRouter vr = null;
+        try {
+            vr = _lbVmSvc.startInternalLbVm(validVmId, _accountMgr.getAccount(1L), 1L);
+        } catch (StorageUnavailableException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } catch (InsufficientCapacityException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } catch (ConcurrentOperationException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } catch (ResourceUnavailableException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } finally {
+            assertNotNull("Internal LB vm is null which means it failed to start " + vr, vr);
+        }
+    }
+    
+    
+    //TEST FOR STOP COMMAND
+    @Test (expected = InvalidParameterValueException.class)
+    public void stopNonExistingVm() {
+        String expectedExcText = null;
+        try {
+            _lbVmSvc.stopInternalLbVm(nonExistingVmId, false,_accountMgr.getAccount(1L), 1L);
+        } catch (StorageUnavailableException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } catch (ConcurrentOperationException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } catch (ResourceUnavailableException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } catch (InvalidParameterValueException e) {
+            expectedExcText = e.getMessage();
+            throw e;
+        } finally {
+            assertEquals("Test failed. The non-existing internal lb vm was attempted to stop"
+        + expectedExcText, expectedExcText, "Can't find internal lb vm by id specified");
+        }
+    }
+    
+    
+    @Test (expected = InvalidParameterValueException.class)
+    public void stopNonInternalLbVmVm() {
+        String expectedExcText = null;
+        try {
+            _lbVmSvc.stopInternalLbVm(nonInternalLbVmId, false, _accountMgr.getAccount(1L), 1L);
+        } catch (StorageUnavailableException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } catch (ConcurrentOperationException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } catch (ResourceUnavailableException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }catch (InvalidParameterValueException e) {
+            expectedExcText = e.getMessage();
+            throw e;
+        } finally {
+            assertEquals("Test failed. The existing vm of not Internal lb vm type was attempted to stop"
+        + expectedExcText, expectedExcText, "Can't find internal lb vm by id specified");
+        }
+    }
+    
+    
+    @Test
+    public void stopValidLbVmVm() {
+        VirtualRouter vr = null;
+        try {
+            vr = _lbVmSvc.stopInternalLbVm(validVmId, false, _accountMgr.getAccount(1L), 1L);
+        } catch (StorageUnavailableException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } catch (ConcurrentOperationException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } catch (ResourceUnavailableException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } finally {
+            assertNotNull("Internal LB vm is null which means it failed to stop " + vr, vr);
+        }
+    }
+    
+    
+    
+    private static ServiceOfferingVO setId(ServiceOfferingVO vo, long id) {
+        ServiceOfferingVO voToReturn = vo;
+        Class<?> c = voToReturn.getClass();
+        try {
+            Field f = c.getSuperclass().getDeclaredField("id");
+            f.setAccessible(true);
+            f.setLong(voToReturn, id);
+        } catch (NoSuchFieldException ex) {
+           return null;
+        } catch (IllegalAccessException ex) {
+            return null;
+        }
+        
+        return voToReturn;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2660a6b7/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbvmmgr/LbChildTestConfiguration.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbvmmgr/LbChildTestConfiguration.java b/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbvmmgr/LbChildTestConfiguration.java
new file mode 100644
index 0000000..0f24f96
--- /dev/null
+++ b/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbvmmgr/LbChildTestConfiguration.java
@@ -0,0 +1,170 @@
+// 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.internallbvmmgr;
+
+import java.io.IOException;
+
+import org.apache.cloudstack.lb.dao.ApplicationLoadBalancerRuleDao;
+import org.apache.cloudstack.test.utils.SpringUtils;
+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 com.cloud.agent.AgentManager;
+import com.cloud.configuration.dao.ConfigurationDao;
+import com.cloud.dc.dao.AccountVlanMapDaoImpl;
+import com.cloud.dc.dao.DataCenterDao;
+import com.cloud.network.NetworkManager;
+import com.cloud.network.NetworkModel;
+import com.cloud.network.dao.NetworkDao;
+import com.cloud.network.dao.PhysicalNetworkServiceProviderDao;
+import com.cloud.network.dao.VirtualRouterProviderDao;
+import com.cloud.network.lb.LoadBalancingRulesManager;
+import com.cloud.offerings.dao.NetworkOfferingDao;
+import com.cloud.resource.ResourceManager;
+import com.cloud.server.ConfigurationServer;
+import com.cloud.service.dao.ServiceOfferingDao;
+import com.cloud.storage.dao.VMTemplateDao;
+import com.cloud.user.AccountManager;
+import com.cloud.vm.VirtualMachineManager;
+import com.cloud.vm.dao.DomainRouterDao;
+import com.cloud.vm.dao.NicDao;
+
+@Configuration
+@ComponentScan(
+    basePackageClasses={
+        AccountVlanMapDaoImpl.class
+    },
+    includeFilters={@Filter(value=LbChildTestConfiguration.Library.class, type=FilterType.CUSTOM)},
+    useDefaultFilters=false
+    )
+
+    public class LbChildTestConfiguration {
+        
+        public static class Library implements TypeFilter {
+            
+          
+            @Bean
+            public AccountManager accountManager() {
+                return Mockito.mock(AccountManager.class);
+            }
+            
+            @Bean
+            public VirtualMachineManager virtualMachineManager() {
+                return Mockito.mock(VirtualMachineManager.class);
+            }
+            
+            @Bean
+            public DomainRouterDao domainRouterDao() {
+                return Mockito.mock(DomainRouterDao.class);
+            }
+            
+            @Bean
+            public ConfigurationDao configurationDao() {
+                return Mockito.mock(ConfigurationDao.class);
+            }
+            
+            @Bean
+            public VirtualRouterProviderDao virtualRouterProviderDao() {
+                return Mockito.mock(VirtualRouterProviderDao.class);
+            }
+            
+            @Bean
+            public ApplicationLoadBalancerRuleDao applicationLoadBalancerRuleDao() {
+                return Mockito.mock(ApplicationLoadBalancerRuleDao.class);
+            }
+            
+            @Bean
+            public NetworkModel networkModel() {
+                return Mockito.mock(NetworkModel.class);
+            }
+            
+            @Bean
+            public LoadBalancingRulesManager loadBalancingRulesManager() {
+                return Mockito.mock(LoadBalancingRulesManager.class);
+            }
+            
+            @Bean
+            public NicDao nicDao() {
+                return Mockito.mock(NicDao.class);
+            }
+            
+            @Bean
+            public NetworkDao networkDao() {
+                return Mockito.mock(NetworkDao.class);
+            }
+            
+            @Bean
+            public NetworkManager networkManager() {
+                return Mockito.mock(NetworkManager.class);
+            }
+            
+            @Bean
+            public ServiceOfferingDao serviceOfferingDao() {
+                return Mockito.mock(ServiceOfferingDao.class);
+            }
+            
+            @Bean
+            public PhysicalNetworkServiceProviderDao physicalNetworkServiceProviderDao() {
+                return Mockito.mock(PhysicalNetworkServiceProviderDao.class);
+            }
+            
+            @Bean
+            public NetworkOfferingDao networkOfferingDao() {
+                return Mockito.mock(NetworkOfferingDao.class);
+            }
+            
+            @Bean
+            public VMTemplateDao vmTemplateDao() {
+                return Mockito.mock(VMTemplateDao.class);
+            }
+            
+            @Bean
+            public ResourceManager resourceManager() {
+                return Mockito.mock(ResourceManager.class);
+            }
+            
+            @Bean
+            public AgentManager agentManager() {
+                return Mockito.mock(AgentManager.class);
+            }
+            
+            @Bean
+            public DataCenterDao dataCenterDao() {
+                return Mockito.mock(DataCenterDao.class);
+            }
+            
+            @Bean
+            public ConfigurationServer configurationServer() {
+                return Mockito.mock(ConfigurationServer.class);
+            }
+            
+            @Override
+            public boolean match(MetadataReader mdr, MetadataReaderFactory arg1) throws IOException {
+                mdr.getClassMetadata().getClassName();
+                ComponentScan cs = LbChildTestConfiguration.class.getAnnotation(ComponentScan.class);
+                return SpringUtils.includedInBasePackageClasses(mdr.getClassMetadata().getClassName(), cs);
+            }
+    
+        }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2660a6b7/plugins/network-elements/internal-loadbalancer/test/resources/lb_element.xml
----------------------------------------------------------------------
diff --git a/plugins/network-elements/internal-loadbalancer/test/resources/lb_element.xml b/plugins/network-elements/internal-loadbalancer/test/resources/lb_element.xml
new file mode 100644
index 0000000..5dec9c3
--- /dev/null
+++ b/plugins/network-elements/internal-loadbalancer/test/resources/lb_element.xml
@@ -0,0 +1,46 @@
+<!-- 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. -->
+<beans xmlns="http://www.springframework.org/schema/beans"
+  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
+  xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
+  xsi:schemaLocation="http://www.springframework.org/schema/beans
+                      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+                      http://www.springframework.org/schema/tx 
+                      http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
+                      http://www.springframework.org/schema/aop
+                      http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
+                      http://www.springframework.org/schema/context
+                      http://www.springframework.org/schema/context/spring-context-3.0.xsd">
+
+     <context:annotation-config />
+
+    <!-- @DB support -->
+      
+  <bean id="componentContext" class="com.cloud.utils.component.ComponentContext" />
+
+  <bean id="transactionContextBuilder" class="com.cloud.utils.db.TransactionContextBuilder" />
+  <bean id="actionEventInterceptor" class="com.cloud.event.ActionEventInterceptor" />
+  <bean id="instantiatePostProcessor" class="com.cloud.utils.component.ComponentInstantiationPostProcessor">
+    <property name="Interceptors">
+        <list>
+            <ref bean="transactionContextBuilder" />
+            <ref bean="actionEventInterceptor" />
+        </list>
+    </property>
+  </bean>
+
+    <bean id="InternalLoadBalancerElementService" class="org.apache.cloudstack.network.element.InternalLoadBalancerElement">
+        <property name="name" value="InternalLoadBalancerElementService"/>
+    </bean>
+  
+    <bean class="org.apache.cloudstack.internallbelement.ElementChildTestConfiguration" />
+    
+</beans>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2660a6b7/plugins/network-elements/internal-loadbalancer/test/resources/lb_mgr.xml
----------------------------------------------------------------------
diff --git a/plugins/network-elements/internal-loadbalancer/test/resources/lb_mgr.xml b/plugins/network-elements/internal-loadbalancer/test/resources/lb_mgr.xml
new file mode 100644
index 0000000..1ad6403
--- /dev/null
+++ b/plugins/network-elements/internal-loadbalancer/test/resources/lb_mgr.xml
@@ -0,0 +1,46 @@
+<!-- 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. -->
+<beans xmlns="http://www.springframework.org/schema/beans"
+  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
+  xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
+  xsi:schemaLocation="http://www.springframework.org/schema/beans
+                      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+                      http://www.springframework.org/schema/tx 
+                      http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
+                      http://www.springframework.org/schema/aop
+                      http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
+                      http://www.springframework.org/schema/context
+                      http://www.springframework.org/schema/context/spring-context-3.0.xsd">
+
+     <context:annotation-config />
+
+    <!-- @DB support -->
+      
+  <bean id="componentContext" class="com.cloud.utils.component.ComponentContext" />
+
+  <bean id="transactionContextBuilder" class="com.cloud.utils.db.TransactionContextBuilder" />
+  <bean id="actionEventInterceptor" class="com.cloud.event.ActionEventInterceptor" />
+  <bean id="instantiatePostProcessor" class="com.cloud.utils.component.ComponentInstantiationPostProcessor">
+    <property name="Interceptors">
+        <list>
+            <ref bean="transactionContextBuilder" />
+            <ref bean="actionEventInterceptor" />
+        </list>
+    </property>
+  </bean>
+
+    <bean id="InternalLoadBalancerVMManager" class="org.apache.cloudstack.network.lb.InternalLoadBalancerVMManagerImpl">
+        <property name="name" value="InternalLoadBalancerVMManager"/>
+    </bean>
+  
+    <bean class="org.apache.cloudstack.internallbvmmgr.LbChildTestConfiguration" />
+    
+</beans>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2660a6b7/plugins/network-elements/internal-loadbalancer/test/resources/lb_svc.xml
----------------------------------------------------------------------
diff --git a/plugins/network-elements/internal-loadbalancer/test/resources/lb_svc.xml b/plugins/network-elements/internal-loadbalancer/test/resources/lb_svc.xml
new file mode 100644
index 0000000..fa822f3
--- /dev/null
+++ b/plugins/network-elements/internal-loadbalancer/test/resources/lb_svc.xml
@@ -0,0 +1,46 @@
+<!-- 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. -->
+<beans xmlns="http://www.springframework.org/schema/beans"
+  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
+  xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
+  xsi:schemaLocation="http://www.springframework.org/schema/beans
+                      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+                      http://www.springframework.org/schema/tx 
+                      http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
+                      http://www.springframework.org/schema/aop
+                      http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
+                      http://www.springframework.org/schema/context
+                      http://www.springframework.org/schema/context/spring-context-3.0.xsd">
+
+     <context:annotation-config />
+
+    <!-- @DB support -->
+      
+  <bean id="componentContext" class="com.cloud.utils.component.ComponentContext" />
+
+  <bean id="transactionContextBuilder" class="com.cloud.utils.db.TransactionContextBuilder" />
+  <bean id="actionEventInterceptor" class="com.cloud.event.ActionEventInterceptor" />
+  <bean id="instantiatePostProcessor" class="com.cloud.utils.component.ComponentInstantiationPostProcessor">
+    <property name="Interceptors">
+        <list>
+            <ref bean="transactionContextBuilder" />
+            <ref bean="actionEventInterceptor" />
+        </list>
+    </property>
+  </bean>
+
+    <bean id="InternalLoadBalancerVMService" class="org.apache.cloudstack.network.lb.InternalLoadBalancerVMManagerImpl">
+        <property name="name" value="InternalLoadBalancerVMService"/>
+    </bean>
+  
+    <bean class="org.apache.cloudstack.internallbvmmgr.LbChildTestConfiguration" />
+    
+</beans>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2660a6b7/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerElement.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerElement.java b/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerElement.java
index b814430..4f2a0a1 100644
--- a/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerElement.java
+++ b/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerElement.java
@@ -16,6 +16,22 @@
 // under the License.
 package com.cloud.network.element;
 
+import java.net.URI;
+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.ejb.Local;
+import javax.inject.Inject;
+
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice;
+import org.apache.cloudstack.region.gslb.GslbServiceProvider;
+import org.apache.log4j.Logger;
+
 import com.cloud.agent.AgentManager;
 import com.cloud.agent.api.Answer;
 import com.cloud.agent.api.routing.GlobalLoadBalancerConfigCommand;
@@ -27,7 +43,11 @@ import com.cloud.agent.api.routing.SetStaticNatRulesCommand;
 import com.cloud.agent.api.to.LoadBalancerTO;
 import com.cloud.agent.api.to.StaticNatRuleTO;
 import com.cloud.api.ApiDBUtils;
-import com.cloud.api.commands.*;
+import com.cloud.api.commands.AddNetscalerLoadBalancerCmd;
+import com.cloud.api.commands.ConfigureNetscalerLoadBalancerCmd;
+import com.cloud.api.commands.DeleteNetscalerLoadBalancerCmd;
+import com.cloud.api.commands.ListNetscalerLoadBalancerNetworksCmd;
+import com.cloud.api.commands.ListNetscalerLoadBalancersCmd;
 import com.cloud.api.response.NetscalerLoadBalancerResponse;
 import com.cloud.configuration.Config;
 import com.cloud.configuration.ConfigurationManager;
@@ -39,27 +59,48 @@ import com.cloud.dc.HostPodVO;
 import com.cloud.dc.dao.DataCenterDao;
 import com.cloud.dc.dao.DataCenterIpAddressDao;
 import com.cloud.deploy.DeployDestination;
-import com.cloud.exception.*;
+import com.cloud.exception.ConcurrentOperationException;
+import com.cloud.exception.InsufficientCapacityException;
+import com.cloud.exception.InsufficientNetworkCapacityException;
+import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.exception.ResourceUnavailableException;
 import com.cloud.host.Host;
 import com.cloud.host.HostVO;
 import com.cloud.host.dao.HostDao;
 import com.cloud.host.dao.HostDetailsDao;
-import com.cloud.network.*;
+import com.cloud.network.ExternalLoadBalancerDeviceManager;
+import com.cloud.network.ExternalLoadBalancerDeviceManagerImpl;
+import com.cloud.network.IpAddress;
+import com.cloud.network.NetScalerPodVO;
+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.TrafficType;
+import com.cloud.network.PhysicalNetwork;
+import com.cloud.network.PhysicalNetworkServiceProvider;
+import com.cloud.network.PublicIpAddress;
 import com.cloud.network.as.AutoScaleCounter;
 import com.cloud.network.as.AutoScaleCounter.AutoScaleCounterType;
-import com.cloud.network.dao.*;
+import com.cloud.network.dao.ExternalLoadBalancerDeviceDao;
+import com.cloud.network.dao.ExternalLoadBalancerDeviceVO;
 import com.cloud.network.dao.ExternalLoadBalancerDeviceVO.LBDeviceState;
+import com.cloud.network.dao.NetScalerPodDao;
+import com.cloud.network.dao.NetworkDao;
+import com.cloud.network.dao.NetworkExternalLoadBalancerDao;
+import com.cloud.network.dao.NetworkExternalLoadBalancerVO;
+import com.cloud.network.dao.NetworkServiceMapDao;
+import com.cloud.network.dao.NetworkVO;
+import com.cloud.network.dao.PhysicalNetworkDao;
+import com.cloud.network.dao.PhysicalNetworkVO;
 import com.cloud.network.lb.LoadBalancingRule;
 import com.cloud.network.lb.LoadBalancingRule.LbDestination;
 import com.cloud.network.resource.NetscalerResource;
 import com.cloud.network.rules.FirewallRule;
-import com.cloud.network.rules.FirewallRule.Purpose;
 import com.cloud.network.rules.LbStickinessMethod;
 import com.cloud.network.rules.LbStickinessMethod.StickinessMethodType;
+import com.cloud.network.rules.LoadBalancerContainer;
 import com.cloud.network.rules.StaticNat;
 import com.cloud.network.vpc.PrivateGateway;
 import com.cloud.network.vpc.StaticRouteProfile;
@@ -75,15 +116,6 @@ import com.cloud.vm.ReservationContext;
 import com.cloud.vm.VirtualMachine;
 import com.cloud.vm.VirtualMachineProfile;
 import com.google.gson.Gson;
-import org.apache.cloudstack.api.ApiConstants;
-import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice;
-import org.apache.cloudstack.region.gslb.GslbServiceProvider;
-import org.apache.log4j.Logger;
-
-import javax.ejb.Local;
-import javax.inject.Inject;
-import java.net.URI;
-import java.util.*;
 
 @Local(value = {NetworkElement.class, StaticNatServiceProvider.class, LoadBalancingServiceProvider.class, GslbServiceProvider.class})
 public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl implements LoadBalancingServiceProvider,
@@ -207,6 +239,10 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
         if (!canHandle(config, Service.Lb)) {
             return false;
         }
+        
+        if (canHandleLbRules(rules)) {
+            return false;
+        }
 
         if (isBasicZoneNetwok(config)) {
             return applyElasticLoadBalancerRules(config, rules);
@@ -237,6 +273,9 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
         // Specifies that load balancing rules can only be made with public IPs that aren't source NAT IPs
         lbCapabilities.put(Capability.LoadBalancingSupportedIps, "additional");
 
+        // Supports only Public load balancing
+        lbCapabilities.put(Capability.LbSchemes, LoadBalancerContainer.Scheme.Public.toString());
+        
         // Specifies that load balancing rules can support autoscaling and the list of counters it supports
         AutoScaleCounter counter;
         List<AutoScaleCounter> counterList = new ArrayList<AutoScaleCounter>();
@@ -644,14 +683,7 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
         return this;
     }
 
-    public boolean applyElasticLoadBalancerRules(Network network, List<? extends FirewallRule> rules) throws ResourceUnavailableException {
-
-        List<LoadBalancingRule> loadBalancingRules = new ArrayList<LoadBalancingRule>();
-        for (FirewallRule rule : rules) {
-            if (rule.getPurpose().equals(Purpose.LoadBalancing)) {
-                loadBalancingRules.add((LoadBalancingRule) rule);
-            }
-        }
+    public boolean applyElasticLoadBalancerRules(Network network, List<LoadBalancingRule> loadBalancingRules) throws ResourceUnavailableException {
 
         if (loadBalancingRules == null || loadBalancingRules.isEmpty()) {
             return true;
@@ -682,7 +714,7 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
             String protocol = rule.getProtocol();
             String algorithm = rule.getAlgorithm();
             String lbUuid = rule.getUuid();
-            String srcIp = _networkMgr.getIp(rule.getSourceIpAddressId()).getAddress().addr();
+            String srcIp = rule.getSourceIp().addr();
             int srcPort = rule.getSourcePortStart();
             List<LbDestination> destinations = rule.getDestinations();
 
@@ -813,16 +845,10 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
         return null;
     }
 
-    public List<LoadBalancerTO> getElasticLBRulesHealthCheck(Network network, List<? extends FirewallRule> rules)
+    public List<LoadBalancerTO> getElasticLBRulesHealthCheck(Network network, List<LoadBalancingRule> loadBalancingRules)
             throws ResourceUnavailableException {
 
         HealthCheckLBConfigAnswer answer = null;
-        List<LoadBalancingRule> loadBalancingRules = new ArrayList<LoadBalancingRule>();
-        for (FirewallRule rule : rules) {
-            if (rule.getPurpose().equals(Purpose.LoadBalancing)) {
-                loadBalancingRules.add((LoadBalancingRule) rule);
-            }
-        }
 
         if (loadBalancingRules == null || loadBalancingRules.isEmpty()) {
             return null;
@@ -849,7 +875,7 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
             String protocol = rule.getProtocol();
             String algorithm = rule.getAlgorithm();
             String lbUuid = rule.getUuid();
-            String srcIp = _networkMgr.getIp(rule.getSourceIpAddressId()).getAddress().addr();
+            String srcIp = rule.getSourceIp().addr();
             int srcPort = rule.getSourcePortStart();
             List<LbDestination> destinations = rule.getDestinations();
 
@@ -874,7 +900,7 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
 
     public List<LoadBalancerTO> updateHealthChecks(Network network, List<LoadBalancingRule> lbrules) {
 
-        if (canHandle(network, Service.Lb)) {
+        if (canHandle(network, Service.Lb) && canHandleLbRules(lbrules)) {
             try {
 
                 if (isBasicZoneNetwok(network)) {
@@ -891,7 +917,7 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
         return null;
     }
 
-    public List<LoadBalancerTO> getLBHealthChecks(Network network, List<? extends FirewallRule> rules)
+    public List<LoadBalancerTO> getLBHealthChecks(Network network, List<LoadBalancingRule> rules)
             throws ResourceUnavailableException {
         return super.getLBHealthChecks(network, rules);
     }
@@ -960,6 +986,22 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
         }
         return null;
     }
+    
+    private boolean canHandleLbRules(List<LoadBalancingRule> rules) {
+        Map<Capability, String> lbCaps = this.getCapabilities().get(Service.Lb);
+        if (!lbCaps.isEmpty()) {
+            String schemeCaps = lbCaps.get(Capability.LbSchemes);
+            if (schemeCaps != null) {
+                for (LoadBalancingRule rule : rules) {
+                    if (!schemeCaps.contains(rule.getScheme().toString())) {
+                        s_logger.debug("Scheme " + rules.get(0).getScheme() + " is not supported by the provider " + this.getName());
+                        return false;
+                    }
+                }
+            }
+        }
+        return true;
+    }
 
     @Override
     public boolean implementVpc(Vpc vpc, DeployDestination dest, ReservationContext context)

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2660a6b7/plugins/pom.xml
----------------------------------------------------------------------
diff --git a/plugins/pom.xml b/plugins/pom.xml
index b940271..e49fac9 100755
--- a/plugins/pom.xml
+++ b/plugins/pom.xml
@@ -62,6 +62,7 @@
     <module>storage/volume/default</module>
     <module>alert-handlers/snmp-alerts</module>
     <module>alert-handlers/syslog-alerts</module>
+    <module>network-elements/internal-loadbalancer</module>
   </modules>
 
   <dependencies>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2660a6b7/server/src/com/cloud/api/ApiDBUtils.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/ApiDBUtils.java b/server/src/com/cloud/api/ApiDBUtils.java
index b8eea12..fce1f71 100755
--- a/server/src/com/cloud/api/ApiDBUtils.java
+++ b/server/src/com/cloud/api/ApiDBUtils.java
@@ -25,8 +25,6 @@ import java.util.Set;
 import javax.annotation.PostConstruct;
 import javax.inject.Inject;
 
-import com.cloud.network.rules.LoadBalancer;
-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;
@@ -37,8 +35,8 @@ import org.apache.cloudstack.api.response.AsyncJobResponse;
 import org.apache.cloudstack.api.response.DiskOfferingResponse;
 import org.apache.cloudstack.api.response.DomainRouterResponse;
 import org.apache.cloudstack.api.response.EventResponse;
-import org.apache.cloudstack.api.response.HostResponse;
 import org.apache.cloudstack.api.response.HostForMigrationResponse;
+import org.apache.cloudstack.api.response.HostResponse;
 import org.apache.cloudstack.api.response.InstanceGroupResponse;
 import org.apache.cloudstack.api.response.ProjectAccountResponse;
 import org.apache.cloudstack.api.response.ProjectInvitationResponse;
@@ -52,6 +50,7 @@ import org.apache.cloudstack.api.response.UserResponse;
 import org.apache.cloudstack.api.response.UserVmResponse;
 import org.apache.cloudstack.api.response.VolumeResponse;
 import org.apache.cloudstack.api.response.ZoneResponse;
+import org.apache.cloudstack.lb.dao.ApplicationLoadBalancerRuleDao;
 import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
 import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
 import org.springframework.stereotype.Component;
@@ -157,6 +156,8 @@ import com.cloud.network.as.dao.AutoScaleVmGroupPolicyMapDao;
 import com.cloud.network.as.dao.AutoScaleVmProfileDao;
 import com.cloud.network.as.dao.ConditionDao;
 import com.cloud.network.as.dao.CounterDao;
+import com.cloud.network.dao.AccountGuestVlanMapDao;
+import com.cloud.network.dao.AccountGuestVlanMapVO;
 import com.cloud.network.dao.FirewallRulesCidrsDao;
 import com.cloud.network.dao.FirewallRulesDao;
 import com.cloud.network.dao.IPAddressDao;
@@ -181,6 +182,7 @@ import com.cloud.network.dao.Site2SiteVpnGatewayDao;
 import com.cloud.network.dao.Site2SiteVpnGatewayVO;
 import com.cloud.network.router.VirtualRouter;
 import com.cloud.network.rules.FirewallRuleVO;
+import com.cloud.network.rules.LoadBalancer;
 import com.cloud.network.security.SecurityGroup;
 import com.cloud.network.security.SecurityGroupManager;
 import com.cloud.network.security.SecurityGroupVO;
@@ -204,6 +206,7 @@ import com.cloud.projects.Project;
 import com.cloud.projects.ProjectAccount;
 import com.cloud.projects.ProjectInvitation;
 import com.cloud.projects.ProjectService;
+import com.cloud.region.ha.GlobalLoadBalancingRulesService;
 import com.cloud.resource.ResourceManager;
 import com.cloud.server.Criteria;
 import com.cloud.server.ManagementServer;
@@ -499,6 +502,7 @@ public class ApiDBUtils {
     @Inject private VMSnapshotDao vmSnapshotDao;
     @Inject private NicSecondaryIpDao nicSecondaryIpDao;
     @Inject private VpcProvisioningService vpcProvSvc;
+    @Inject private ApplicationLoadBalancerRuleDao _appLbDao;
     @Inject private AffinityGroupDao affinityGroupDao;
     @Inject private AffinityGroupJoinDao affinityGroupJoinDao;
     @Inject private GlobalLoadBalancingRulesService gslbService;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2660a6b7/server/src/com/cloud/api/ApiResponseHelper.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java
index d7eaa26..d5960ab 100755
--- a/server/src/com/cloud/api/ApiResponseHelper.java
+++ b/server/src/com/cloud/api/ApiResponseHelper.java
@@ -44,6 +44,9 @@ import org.apache.cloudstack.api.BaseCmd;
 import org.apache.cloudstack.api.ResponseGenerator;
 import org.apache.cloudstack.api.command.user.job.QueryAsyncJobResultCmd;
 import org.apache.cloudstack.api.response.AccountResponse;
+import org.apache.cloudstack.api.response.ApplicationLoadBalancerInstanceResponse;
+import org.apache.cloudstack.api.response.ApplicationLoadBalancerResponse;
+import org.apache.cloudstack.api.response.ApplicationLoadBalancerRuleResponse;
 import org.apache.cloudstack.api.response.AsyncJobResponse;
 import org.apache.cloudstack.api.response.AutoScalePolicyResponse;
 import org.apache.cloudstack.api.response.AutoScaleVmGroupResponse;
@@ -72,6 +75,7 @@ import org.apache.cloudstack.api.response.HostResponse;
 import org.apache.cloudstack.api.response.HypervisorCapabilitiesResponse;
 import org.apache.cloudstack.api.response.IPAddressResponse;
 import org.apache.cloudstack.api.response.InstanceGroupResponse;
+import org.apache.cloudstack.api.response.InternalLoadBalancerElementResponse;
 import org.apache.cloudstack.api.response.IpForwardingRuleResponse;
 import org.apache.cloudstack.api.response.IsolationMethodResponse;
 import org.apache.cloudstack.api.response.LBHealthCheckPolicyResponse;
@@ -130,6 +134,7 @@ import org.apache.cloudstack.api.response.VpcOfferingResponse;
 import org.apache.cloudstack.api.response.VpcResponse;
 import org.apache.cloudstack.api.response.VpnUsersResponse;
 import org.apache.cloudstack.api.response.ZoneResponse;
+import org.apache.cloudstack.network.lb.ApplicationLoadBalancerRule;
 import org.apache.cloudstack.region.Region;
 import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
 import org.apache.cloudstack.usage.Usage;
@@ -189,6 +194,7 @@ 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.NetworkProfile;
 import com.cloud.network.Networks.IsolationType;
 import com.cloud.network.Networks.TrafficType;
@@ -216,6 +222,7 @@ import com.cloud.network.rules.FirewallRule;
 import com.cloud.network.rules.FirewallRuleVO;
 import com.cloud.network.rules.HealthCheckPolicy;
 import com.cloud.network.rules.LoadBalancer;
+import com.cloud.network.rules.LoadBalancerContainer.Scheme;
 import com.cloud.network.rules.PortForwardingRule;
 import com.cloud.network.rules.StaticNatRule;
 import com.cloud.network.rules.StickinessPolicy;
@@ -229,6 +236,7 @@ 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;
 import com.cloud.offering.ServiceOffering;
 import com.cloud.offerings.NetworkOfferingVO;
 import com.cloud.org.Cluster;
@@ -269,6 +277,7 @@ import com.cloud.user.UserContext;
 import com.cloud.uservm.UserVm;
 import com.cloud.utils.Pair;
 import com.cloud.utils.StringUtils;
+import com.cloud.utils.net.Ip;
 import com.cloud.utils.net.NetUtils;
 import com.cloud.vm.ConsoleProxyVO;
 import com.cloud.vm.InstanceGroup;
@@ -289,6 +298,7 @@ public class ApiResponseHelper implements ResponseGenerator {
     private static final DecimalFormat s_percentFormat = new DecimalFormat("##.##");
     @Inject private EntityManager _entityMgr = null;
     @Inject private UsageService _usageSvc = null;
+    @Inject NetworkModel _ntwkModel;
 
     @Override
     public UserResponse createUserResponse(User user) {
@@ -750,7 +760,7 @@ public class ApiResponseHelper implements ResponseGenerator {
         }
 
         //set tag information
-        List<? extends ResourceTag> tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.UserVm, loadBalancer.getId());
+        List<? extends ResourceTag> tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.LoadBalancer, loadBalancer.getId());
         List<ResourceTagResponse> tagResponses = new ArrayList<ResourceTagResponse>();
         for (ResourceTag tag : tags) {
             ResourceTagResponse tagResponse = createResourceTagResponse(tag, true);
@@ -2263,6 +2273,13 @@ public class ApiResponseHelper implements ResponseGenerator {
         response.setForVpc(ApiDBUtils.isOfferingForVpc(offering));
 
         response.setServices(serviceResponses);
+        
+        //set network offering details
+        Map<Detail, String> details = _ntwkModel.getNtwkOffDetails(offering.getId());
+        if (details != null && !details.isEmpty()) {
+            response.setDetails(details);
+        }
+        
         response.setObjectName("networkoffering");
         return response;
     }
@@ -2826,6 +2843,11 @@ public class ApiResponseHelper implements ResponseGenerator {
 
     @Override
     public VirtualRouterProviderResponse createVirtualRouterProviderResponse(VirtualRouterProvider result) {
+        //generate only response of the VR/VPCVR provider type
+        if (!(result.getType() == VirtualRouterProvider.VirtualRouterProviderType.VirtualRouter
+                || result.getType() == VirtualRouterProvider.VirtualRouterProviderType.VPCVirtualRouter)) {
+            return null;
+        }
         VirtualRouterProviderResponse response = new VirtualRouterProviderResponse();
         response.setId(result.getUuid());
         PhysicalNetworkServiceProvider nsp = ApiDBUtils.findPhysicalNetworkServiceProviderById(result.getNspId());
@@ -3689,6 +3711,73 @@ public class ApiResponseHelper implements ResponseGenerator {
         return response;
     }
 
+    
+    @Override
+    public ApplicationLoadBalancerResponse createLoadBalancerContainerReponse(ApplicationLoadBalancerRule lb, Map<Ip, UserVm> lbInstances) {
+
+        ApplicationLoadBalancerResponse lbResponse = new ApplicationLoadBalancerResponse();
+        lbResponse.setId(lb.getUuid());
+        lbResponse.setName(lb.getName());
+        lbResponse.setDescription(lb.getDescription());
+        lbResponse.setAlgorithm(lb.getAlgorithm());
+        Network nw = ApiDBUtils.findNetworkById(lb.getNetworkId());
+        lbResponse.setNetworkId(nw.getUuid());
+        populateOwner(lbResponse, lb);
+        
+        if (lb.getScheme() == Scheme.Internal) {
+            lbResponse.setSourceIp(lb.getSourceIp().addr());
+            //TODO - create the view for the load balancer rule to reflect the network uuid
+            Network network = ApiDBUtils.findNetworkById(lb.getNetworkId());
+            lbResponse.setSourceIpNetworkId(network.getUuid());
+        } else {
+            //for public, populate the ip information from the ip address
+            IpAddress publicIp = ApiDBUtils.findIpAddressById(lb.getSourceIpAddressId());
+            lbResponse.setSourceIp(publicIp.getAddress().addr());
+            Network ntwk = ApiDBUtils.findNetworkById(publicIp.getNetworkId());
+            lbResponse.setSourceIpNetworkId(ntwk.getUuid());
+        }
+        
+        //set load balancer rules information (only one rule per load balancer in this release)
+        List<ApplicationLoadBalancerRuleResponse> ruleResponses = new ArrayList<ApplicationLoadBalancerRuleResponse>();
+        ApplicationLoadBalancerRuleResponse ruleResponse = new ApplicationLoadBalancerRuleResponse();
+        ruleResponse.setInstancePort(lb.getDefaultPortStart());
+        ruleResponse.setSourcePort(lb.getSourcePortStart());
+        String stateToSet = lb.getState().toString();
+        if (stateToSet.equals(FirewallRule.State.Revoke)) {
+            stateToSet = "Deleting";
+        }
+        ruleResponse.setState(stateToSet);
+        ruleResponse.setObjectName("loadbalancerrule");
+        ruleResponses.add(ruleResponse);
+        lbResponse.setLbRules(ruleResponses);
+        
+        //set Lb instances information
+        List<ApplicationLoadBalancerInstanceResponse> instanceResponses = new ArrayList<ApplicationLoadBalancerInstanceResponse>();
+        for (Ip ip : lbInstances.keySet()) {
+            ApplicationLoadBalancerInstanceResponse instanceResponse = new ApplicationLoadBalancerInstanceResponse();
+            instanceResponse.setIpAddress(ip.addr());
+            UserVm vm = lbInstances.get(ip);
+            instanceResponse.setId(vm.getUuid());
+            instanceResponse.setName(vm.getInstanceName());
+            instanceResponse.setObjectName("loadbalancerinstance");
+            instanceResponses.add(instanceResponse);
+        }
+        
+        lbResponse.setLbInstances(instanceResponses);
+
+        //set tag information
+        List<? extends ResourceTag> tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.LoadBalancer, lb.getId());
+        List<ResourceTagResponse> tagResponses = new ArrayList<ResourceTagResponse>();
+        for (ResourceTag tag : tags) {
+            ResourceTagResponse tagResponse = createResourceTagResponse(tag, true);
+            tagResponses.add(tagResponse);
+        }
+        lbResponse.setTags(tagResponses);
+
+        lbResponse.setObjectName("loadbalancer");
+        return lbResponse;
+    }
+
     @Override
     public AffinityGroupResponse createAffinityGroupResponse(AffinityGroup group) {
 
@@ -3719,8 +3808,25 @@ public class ApiResponseHelper implements ResponseGenerator {
         }
     }
 
+    
+    @Override
+    public InternalLoadBalancerElementResponse createInternalLbElementResponse(VirtualRouterProvider result) {
+        if (result.getType() != VirtualRouterProvider.VirtualRouterProviderType.InternalLbVm) {
+            return null;
+        }
+        InternalLoadBalancerElementResponse response = new InternalLoadBalancerElementResponse();
+        response.setId(result.getUuid());
+        PhysicalNetworkServiceProvider nsp = ApiDBUtils.findPhysicalNetworkServiceProviderById(result.getNspId());
+        if (nsp != null) {
+            response.setNspId(nsp.getUuid());
+        }
+        response.setEnabled(result.isEnabled());
 
+        response.setObjectName("internalloadbalancerelement");
+        return response;
+    }
 
+    
     @Override
     public IsolationMethodResponse createIsolationMethodResponse(IsolationType method) {
         IsolationMethodResponse response = new IsolationMethodResponse();


Mime
View raw message