cloudstack-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From chipchild...@apache.org
Subject [2/6] Contrail network virtualization plugin.
Date Tue, 08 Oct 2013 13:38:34 GMT
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7099686b/plugins/network-elements/juniper-contrail/test/net/juniper/contrail/management/NetworkProviderTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/juniper-contrail/test/net/juniper/contrail/management/NetworkProviderTest.java b/plugins/network-elements/juniper-contrail/test/net/juniper/contrail/management/NetworkProviderTest.java
new file mode 100644
index 0000000..7cdb1a2
--- /dev/null
+++ b/plugins/network-elements/juniper-contrail/test/net/juniper/contrail/management/NetworkProviderTest.java
@@ -0,0 +1,789 @@
+package net.juniper.contrail.management;
+
+import java.io.IOException;
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+
+import javax.inject.Inject;
+
+import junit.framework.TestCase;
+import net.juniper.contrail.management.ContrailManager;
+import com.cloud.offering.NetworkOffering;
+import net.juniper.contrail.management.ServerDBSync;
+import net.juniper.contrail.api.ApiConnector;
+import net.juniper.contrail.api.ApiConnectorMock;
+import net.juniper.contrail.api.ApiObjectBase;
+import net.juniper.contrail.api.types.InstanceIp;
+import net.juniper.contrail.api.types.NetworkIpam;
+import net.juniper.contrail.api.types.SubnetType;
+import net.juniper.contrail.api.types.VirtualMachine;
+import net.juniper.contrail.api.types.VirtualMachineInterface;
+import net.juniper.contrail.api.types.VirtualNetwork;
+import net.juniper.contrail.api.types.VnSubnetsType;
+import net.juniper.contrail.api.types.NetworkPolicy;
+import net.juniper.contrail.api.types.Project;
+import net.juniper.contrail.api.types.VnSubnetsType;
+
+import org.apache.log4j.Logger;
+import org.mockito.Mockito;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.BaseCmd;
+import org.apache.cloudstack.api.command.user.project.CreateProjectCmd;
+import org.apache.cloudstack.api.command.user.project.DeleteProjectCmd;
+import org.apache.cloudstack.api.command.user.address.AssociateIPAddrCmd;
+import org.apache.cloudstack.api.command.user.address.ListPublicIpAddressesCmd;
+import org.apache.cloudstack.api.command.user.nat.EnableStaticNatCmd;
+import org.apache.cloudstack.api.command.user.nat.DisableStaticNatCmd;
+import org.apache.cloudstack.api.command.user.network.CreateNetworkCmd;
+import org.apache.cloudstack.api.command.admin.vlan.CreateVlanIpRangeCmd;
+import org.junit.runner.RunWith;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.AfterClass;
+import org.junit.Ignore;
+import org.junit.Test;
+
+import com.cloud.utils.db.Merovingian2;
+import com.cloud.utils.mgmt.JmxUtil;
+import org.apache.cloudstack.utils.identity.ManagementServerNode;
+import com.cloud.agent.AgentManager;
+import com.cloud.agent.api.PlugNicAnswer;
+import com.cloud.agent.api.UnPlugNicAnswer;
+import com.cloud.agent.manager.Commands;
+import com.cloud.configuration.ConfigurationManager;
+import com.cloud.configuration.ConfigurationService;
+import com.cloud.dc.DataCenter.NetworkType;
+import com.cloud.dc.DataCenterVO;
+import com.cloud.dc.dao.DataCenterDao;
+import com.cloud.domain.Domain;
+import com.cloud.exception.AgentUnavailableException;
+import com.cloud.exception.CloudException;
+import com.cloud.exception.ConcurrentOperationException;
+import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.exception.OperationTimedoutException;
+import com.cloud.exception.ResourceUnavailableException;
+import com.cloud.host.Host.Type;
+import com.cloud.host.HostVO;
+import com.cloud.host.Status;
+import com.cloud.host.dao.HostDao;
+import com.cloud.hypervisor.Hypervisor.HypervisorType;
+import com.cloud.network.Network;
+import com.cloud.network.NetworkService;
+import com.cloud.network.Network.Provider;
+import com.cloud.network.Networks.TrafficType;
+import com.cloud.network.PhysicalNetwork;
+import com.cloud.network.PhysicalNetwork.BroadcastDomainRange;
+import com.cloud.network.PhysicalNetworkServiceProvider;
+import com.cloud.network.PhysicalNetworkTrafficType;
+import com.cloud.offering.ServiceOffering;
+import com.cloud.resource.ResourceState;
+import com.cloud.service.ServiceOfferingVO;
+import com.cloud.service.dao.ServiceOfferingDao;
+import com.cloud.storage.Storage.StoragePoolType;
+import com.cloud.storage.VMTemplateVO;
+import com.cloud.storage.dao.VMTemplateDao;
+import com.cloud.domain.DomainVO;
+import com.cloud.domain.dao.DomainDao;
+import com.cloud.projects.ProjectVO;
+import com.cloud.projects.dao.ProjectDao;
+import com.cloud.user.Account;
+import com.cloud.user.AccountManager;
+import com.cloud.user.User;
+import com.cloud.uservm.UserVm;
+import com.cloud.utils.Pair;
+import com.cloud.utils.component.ComponentContext;
+import com.cloud.utils.db.SearchBuilder;
+import com.cloud.utils.db.SearchCriteria;
+import com.cloud.utils.db.SearchCriteria.Op;
+import com.cloud.vm.NicProfile;
+import com.cloud.vm.UserVmVO;
+import com.cloud.vm.VirtualMachine.State;
+import com.cloud.vm.VirtualMachineManager;
+import com.cloud.vm.dao.UserVmDao;
+import com.cloud.network.dao.IPAddressDao;
+import com.cloud.network.dao.IPAddressVO;
+import com.cloud.network.dao.NetworkDao;
+import com.cloud.network.dao.NetworkVO;
+import com.cloud.network.dao.PhysicalNetworkDao;
+import com.cloud.network.dao.PhysicalNetworkVO;
+import org.apache.cloudstack.context.CallContext;
+
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(locations="classpath:/serviceContext.xml")
+/**
+ * Exercise the public API.
+ */
+public class NetworkProviderTest extends TestCase {
+    private static final Logger s_logger =
+            Logger.getLogger(NetworkProviderTest.class);
+
+    @Inject public ConfigurationService _configService;
+    @Inject public DataCenterDao _zoneDao;
+
+    @Inject public NetworkService _networkService;
+    @Inject public ContrailManager _contrailMgr;
+    @Inject public ServerDBSync _dbSync;
+    @Inject public AccountManager _accountMgr;
+    @Inject NetworkDao _networksDao;
+    @Inject PhysicalNetworkDao _physicalNetworkDao;
+    @Inject IPAddressDao _ipAddressDao;
+
+    @Inject public VirtualMachineManager _vmMgr;
+
+    private DataCenterVO _zone;
+    private PhysicalNetwork _znet;
+    @Inject public UserVmDao _userVmDao;
+    @Inject public ServiceOfferingDao _serviceOfferingDao;
+    @Inject public VMTemplateDao _vmTemplateDao;
+    @Inject public DomainDao _domainDao;
+    @Inject public ProjectDao _projectDao;
+    @Inject public HostDao _hostDao;
+    @Inject public AgentManager _agentMgr;
+    private ApiConnector _api;
+    private long _host_id = -1L;
+    private static int _mysql_server_port;
+    private static long _msId;
+    private static Merovingian2 _lockMaster;
+    public static boolean initDone = false;
+
+    @BeforeClass
+    public static void globalSetUp() throws Exception {
+
+        s_logger.info("mysql server is getting launched ");
+        _mysql_server_port = TestDbSetup.init(null);
+        s_logger.info("mysql server launched on port " + _mysql_server_port);
+        _msId = ManagementServerNode.getManagementServerId();
+        _lockMaster = Merovingian2.createLockMaster(_msId);
+    }
+
+    @AfterClass
+    public static void globalTearDown() throws Exception {
+
+        _lockMaster.cleanupForServer(_msId);
+        JmxUtil.unregisterMBean("Locks", "Locks");
+        _lockMaster = null;
+        Thread.sleep(3000);
+
+        s_logger.info("destroying mysql server instance running at port <" + _mysql_server_port + ">");
+        TestDbSetup.destroy(_mysql_server_port, null);
+    }
+
+    @Before
+    public void setUp() throws Exception {
+        try {
+            ComponentContext.initComponentsLifeCycle();
+        } catch (Exception ex) {
+            ex.printStackTrace();
+            s_logger.error(ex.getMessage());
+        }
+        Account system = _accountMgr.getSystemAccount();
+        User user = _accountMgr.getSystemUser();
+        CallContext.register(user, system);
+        LocateZone();
+        LocatePhysicalNetwork();
+        LocateHost();
+        _api = _contrailMgr.getApiConnector();
+        if (NetworkProviderTest.initDone == false) {
+            createPublicVlanIpRange();
+            NetworkProviderTest.initDone = true;
+        }
+    }
+
+    @After
+    public void tearDown() throws Exception {
+        DeleteHost();
+    }
+
+    // TODO: Use the name parameter to retrieve the @Parameter annotation.
+    private void SetParameter(BaseCmd cmd, String name, BaseCmd.CommandType field_type, Object value) {
+        Class<?> cls = cmd.getClass();
+        Field field;
+        try {
+            field = cls.getDeclaredField(name);
+        } catch (Exception ex) {
+            s_logger.warn("class: " + cls.getName() + "\t" + ex);
+            return;
+        }
+        field.setAccessible(true);
+        switch (field_type) {
+        case STRING:
+            try {
+                field.set(cmd, value);
+            } catch (Exception ex) {
+                s_logger.warn(ex);
+                return;
+            }
+            break;
+        case UUID:
+            if (value.equals("-1")) {
+                try {
+                    field.setLong(cmd, -1L);
+                } catch (Exception ex) {
+                    s_logger.warn(ex);
+                    return;
+                }
+            }
+            break;
+        case LONG:
+            try {
+                field.set(cmd, value);
+            } catch (Exception ex) {
+                s_logger.warn(ex);
+                return;
+            }
+            break;
+        default:
+            try {
+                field.set(cmd, value);
+            } catch (Exception ex) {
+                s_logger.warn(ex);
+                return;
+            }
+            break;
+        }
+    }
+
+    private void LocateZone() {
+        _zone = _zoneDao.findByName("default");
+        if (_zone == null) {
+            ConfigurationManager mgr = (ConfigurationManager) _configService;
+            _zone = mgr.createZone(User.UID_SYSTEM, "default", "8.8.8.8", null, "8.8.4.4", null,
+                    null /* cidr */, "ROOT", Domain.ROOT_DOMAIN,
+                    NetworkType.Advanced, null, null /* networkDomain */, false, false, null, null);
+        }
+    }
+    private void LocatePhysicalNetwork() {
+        // mandatory: name, zone-id
+        try {
+            long id = _networkService.findPhysicalNetworkId(_zone.getId(), "znet", TrafficType.Guest);
+            _znet = _networkService.getPhysicalNetwork(id);
+            List<PhysicalNetworkVO> nets = _physicalNetworkDao.listByZoneAndTrafficType(_zone.getId(), TrafficType.Public);
+            if (nets == null || nets.isEmpty()) {
+                _networkService.addTrafficTypeToPhysicalNetwork(_znet.getId(), TrafficType.Public.toString(), null, null, null, null, null);
+            }
+        } catch (InvalidParameterValueException e) {
+            List<String> isolationMethods = new ArrayList<String>();
+            isolationMethods.add("GRE");
+            _znet = _networkService.createPhysicalNetwork(_zone.getId(), null, null, isolationMethods,
+                    BroadcastDomainRange.ZONE.toString(), _zone.getDomainId(),
+                    null, "znet");
+            List<PhysicalNetworkVO> nets = _physicalNetworkDao.listByZoneAndTrafficType(_zone.getId(), TrafficType.Public);
+            if (nets == null || nets.isEmpty()) {
+                _networkService.addTrafficTypeToPhysicalNetwork(_znet.getId(), TrafficType.Public.toString(), null, null, null, null, null);
+            }
+        }
+        if (_znet.getState() != PhysicalNetwork.State.Enabled) {
+            _znet = _networkService.updatePhysicalNetwork(_znet.getId(), null, null, null,
+                    PhysicalNetwork.State.Enabled.toString());
+        }
+
+        // Ensure that the physical network supports Guest traffic.
+        Pair<List<? extends PhysicalNetworkTrafficType>, Integer> trafficTypes =
+                _networkService.listTrafficTypes(_znet.getId());
+        boolean found = false;
+        for (PhysicalNetworkTrafficType ttype: trafficTypes.first()) {
+            if (ttype.getTrafficType() == TrafficType.Guest) {
+                found = true;
+            }
+        }
+        if (!found) {
+            _networkService.addTrafficTypeToPhysicalNetwork(_znet.getId(), TrafficType.Guest.toString(),
+                    null, null, null, null, null);
+        }
+
+        Pair<List<? extends PhysicalNetworkServiceProvider>, Integer> providers =
+                _networkService.listNetworkServiceProviders(_znet.getId(), Provider.JuniperContrail.getName(),
+                        null, null, null);
+        if (providers.second() == 0) {
+            s_logger.debug("Add " + Provider.JuniperContrail.getName() + " to network " + _znet.getName());
+            PhysicalNetworkServiceProvider provider =
+                    _networkService.addProviderToPhysicalNetwork(_znet.getId(), Provider.JuniperContrail.getName(),
+                            null, null);
+            _networkService.updateNetworkServiceProvider(provider.getId(),
+                    PhysicalNetworkServiceProvider.State.Enabled.toString(), null);
+        } else {
+            PhysicalNetworkServiceProvider provider = providers.first().get(0);
+            if (provider.getState() != PhysicalNetworkServiceProvider.State.Enabled) {
+                _networkService.updateNetworkServiceProvider(provider.getId(),
+                        PhysicalNetworkServiceProvider.State.Enabled.toString(), null); 
+            }
+        }
+
+        providers = _networkService.listNetworkServiceProviders(_znet.getId(), null,
+                PhysicalNetworkServiceProvider.State.Enabled.toString(), null, null);
+        s_logger.debug(_znet.getName() + " has " + providers.second().toString() + " Enabled providers");
+        for (PhysicalNetworkServiceProvider provider: providers.first()) {
+            if (provider.getProviderName().equals(Provider.JuniperContrail.getName())) {
+                continue;
+            }
+            s_logger.debug("Disabling " + provider.getProviderName());
+            _networkService.updateNetworkServiceProvider(provider.getId(),
+                    PhysicalNetworkServiceProvider.State.Disabled.toString(), null);
+        }
+    }
+
+    private void LocateHost() {
+        HostVO host = new HostVO(_host_id, "aa01", Type.BaremetalDhcp,
+                "192.168.1.1", "255.255.255.0", null,
+                null, null, null,
+                null, null, null,
+                null, null, null,
+                UUID.randomUUID().toString(), Status.Up, "1.0", null,
+                null, _zone.getId(), null, 0, 0, "aa", 0, StoragePoolType.NetworkFilesystem);
+        host.setResourceState(ResourceState.Enabled);
+        _hostDao.persist(host);
+        _host_id = host.getId();
+    }
+
+    private void DeleteHost() {
+        _hostDao.remove(_host_id);
+
+    }
+    private void purgeTestNetwork() {
+        Account system = _accountMgr.getSystemAccount();
+        List<? extends Network> list =
+                _networkService.getIsolatedNetworksOwnedByAccountInZone(_zone.getId(), system);
+        for (Network net : list) {
+            s_logger.debug("Delete network " + net.getName());
+            _networkService.deleteNetwork(net.getId());
+        }
+    }
+
+    private Network lookupTestNetwork(String name) {
+        Account system = _accountMgr.getSystemAccount();
+        List<? extends Network> list =
+                _networkService.getIsolatedNetworksOwnedByAccountInZone(_zone.getId(), system);
+        for (Network net : list) {
+            if (net.getName().equals(name)) {
+                return net;
+            }
+        }
+        return null;
+    }
+
+    private Network createTestNetwork(String name) {
+        CreateNetworkCmd cmd = new CreateNetworkCmd();
+        BaseCmd proxy = ComponentContext.inject(cmd);
+        Account system = _accountMgr.getSystemAccount();
+
+        SetParameter(cmd, "accountName", BaseCmd.CommandType.STRING, system.getAccountName());
+        SetParameter(cmd, ApiConstants.NAME, BaseCmd.CommandType.STRING, name);
+        SetParameter(cmd, "displayText", BaseCmd.CommandType.STRING, "test network");
+        SetParameter(cmd, "networkOfferingId", BaseCmd.CommandType.LONG, _contrailMgr.getOffering().getId());
+        SetParameter(cmd, "zoneId", BaseCmd.CommandType.LONG, _zone.getId());
+        SetParameter(cmd, ApiConstants.GATEWAY, BaseCmd.CommandType.STRING, "10.0.1.254");
+        SetParameter(cmd, ApiConstants.NETMASK, BaseCmd.CommandType.STRING, "255.255.255.0");
+        // Physical network id can't be specified for Guest traffic type.
+        // SetParameter(cmd, "physicalNetworkId", BaseCmd.CommandType.LONG, _znet.getId());
+
+        Network result = null;
+        try {
+            result = _networkService.createGuestNetwork(cmd);
+        } catch (CloudException e) {
+            e.printStackTrace();
+            return null;
+        }
+        return result;
+    }
+
+    private void createPublicVlanIpRange() {
+        CreateVlanIpRangeCmd cmd = new CreateVlanIpRangeCmd();
+        BaseCmd proxy = ComponentContext.inject(cmd);
+        Long public_net_id = null;
+
+        List<NetworkVO> nets = _networksDao.listByZoneAndTrafficType(_zone.getId(), TrafficType.Public);
+        if (nets != null && !nets.isEmpty()) {
+            NetworkVO public_net = nets.get(0); 
+            public_net_id = public_net.getId();
+        } else {
+            s_logger.debug("no public network found in the zone: " + _zone.getId());
+        }
+        Account system = _accountMgr.getSystemAccount();
+
+        SetParameter(cmd, "accountName", BaseCmd.CommandType.STRING, system.getAccountName());
+        SetParameter(cmd, "domainId", BaseCmd.CommandType.LONG, Domain.ROOT_DOMAIN);
+        SetParameter(cmd, "startIp", BaseCmd.CommandType.STRING, "10.84.60.200");
+        SetParameter(cmd, "endIp", BaseCmd.CommandType.STRING, "10.84.60.250");
+        SetParameter(cmd, ApiConstants.GATEWAY, BaseCmd.CommandType.STRING, "10.84.60.254");
+        SetParameter(cmd, ApiConstants.NETMASK, BaseCmd.CommandType.STRING, "255.255.255.0");
+        SetParameter(cmd, "networkID", BaseCmd.CommandType.LONG, public_net_id);
+        SetParameter(cmd, "zoneId", BaseCmd.CommandType.LONG, _zone.getId());
+        //SetParameter(cmd, "forVirtualNetwork", BaseCmd.CommandType.BOOLEAN, true);
+        SetParameter(cmd, "vlan", BaseCmd.CommandType.STRING, "untagged");
+        s_logger.debug("createPublicVlanIpRange execute : zone id: " + _zone.getId() + ", public net id: " + public_net_id);
+        try {
+           _configService.createVlanAndPublicIpRange(cmd);
+        } catch (Exception e) {
+           s_logger.debug("createPublicVlanIpRange: " + e);
+        }
+    }
+
+    @Test
+    //@Ignore
+    public void testCreateNetwork() {
+        purgeTestNetwork();
+        createTestNetwork("test");
+    }
+
+    private VMTemplateVO getVMTemplate() {
+        List<VMTemplateVO> tmpl_list = _vmTemplateDao.listDefaultBuiltinTemplates();
+        for (VMTemplateVO tmpl: tmpl_list) {
+            if (tmpl.getHypervisorType() == HypervisorType.XenServer) {
+                return tmpl;
+            }
+        }    
+        return null;
+    }
+
+    private ServiceOffering getServiceByName(String name) {
+        List<ServiceOfferingVO> service_list = _serviceOfferingDao.findPublicServiceOfferings();
+        for (ServiceOfferingVO service: service_list) {
+            if (service.getName().equals(name)) {
+                return service;
+            }
+        }
+        return null;
+    }
+
+    private UserVm createVM(String name, Network network) {
+        VMTemplateVO tmpl = getVMTemplate();
+        assertNotNull(tmpl);
+        ServiceOffering small = getServiceByName("Small Instance");
+        assertNotNull(small);
+
+        Answer<?> callback = new Answer<Object>() {
+            public Object answer(InvocationOnMock invocation) {
+                Object[] args = invocation.getArguments();
+                Commands cmds = (Commands) args[1];
+                if (cmds == null) {
+                    return null;
+                }
+                PlugNicAnswer reply = new PlugNicAnswer(null, true, "PlugNic");
+                com.cloud.agent.api.Answer[] answers = { reply };
+                cmds.setAnswers(answers);
+                return null;
+            }
+        };
+        try {
+            Mockito.when(_agentMgr.send(Mockito.anyLong(), Mockito.any(Commands.class))).thenAnswer(callback);
+        } catch (AgentUnavailableException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } catch (OperationTimedoutException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+        long id = _userVmDao.getNextInSequence(Long.class, "id");
+        UserVmVO vm = new UserVmVO(id, name, name, tmpl.getId(), HypervisorType.XenServer, tmpl.getGuestOSId(),
+                false, false, _zone.getDomainId(), Account.ACCOUNT_ID_SYSTEM, small.getId(), null, name, null);
+        vm.setState(State.Running);
+        vm.setHostId(_host_id);
+        vm.setDataCenterId(network.getDataCenterId());
+        _userVmDao.persist(vm);
+
+        NicProfile profile = new NicProfile();
+        try {
+            _vmMgr.addVmToNetwork(vm, network, profile);
+        } catch (Exception ex) {
+            // TODO Auto-generated catch block
+            //ex.printStackTrace();
+        }
+        return vm;
+    }
+
+    private void deleteVM(UserVm vm, Network network) {
+        Answer<?> callback = new Answer<Object>() {
+            public Object answer(InvocationOnMock invocation) {
+                Object[] args = invocation.getArguments();
+                Commands cmds = (Commands) args[1];
+                if (cmds == null) {
+                    return null;
+                }
+                UnPlugNicAnswer reply = new UnPlugNicAnswer(null, true, "PlugNic");
+                com.cloud.agent.api.Answer[] answers = { reply };
+                cmds.setAnswers(answers);
+                return null;
+            }
+        };
+
+        try {
+            Mockito.when(_agentMgr.send(Mockito.anyLong(), Mockito.any(Commands.class))).thenAnswer(callback);
+        } catch (AgentUnavailableException e) {
+            e.printStackTrace();
+        } catch (OperationTimedoutException e) {
+            e.printStackTrace();
+        }
+
+/*
+        try {
+             if (network == null) {
+                s_logger.debug("network is NULL");
+             } else {
+                s_logger.debug("network data center: " + network.getDataCenterId());
+             }
+            //_vmMgr.removeVmFromNetwork(vm, network, null);
+        } catch (ConcurrentOperationException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } catch (ResourceUnavailableException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+*/
+        _userVmDao.remove(vm.getId());
+    }
+
+    @Test
+    public void testConnectivity() {
+        Network network = lookupTestNetwork("test");
+        if (network == null) {
+            network = createTestNetwork("test");
+        }
+        UserVm vm1 = createVM("x01", network);
+        UserVm vm2 = createVM("x02", network);
+
+        deleteVM(vm1, network);
+        deleteVM(vm2, network);
+    }
+
+    @Test
+    public void floatingIpTest() {
+        Network network = lookupTestNetwork("test-fip-net");
+        if (network == null) {
+            network = createTestNetwork("test-fip-net");
+        }
+        UserVm vm = createVM("test-fip-vm", network);
+        try {
+            IPAddressVO ip = createFloatingIp(network, vm);
+            deleteFloatingIp(ip);
+        } catch (Exception e) {
+            fail("unable to create/delete floating ip");
+        }
+        deleteVM(vm, network);
+    }
+
+    public void deleteFloatingIp(IPAddressVO ip) throws Exception{
+        BaseCmd cmd = new DisableStaticNatCmd();
+        BaseCmd proxy = ComponentContext.inject(cmd);
+        SetParameter(proxy, "ipAddressId", BaseCmd.CommandType.LONG, ip.getId());
+        try {
+            proxy.execute();
+        } catch (Exception e) {
+            s_logger.debug("DisableStaticNatCmd exception: " + e);
+            e.printStackTrace();
+            throw e;
+        }
+    }
+
+    public IPAddressVO createFloatingIp(Network network, UserVm vm) throws Exception {
+        BaseCmd cmd = new AssociateIPAddrCmd();
+        BaseCmd proxy = ComponentContext.inject(cmd);
+        Account system = _accountMgr.getSystemAccount();
+
+        SetParameter(proxy, "accountName", BaseCmd.CommandType.STRING, system.getAccountName());
+        SetParameter(proxy, "domainId", BaseCmd.CommandType.LONG, Domain.ROOT_DOMAIN);
+        SetParameter(proxy, "zoneId", BaseCmd.CommandType.LONG, _zone.getId());
+        SetParameter(proxy, "networkId", BaseCmd.CommandType.LONG, network.getId());
+        try {
+            ((AssociateIPAddrCmd)cmd).create();
+            ((AssociateIPAddrCmd)cmd).execute();
+        } catch (Exception e) {
+            s_logger.debug("AssociateIPAddrCmd exception: " + e);
+            e.printStackTrace();
+            throw e;
+        }
+
+        SearchBuilder<IPAddressVO> searchBuilder = _ipAddressDao.createSearchBuilder();
+        searchBuilder.and("sourceNat", searchBuilder.entity().isSourceNat(), Op.EQ);
+        searchBuilder.and("network", searchBuilder.entity().getAssociatedWithNetworkId(), Op.EQ);
+        searchBuilder.and("dataCenterId", searchBuilder.entity().getDataCenterId(), Op.EQ);
+        searchBuilder.and("associatedWithVmId", searchBuilder.entity().getAssociatedWithVmId(), Op.NULL);
+        SearchCriteria<IPAddressVO> sc = searchBuilder.create();
+        sc.setParameters("sourceNat", false);
+        sc.setParameters("network", network.getId());
+
+        List<IPAddressVO> publicIps = _ipAddressDao.search(sc, null);
+        assertNotNull(publicIps);
+
+        cmd = new EnableStaticNatCmd();
+        proxy = ComponentContext.inject(cmd);
+        SetParameter(proxy, "ipAddressId", BaseCmd.CommandType.LONG, publicIps.get(0).getId());
+        SetParameter(proxy, "networkId", BaseCmd.CommandType.LONG, network.getId());
+        SetParameter(proxy, "virtualMachineId", BaseCmd.CommandType.LONG, vm.getId());
+
+        try {
+            proxy.execute();
+        } catch (Exception e) {
+            s_logger.debug("EnableStaticNatCmd exception: " + e);
+            e.printStackTrace();
+            throw e;
+        }
+        return publicIps.get(0);
+    }
+
+    public void createProject(String name) {
+        BaseCmd cmd = new CreateProjectCmd();
+        BaseCmd proxy = ComponentContext.inject(cmd);
+        Account system = _accountMgr.getSystemAccount();
+
+        SetParameter(proxy, "accountName", BaseCmd.CommandType.STRING, system.getAccountName());
+        SetParameter(proxy, "domainId", BaseCmd.CommandType.LONG, Domain.ROOT_DOMAIN);
+        SetParameter(proxy, "name", BaseCmd.CommandType.STRING, name);
+        SetParameter(proxy, "displayText", BaseCmd.CommandType.STRING, name);
+        try {
+            ((CreateProjectCmd)proxy).create();
+            ((CreateProjectCmd)proxy).execute();
+        } catch (Exception e) {
+            s_logger.debug("CreateProjectCmd exception: " + e);
+            e.printStackTrace();
+            fail("create project cmd failed");
+        }
+        DomainVO domain = _domainDao.findById(Domain.ROOT_DOMAIN);
+        try {
+            net.juniper.contrail.api.types.Domain vncDomain = (net.juniper.contrail.api.types.Domain)
+                    _api.findById(net.juniper.contrail.api.types.Domain.class, domain.getUuid());
+            if (_api.findByName(net.juniper.contrail.api.types.Project.class, vncDomain, name) == null) {
+                 fail("create project failed in vnc");
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+            fail("Exception while creating a project in vnc");
+        }
+    }
+
+    public void deleteProject(String name) {
+        BaseCmd cmd = new DeleteProjectCmd();
+        BaseCmd proxy = ComponentContext.inject(cmd);
+
+        ProjectVO project = _projectDao.findByNameAndDomain(name, Domain.ROOT_DOMAIN);
+        try {
+            SetParameter(proxy, "id", BaseCmd.CommandType.LONG, project.getId());
+            ((DeleteProjectCmd)proxy).execute();
+            if (_api.findById(net.juniper.contrail.api.types.Project.class, project.getUuid()) != null) {
+                 fail("unable to delete project in vnc");
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+            fail("Exception while deleting project");
+        }
+    }
+
+    @Test
+    public void testProject() {
+        createProject("test-project");
+        deleteProject("test-project");
+    }
+
+    @Test
+    public void dbSyncTest() {
+        Network network = lookupTestNetwork("test-db-only-net");
+        if (network == null) {
+            network = createTestNetwork("test-db-only-net");
+        }
+        UserVm vm = createVM("test-db-only-vm", network);
+        try {
+            createFloatingIp(network, vm);
+        } catch (Exception e) {
+            fail("unable to create floating ip");
+        }
+
+        /* reset ApiServer objects to default config only, so above created objects 
+         * exists only in cludstack db but not in api server
+         */
+        ((ApiConnectorMock)_api).initConfig();
+        /* reset model cached objects */
+        _contrailMgr.getDatabase().initDb();
+
+        /* Create one object of each type directly in api-server - these objects does not exist in cloudstack */
+        net.juniper.contrail.api.types.Domain domain = new net.juniper.contrail.api.types.Domain();
+        domain.setName("test-vnc-only-domain--1");
+        domain.setUuid(UUID.randomUUID().toString());
+        try {
+            assertTrue(_api.create(domain));
+        } catch (IOException ex) {
+            fail(ex.getMessage());
+        }
+
+        Project project = new Project();
+        project.setName("test-vnc-only-project-1");
+        project.setUuid(UUID.randomUUID().toString());
+        project.setParent(domain);
+        try {
+            assertTrue(_api.create(project));
+        } catch (IOException ex) {
+            fail(ex.getMessage());
+        }
+
+        VirtualNetwork net = new VirtualNetwork();
+        net.setName("test-vnc-only-net-1");
+        net.setUuid(UUID.randomUUID().toString());
+        net.setParent(project);
+        
+        NetworkIpam ipam = null;
+        try {
+            // Find default-network-ipam
+            String ipam_id = _api.findByName(NetworkIpam.class, null, "default-network-ipam");
+            assertNotNull(ipam_id);
+            ipam = (NetworkIpam) _api.findById(NetworkIpam.class, ipam_id);
+            assertNotNull(ipam);
+        } catch (IOException ex) {
+            fail(ex.getMessage());
+        }
+
+        VnSubnetsType subnet = new VnSubnetsType();
+        subnet.addIpamSubnets(new SubnetType("10.0.2.0", 24), "10.0.2.254");
+
+        net.addNetworkIpam(ipam, subnet);
+
+        VirtualMachine vncVm = new VirtualMachine();
+        vncVm.setName("test-vnc-only-vm-1");
+        try {
+            assertTrue(_api.create(vncVm));
+        } catch (IOException ex) {
+            fail(ex.getMessage());
+        }
+
+        VirtualMachineInterface vmi = new VirtualMachineInterface();
+        vmi.setParent(vncVm);
+        vmi.setName("test-vnc-only-vmi-1");
+
+        try {
+            assertTrue(_api.create(vmi));
+            assertTrue(_api.create(net));
+        } catch (IOException ex) {
+            fail(ex.getMessage());
+        }
+        InstanceIp ip_obj = new InstanceIp();
+        ip_obj.setName(net.getName() + ":0");
+        ip_obj.setVirtualNetwork(net);
+        ip_obj.setVirtualMachineInterface(vmi);
+        try {
+            assertTrue(_api.create(ip_obj));
+            // Must perform a GET in order to update the object contents.
+            assertTrue(_api.read(ip_obj));
+            assertNotNull(ip_obj.getAddress());
+
+        } catch (IOException ex) {
+            fail(ex.getMessage());
+        }
+        
+        //now db sync
+        if (_dbSync.syncAll(DBSyncGeneric.SYNC_MODE_UPDATE) == ServerDBSync.SYNC_STATE_OUT_OF_SYNC) {
+            s_logger.info("# Cloudstack DB & VNC are out of sync - resync done");
+        }
+        
+        if (_dbSync.syncAll(DBSyncGeneric.SYNC_MODE_CHECK) == ServerDBSync.SYNC_STATE_OUT_OF_SYNC) {
+            s_logger.info("# Cloudstack DB & VNC are still out of sync");
+            fail("DB Sync failed"); 
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7099686b/plugins/network-elements/juniper-contrail/test/net/juniper/contrail/management/TestConfiguration.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/juniper-contrail/test/net/juniper/contrail/management/TestConfiguration.java b/plugins/network-elements/juniper-contrail/test/net/juniper/contrail/management/TestConfiguration.java
new file mode 100644
index 0000000..0f682d6
--- /dev/null
+++ b/plugins/network-elements/juniper-contrail/test/net/juniper/contrail/management/TestConfiguration.java
@@ -0,0 +1,803 @@
+package net.juniper.contrail.management;
+
+import java.io.IOException;
+
+import javax.inject.Inject;
+
+import com.cloud.network.dao.IPAddressDao;
+import com.cloud.network.IpAddress;
+import org.apache.cloudstack.acl.APIChecker;
+import org.apache.cloudstack.acl.ControlledEntity;
+import org.apache.cloudstack.affinity.AffinityGroupService;
+import org.apache.cloudstack.affinity.AffinityGroupVO;
+import org.apache.cloudstack.affinity.dao.AffinityGroupDao;
+import org.apache.cloudstack.affinity.dao.AffinityGroupDaoImpl;
+import org.apache.cloudstack.affinity.dao.AffinityGroupDomainMapDaoImpl;
+import org.apache.cloudstack.affinity.dao.AffinityGroupVMMapDaoImpl;
+import org.apache.cloudstack.api.IdentityService;
+import org.apache.cloudstack.engine.service.api.OrchestrationService;
+import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
+import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector;
+import org.apache.cloudstack.engine.subsystem.api.storage.StoragePoolAllocator;
+import org.apache.cloudstack.engine.subsystem.api.storage.TemplateDataFactory;
+import org.apache.cloudstack.engine.subsystem.api.storage.TemplateService;
+import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory;
+import org.apache.cloudstack.lb.dao.ApplicationLoadBalancerRuleDaoImpl;
+import org.apache.cloudstack.query.QueryService;
+import org.apache.cloudstack.region.PortableIpDaoImpl;
+import org.apache.cloudstack.region.PortableIpRangeDaoImpl;
+import org.apache.cloudstack.region.RegionManager;
+import org.apache.cloudstack.region.dao.RegionDaoImpl;
+import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDaoImpl;
+import org.apache.cloudstack.storage.image.db.ImageStoreDaoImpl;
+import org.apache.cloudstack.storage.image.db.TemplateDataStoreDaoImpl;
+import org.apache.cloudstack.usage.UsageService;
+import org.mockito.Mockito;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+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.acl.DomainChecker;
+import com.cloud.agent.AgentManager;
+import com.cloud.agent.manager.allocator.HostAllocator;
+import com.cloud.agent.manager.allocator.PodAllocator;
+import com.cloud.alert.AlertManager;
+import com.cloud.api.ApiDBUtils;
+import com.cloud.api.query.dao.AccountJoinDaoImpl;
+import com.cloud.api.query.dao.AffinityGroupJoinDaoImpl;
+import com.cloud.api.query.dao.AsyncJobJoinDaoImpl;
+import com.cloud.api.query.dao.DataCenterJoinDaoImpl;
+import com.cloud.api.query.dao.DiskOfferingJoinDaoImpl;
+import com.cloud.api.query.dao.DomainRouterJoinDaoImpl;
+import com.cloud.api.query.dao.HostJoinDaoImpl;
+import com.cloud.api.query.dao.ImageStoreJoinDaoImpl;
+import com.cloud.api.query.dao.InstanceGroupJoinDaoImpl;
+import com.cloud.api.query.dao.ProjectAccountJoinDaoImpl;
+import com.cloud.api.query.dao.ProjectInvitationJoinDaoImpl;
+import com.cloud.api.query.dao.ProjectJoinDaoImpl;
+import com.cloud.api.query.dao.ResourceTagJoinDaoImpl;
+import com.cloud.api.query.dao.SecurityGroupJoinDaoImpl;
+import com.cloud.api.query.dao.ServiceOfferingJoinDaoImpl;
+import com.cloud.api.query.dao.StoragePoolJoinDaoImpl;
+import com.cloud.api.query.dao.TemplateJoinDaoImpl;
+import com.cloud.api.query.dao.UserAccountJoinDaoImpl;
+import com.cloud.api.query.dao.UserVmJoinDaoImpl;
+import com.cloud.api.query.dao.VolumeJoinDaoImpl;
+import com.cloud.capacity.CapacityManager;
+import com.cloud.capacity.dao.CapacityDaoImpl;
+import com.cloud.cluster.ClusterManager;
+import com.cloud.cluster.agentlb.dao.HostTransferMapDaoImpl;
+import com.cloud.cluster.dao.ManagementServerHostDaoImpl;
+import com.cloud.configuration.ConfigurationManagerImpl;
+import org.apache.cloudstack.framework.config.dao.ConfigurationDaoImpl;
+import com.cloud.configuration.dao.ResourceCountDaoImpl;
+import com.cloud.configuration.dao.ResourceLimitDaoImpl;
+import com.cloud.consoleproxy.ConsoleProxyManager;
+import com.cloud.consoleproxy.ConsoleProxyService;
+import com.cloud.dc.ClusterDetailsDaoImpl;
+import com.cloud.dc.DataCenter;
+import com.cloud.dc.dao.AccountVlanMapDaoImpl;
+import com.cloud.dc.dao.ClusterDaoImpl;
+import com.cloud.dc.dao.DataCenterDaoImpl;
+import com.cloud.dc.dao.DataCenterIpAddressDaoImpl;
+import com.cloud.dc.dao.DataCenterLinkLocalIpAddressDaoImpl;
+import com.cloud.dc.dao.DataCenterVnetDaoImpl;
+import com.cloud.dc.dao.DcDetailsDaoImpl;
+import com.cloud.dc.dao.DedicatedResourceDaoImpl;
+import com.cloud.dc.dao.HostPodDaoImpl;
+import com.cloud.dc.dao.PodVlanDaoImpl;
+import com.cloud.dc.dao.PodVlanMapDaoImpl;
+import com.cloud.dc.dao.VlanDaoImpl;
+import com.cloud.deploy.DeploymentPlanner;
+import com.cloud.deploy.DeploymentPlanningManager;
+import com.cloud.deploy.dao.PlannerHostReservationDaoImpl;
+import com.cloud.domain.dao.DomainDaoImpl;
+import com.cloud.event.dao.EventDaoImpl;
+import com.cloud.event.dao.EventJoinDaoImpl;
+import com.cloud.event.dao.UsageEventDaoImpl;
+import com.cloud.ha.HighAvailabilityManager;
+import com.cloud.host.dao.HostDaoImpl;
+import com.cloud.host.dao.HostDetailsDaoImpl;
+import com.cloud.host.dao.HostTagsDaoImpl;
+import com.cloud.hypervisor.HypervisorGuruManagerImpl;
+import com.cloud.hypervisor.dao.HypervisorCapabilitiesDaoImpl;
+import com.cloud.network.ExternalDeviceUsageManager;
+import com.cloud.network.Ipv6AddressManagerImpl;
+import com.cloud.network.NetworkModelImpl;
+import com.cloud.network.NetworkServiceImpl;
+import com.cloud.network.NetworkUsageService;
+import com.cloud.network.StorageNetworkManager;
+import com.cloud.network.StorageNetworkService;
+import com.cloud.network.as.AutoScaleService;
+import com.cloud.network.as.dao.AutoScalePolicyConditionMapDaoImpl;
+import com.cloud.network.as.dao.AutoScalePolicyDaoImpl;
+import com.cloud.network.as.dao.AutoScaleVmGroupDaoImpl;
+import com.cloud.network.as.dao.AutoScaleVmGroupPolicyMapDaoImpl;
+import com.cloud.network.as.dao.AutoScaleVmProfileDaoImpl;
+import com.cloud.network.as.dao.ConditionDaoImpl;
+import com.cloud.network.as.dao.CounterDaoImpl;
+import com.cloud.network.dao.AccountGuestVlanMapDaoImpl;
+import com.cloud.network.dao.FirewallRulesCidrsDaoImpl;
+import com.cloud.network.dao.FirewallRulesDaoImpl;
+import com.cloud.network.dao.LBHealthCheckPolicyDaoImpl;
+import com.cloud.network.dao.LBStickinessPolicyDaoImpl;
+import com.cloud.network.dao.LoadBalancerDaoImpl;
+import com.cloud.network.dao.LoadBalancerVMMapDaoImpl;
+import com.cloud.network.dao.NetworkAccountDaoImpl;
+import com.cloud.network.dao.NetworkDaoImpl;
+import com.cloud.network.dao.NetworkDomainDaoImpl;
+import com.cloud.network.dao.NetworkOpDaoImpl;
+import com.cloud.network.dao.NetworkRuleConfigDaoImpl;
+import com.cloud.network.dao.NetworkServiceMapDaoImpl;
+import com.cloud.network.dao.PhysicalNetworkDaoImpl;
+import com.cloud.network.dao.PhysicalNetworkServiceProviderDaoImpl;
+import com.cloud.network.dao.PhysicalNetworkTrafficTypeDaoImpl;
+import com.cloud.network.dao.RemoteAccessVpnDaoImpl;
+import com.cloud.network.dao.RouterNetworkDaoImpl;
+import com.cloud.network.dao.Site2SiteCustomerGatewayDaoImpl;
+import com.cloud.network.dao.Site2SiteVpnConnectionDaoImpl;
+import com.cloud.network.dao.Site2SiteVpnGatewayDaoImpl;
+import com.cloud.network.dao.UserIpv6AddressDaoImpl;
+import com.cloud.network.dao.VirtualRouterProviderDaoImpl;
+import com.cloud.network.dao.VpnUserDaoImpl;
+import com.cloud.network.element.Site2SiteVpnServiceProvider;
+import com.cloud.network.firewall.FirewallManagerImpl;
+import com.cloud.network.lb.LoadBalancingRulesManagerImpl;
+import com.cloud.network.router.VpcVirtualNetworkApplianceManagerImpl;
+import com.cloud.network.rules.RulesManagerImpl;
+import com.cloud.network.rules.dao.PortForwardingRulesDaoImpl;
+import com.cloud.network.security.dao.SecurityGroupDaoImpl;
+import com.cloud.network.security.dao.SecurityGroupRuleDaoImpl;
+import com.cloud.network.security.dao.SecurityGroupRulesDaoImpl;
+import com.cloud.network.security.dao.SecurityGroupVMMapDaoImpl;
+import com.cloud.network.security.dao.SecurityGroupWorkDaoImpl;
+import com.cloud.network.security.dao.VmRulesetLogDaoImpl;
+import com.cloud.network.vpc.NetworkACLManagerImpl;
+import com.cloud.network.vpc.NetworkACLService;
+import com.cloud.network.vpc.VpcManagerImpl;
+import com.cloud.network.vpc.dao.NetworkACLDaoImpl;
+import com.cloud.network.vpc.dao.NetworkACLItemDaoImpl;
+import com.cloud.network.vpc.dao.PrivateIpDaoImpl;
+import com.cloud.network.vpc.dao.StaticRouteDaoImpl;
+import com.cloud.network.vpc.dao.VpcDaoImpl;
+import com.cloud.network.vpc.dao.VpcGatewayDaoImpl;
+import com.cloud.network.vpc.dao.VpcOfferingDaoImpl;
+import com.cloud.network.vpc.dao.VpcOfferingServiceMapDaoImpl;
+import com.cloud.network.vpc.dao.VpcServiceMapDaoImpl;
+import com.cloud.network.vpn.RemoteAccessVpnService;
+import com.cloud.network.vpn.Site2SiteVpnManager;
+import com.cloud.projects.dao.ProjectInvitationDaoImpl;
+import com.cloud.dc.DataCenter;
+import com.cloud.dc.dao.DataCenterDao;
+import com.cloud.offerings.dao.NetworkOfferingDaoImpl;
+import com.cloud.offerings.dao.NetworkOfferingDao;
+import com.cloud.offering.NetworkOffering;
+import com.cloud.offerings.dao.NetworkOfferingDetailsDaoImpl;
+import com.cloud.offerings.dao.NetworkOfferingServiceMapDaoImpl;
+import com.cloud.projects.ProjectManager;
+import com.cloud.projects.dao.ProjectAccountDaoImpl;
+import com.cloud.projects.ProjectManagerImpl;
+import com.cloud.projects.dao.ProjectDaoImpl;
+import com.cloud.region.ha.GlobalLoadBalancingRulesService;
+import com.cloud.resource.ResourceManager;
+import com.cloud.server.ConfigurationServerImpl;
+import com.cloud.server.ManagementServer;
+import com.cloud.server.ResourceMetaDataService;
+import com.cloud.server.StatsCollector;
+import com.cloud.server.TaggedResourceService;
+import com.cloud.server.auth.UserAuthenticator;
+import com.cloud.service.dao.ServiceOfferingDaoImpl;
+import com.cloud.service.dao.ServiceOfferingDetailsDaoImpl;
+import com.cloud.storage.DataStoreProviderApiService;
+import com.cloud.storage.StorageManager;
+import com.cloud.storage.dao.DiskOfferingDaoImpl;
+import com.cloud.storage.dao.GuestOSCategoryDaoImpl;
+import com.cloud.storage.dao.GuestOSDaoImpl;
+import com.cloud.storage.dao.LaunchPermissionDao;
+import com.cloud.storage.dao.SnapshotDaoImpl;
+import com.cloud.storage.dao.SnapshotPolicyDaoImpl;
+import com.cloud.storage.dao.StoragePoolDetailsDaoImpl;
+import com.cloud.storage.dao.StoragePoolHostDaoImpl;
+import com.cloud.storage.dao.UploadDaoImpl;
+import com.cloud.storage.dao.VMTemplateDaoImpl;
+import com.cloud.storage.dao.VMTemplateDetailsDaoImpl;
+import com.cloud.storage.dao.VMTemplateHostDaoImpl;
+import com.cloud.storage.dao.VMTemplateZoneDaoImpl;
+import com.cloud.storage.dao.VolumeDaoImpl;
+import com.cloud.storage.dao.VolumeHostDaoImpl;
+import com.cloud.storage.secondary.SecondaryStorageVmManager;
+import com.cloud.storage.snapshot.SnapshotApiService;
+import com.cloud.storage.snapshot.SnapshotManager;
+import com.cloud.storage.VolumeApiService;
+import com.cloud.tags.dao.ResourceTagDao;
+import com.cloud.tags.dao.ResourceTagsDaoImpl;
+import com.cloud.template.TemplateApiService;
+import com.cloud.template.TemplateManager;
+import com.cloud.user.Account;
+import com.cloud.user.dao.AccountDao;
+import com.cloud.user.AccountManager;
+import com.cloud.user.User;
+import com.cloud.user.UserVO;
+import com.cloud.user.dao.UserDao;
+import com.cloud.user.AccountDetailsDaoImpl;
+import com.cloud.user.AccountVO;
+import com.cloud.user.DomainManagerImpl;
+import com.cloud.user.ResourceLimitService;
+import com.cloud.user.dao.AccountDaoImpl;
+import com.cloud.user.dao.SSHKeyPairDaoImpl;
+import com.cloud.user.dao.UserDaoImpl;
+import com.cloud.user.dao.UserStatisticsDaoImpl;
+import com.cloud.user.dao.UserStatsLogDaoImpl;
+import com.cloud.user.dao.VmDiskStatisticsDaoImpl;
+import com.cloud.utils.db.DB;
+import com.cloud.utils.db.Transaction;
+import com.cloud.uuididentity.dao.IdentityDaoImpl;
+import com.cloud.vm.ItWorkDaoImpl;
+import com.cloud.vm.dao.ConsoleProxyDaoImpl;
+import com.cloud.vm.dao.DomainRouterDaoImpl;
+import com.cloud.vm.dao.InstanceGroupDaoImpl;
+import com.cloud.vm.dao.InstanceGroupVMMapDaoImpl;
+import com.cloud.vm.dao.NicIpAliasDaoImpl;
+import com.cloud.vm.dao.NicSecondaryIpDaoImpl;
+import com.cloud.vm.dao.SecondaryStorageVmDaoImpl;
+import com.cloud.vm.dao.UserVmCloneSettingDaoImpl;
+import com.cloud.vm.dao.UserVmDaoImpl;
+import com.cloud.vm.dao.UserVmDetailsDaoImpl;
+import com.cloud.vm.dao.VMInstanceDaoImpl;
+import com.cloud.vm.snapshot.VMSnapshotManager;
+import com.cloud.vm.snapshot.dao.VMSnapshotDaoImpl;
+import org.apache.cloudstack.framework.jobs.impl.AsyncJobManagerImpl;
+import org.apache.cloudstack.framework.jobs.dao.AsyncJobDaoImpl;
+import org.apache.cloudstack.engine.orchestration.service.VolumeOrchestrationService;
+import com.cloud.network.IpAddressManagerImpl;
+import org.apache.cloudstack.framework.config.ConfigDepot;
+import org.apache.cloudstack.framework.jobs.dao.SyncQueueItemDaoImpl;
+import org.apache.cloudstack.framework.jobs.impl.SyncQueueManager;
+import org.apache.cloudstack.framework.jobs.dao.AsyncJobJournalDaoImpl;
+import org.apache.cloudstack.framework.jobs.dao.AsyncJobJoinMapDaoImpl;
+import org.apache.cloudstack.framework.jobs.AsyncJobDispatcher;
+import org.apache.cloudstack.framework.jobs.impl.AsyncJobMonitor;
+import org.apache.cloudstack.framework.config.ConfigDepotAdmin;
+import org.apache.cloudstack.network.lb.InternalLoadBalancerVMManager;
+import org.apache.cloudstack.network.lb.InternalLoadBalancerVMService;
+import org.apache.cloudstack.network.lb.ApplicationLoadBalancerService;
+import com.cloud.utils.db.EntityManager;
+import org.apache.cloudstack.context.CallContext;
+
+
+@ComponentScan(basePackageClasses={
+        AccountDaoImpl.class,
+        AccountDetailsDaoImpl.class,
+        AccountGuestVlanMapDaoImpl.class,
+        AccountJoinDaoImpl.class,
+        AccountVlanMapDaoImpl.class,
+        AffinityGroupDaoImpl.class,
+        AffinityGroupDomainMapDaoImpl.class,
+        AffinityGroupJoinDaoImpl.class,
+        AffinityGroupVMMapDaoImpl.class,
+        ApiDBUtils.class,
+        ApplicationLoadBalancerRuleDaoImpl.class,
+        AsyncJobDaoImpl.class,
+        AsyncJobJoinDaoImpl.class,
+        AsyncJobJoinMapDaoImpl.class,
+        AsyncJobJournalDaoImpl.class,
+        AsyncJobManagerImpl.class,
+        AutoScalePolicyConditionMapDaoImpl.class,
+        AutoScalePolicyDaoImpl.class,
+        AutoScaleVmGroupDaoImpl.class,
+        AutoScaleVmGroupPolicyMapDaoImpl.class,
+        AutoScaleVmProfileDaoImpl.class,
+        CapacityDaoImpl.class,
+        ClusterDaoImpl.class,
+        ClusterDetailsDaoImpl.class,
+        ConditionDaoImpl.class,
+        ConfigurationDaoImpl.class,
+        ConfigurationManagerImpl.class,
+        ConfigurationServerImpl.class,
+        ConsoleProxyDaoImpl.class,
+        ContrailElementImpl.class,
+        ContrailGuru.class,
+        ContrailManagerImpl.class,
+        CounterDaoImpl.class,
+        DataCenterDaoImpl.class,
+        DataCenterIpAddressDaoImpl.class,
+        DataCenterJoinDaoImpl.class,
+        DataCenterLinkLocalIpAddressDaoImpl.class,
+        DataCenterVnetDaoImpl.class,
+        DcDetailsDaoImpl.class,
+        DedicatedResourceDaoImpl.class,
+        DiskOfferingDaoImpl.class,
+        DiskOfferingJoinDaoImpl.class,
+        DomainDaoImpl.class,
+        DomainManagerImpl.class,
+        DomainRouterDaoImpl.class,
+        DomainRouterJoinDaoImpl.class,
+        EventDaoImpl.class,
+        EventJoinDaoImpl.class,
+        EventUtils.class,
+        EventUtils.class,
+        FirewallManagerImpl.class,
+        FirewallRulesCidrsDaoImpl.class,
+        FirewallRulesDaoImpl.class,
+        GuestOSCategoryDaoImpl.class,
+        GuestOSDaoImpl.class,
+        HostDaoImpl.class,
+        HostDetailsDaoImpl.class,
+        HostJoinDaoImpl.class,
+        HostPodDaoImpl.class,
+        HostTagsDaoImpl.class,
+        HostTransferMapDaoImpl.class,
+        HypervisorCapabilitiesDaoImpl.class,
+        HypervisorGuruManagerImpl.class,
+        IdentityDaoImpl.class,
+        ImageStoreDaoImpl.class,
+        ImageStoreJoinDaoImpl.class,
+        InstanceGroupDaoImpl.class,
+        InstanceGroupJoinDaoImpl.class,
+        InstanceGroupVMMapDaoImpl.class,
+        IpAddressManagerImpl.class,
+        Ipv6AddressManagerImpl.class,
+        ItWorkDaoImpl.class,
+        LBHealthCheckPolicyDaoImpl.class,
+        LBStickinessPolicyDaoImpl.class,
+        LaunchPermissionDao.class,
+        LoadBalancerDaoImpl.class,
+        LoadBalancerVMMapDaoImpl.class,
+        LoadBalancingRulesManagerImpl.class,
+        ManagementServerHostDaoImpl.class,
+        MockAccountManager.class,
+        NetworkACLDaoImpl.class,
+        NetworkACLItemDaoImpl.class,
+        NetworkACLManagerImpl.class,
+        NetworkAccountDaoImpl.class,
+        NetworkDaoImpl.class,
+        NetworkDomainDaoImpl.class,
+        NetworkModelImpl.class,
+        NetworkOfferingDaoImpl.class,
+        NetworkOfferingDetailsDaoImpl.class,
+        NetworkOfferingServiceMapDaoImpl.class,
+        NetworkOpDaoImpl.class,
+        NetworkRuleConfigDaoImpl.class,
+        NetworkServiceImpl.class,
+        NetworkServiceMapDaoImpl.class,
+        NicIpAliasDaoImpl.class,
+        NicSecondaryIpDaoImpl.class,
+        PhysicalNetworkDaoImpl.class,
+        PhysicalNetworkServiceProviderDaoImpl.class,
+        PhysicalNetworkTrafficTypeDaoImpl.class,
+        PlannerHostReservationDaoImpl.class,
+        PodVlanDaoImpl.class,
+        PodVlanMapDaoImpl.class,
+        PortForwardingRulesDaoImpl.class,
+        PortableIpDaoImpl.class,
+        PortableIpRangeDaoImpl.class,
+        PrimaryDataStoreDaoImpl.class,
+        PrivateIpDaoImpl.class,
+        ProjectAccountDaoImpl.class,
+        ProjectAccountJoinDaoImpl.class,
+        ProjectInvitationDaoImpl.class,
+        ProjectDaoImpl.class,
+        ProjectInvitationJoinDaoImpl.class,
+        ProjectJoinDaoImpl.class,
+        ProjectManagerImpl.class,
+        RegionDaoImpl.class,
+        RemoteAccessVpnDaoImpl.class,
+        ResourceCountDaoImpl.class,
+        ResourceLimitDaoImpl.class,
+        ResourceTagDao.class,
+        ResourceTagJoinDaoImpl.class,
+        ResourceTagsDaoImpl.class,
+        RouterNetworkDaoImpl.class,
+        RulesManagerImpl.class,
+        SSHKeyPairDaoImpl.class,
+        SecondaryStorageVmDaoImpl.class,
+        SecurityGroupDaoImpl.class,
+        SecurityGroupJoinDaoImpl.class,
+        SecurityGroupRuleDaoImpl.class,
+        SecurityGroupRulesDaoImpl.class,
+        SecurityGroupVMMapDaoImpl.class,
+        SecurityGroupWorkDaoImpl.class,
+        ServerEventHandlerImpl.class,
+        ServiceOfferingDaoImpl.class,
+        ServiceOfferingDetailsDaoImpl.class,
+        ServiceOfferingJoinDaoImpl.class,
+        Site2SiteCustomerGatewayDaoImpl.class,
+        Site2SiteVpnConnectionDaoImpl.class,
+        Site2SiteVpnGatewayDaoImpl.class,
+        SnapshotDaoImpl.class,
+        SnapshotPolicyDaoImpl.class,
+        StaticRouteDaoImpl.class,
+        StatsCollector.class,
+        StoragePoolDetailsDaoImpl.class,
+        StoragePoolHostDaoImpl.class,
+        StoragePoolJoinDaoImpl.class,
+        SyncQueueItemDaoImpl.class,
+        TemplateDataStoreDaoImpl.class,
+        TemplateJoinDaoImpl.class,
+        UploadDaoImpl.class,
+        UsageEventDaoImpl.class,
+        UserAccountJoinDaoImpl.class,
+        UserDaoImpl.class,
+        UserIpv6AddressDaoImpl.class,
+        UserStatisticsDaoImpl.class,
+        UserStatsLogDaoImpl.class,
+        UserVmCloneSettingDaoImpl.class,
+        UserVmDaoImpl.class,
+        UserVmDetailsDaoImpl.class,
+        UserVmJoinDaoImpl.class,
+        VMInstanceDaoImpl.class,
+        VMSnapshotDaoImpl.class,
+        VMTemplateDaoImpl.class,
+        VMTemplateDetailsDaoImpl.class,
+        VMTemplateHostDaoImpl.class,
+        VMTemplateZoneDaoImpl.class,
+        VirtualRouterProviderDaoImpl.class,
+        VlanDaoImpl.class,
+        VmDiskStatisticsDaoImpl.class,
+        VmRulesetLogDaoImpl.class,
+        VolumeDaoImpl.class,
+        VolumeHostDaoImpl.class,
+        VolumeJoinDaoImpl.class,
+        VpcDaoImpl.class,
+        VpcGatewayDaoImpl.class,
+        VpcManagerImpl.class,
+        VpcOfferingDaoImpl.class,
+        VpcOfferingServiceMapDaoImpl.class,
+        VpcServiceMapDaoImpl.class,
+        VpcVirtualNetworkApplianceManagerImpl.class,
+        VpnUserDaoImpl.class,
+},
+includeFilters={@Filter(value=TestConfiguration.ComponentFilter.class, type=FilterType.CUSTOM)},
+useDefaultFilters=false)
+
+@Configuration
+public class TestConfiguration {
+    public static class ComponentFilter implements TypeFilter {
+        @Override
+        public boolean match(MetadataReader mdr, MetadataReaderFactory arg1) throws IOException {
+            String clsname = mdr.getClassMetadata().getClassName();
+            ComponentScan cs = TestConfiguration.class.getAnnotation(ComponentScan.class);
+            return includedInBasePackageClasses(clsname, cs);
+        }
+    }
+    
+    public static boolean includedInBasePackageClasses(String clazzName, ComponentScan cs) {
+        Class<?> clazzToCheck;
+        try {
+            clazzToCheck = Class.forName(clazzName);
+        } catch (ClassNotFoundException e) {
+            System.out.println("Unable to find " + clazzName);
+            return false;
+        }
+        Class<?>[] clazzes = cs.basePackageClasses();
+        for (Class<?> clazz : clazzes) {
+            if (clazzToCheck.isAssignableFrom(clazz)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    @Inject
+    AffinityGroupDao _affinityGroupDao;
+    @Inject AccountDao _accountDao;
+    @Inject UserDao _userDao;
+    @Inject NetworkOfferingDao _networkOfferingDao;
+    @Inject DataCenterDao _zoneDao;
+    @Inject IPAddressDao _ipAddressDao;
+
+
+    @Bean
+    public AffinityGroupService affinityGroupService() {
+        AffinityGroupService mock = Mockito.mock(AffinityGroupService.class);
+        try {
+            AffinityGroupVO gmock = new AffinityGroupVO("grp1", "grp-type", "affinity group", 1, AccountVO.ACCOUNT_ID_SYSTEM, ControlledEntity.ACLType.Account); 
+            Transaction.open(Transaction.CLOUD_DB);
+            Transaction txn = Transaction.currentTxn();
+            txn.start();
+            _affinityGroupDao.persist(gmock);
+            txn.commit();
+
+            Mockito.when(mock.createAffinityGroupInternal(Mockito.any(String.class), Mockito.any(Long.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class))).thenReturn(gmock);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return mock;
+    }
+
+    @Bean
+    public AgentManager agentManager() {
+        return Mockito.mock(AgentManager.class);
+    }
+
+    @Bean
+    public AlertManager alertManager() {
+        return Mockito.mock(AlertManager.class);
+    }
+
+    @Bean
+    public APIChecker apiChecker() {
+        return Mockito.mock(APIChecker.class);
+    }
+
+    @Bean
+    public AsyncJobDispatcher asyncJobDispatcher() {
+        return Mockito.mock(AsyncJobDispatcher.class);
+    }
+    @Bean
+    public AsyncJobMonitor asyncJobMonitor() {
+        return Mockito.mock(AsyncJobMonitor.class);
+    }
+
+    @Bean
+    public AutoScaleService autoScaleService() {
+        return Mockito.mock(AutoScaleService.class);
+    }
+    @Bean
+    public CapacityManager capacityManager() {
+        return Mockito.mock(CapacityManager.class);
+    }
+    @Bean
+    public ClusterManager clusterManager() {
+        return Mockito.mock(ClusterManager.class);
+    }
+    @Bean
+    public ConfigDepot configDepot() {
+        return Mockito.mock(ConfigDepot.class);
+    }
+    @Bean
+    public ConfigDepotAdmin configDepotAdmin() {
+        return Mockito.mock(ConfigDepotAdmin.class);
+    }
+    @Bean
+    public ConsoleProxyManager consoleProxyManager() {
+        return Mockito.mock(ConsoleProxyManager.class);
+    }
+    @Bean
+    public ConsoleProxyService consoleProxyService() {
+        return Mockito.mock(ConsoleProxyService.class);
+    }
+    @Bean
+    public DataStoreManager dataStoreManager() {
+        return Mockito.mock(DataStoreManager.class);
+    }
+    @Bean
+    public DataStoreProviderApiService dataStoreProviderApiService() {
+        return Mockito.mock(DataStoreProviderApiService.class);
+    }
+    @Bean
+    public DeploymentPlanner deploymentPlanner() {
+        return Mockito.mock(DeploymentPlanner.class);
+    }
+    @Bean
+    public DeploymentPlanningManager deploymentPlanningManager() {
+        return Mockito.mock(DeploymentPlanningManager.class);
+    }
+    @Bean
+    public DomainChecker domainChecker() {
+        DomainChecker mock = Mockito.mock(DomainChecker.class);
+        try {
+            Mockito.when(mock.checkAccess(Mockito.any(Account.class), Mockito.any(DataCenter.class))).thenReturn(true);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return mock;
+    }
+    @Bean
+    public EndPointSelector endPointSelector() {
+        return Mockito.mock(EndPointSelector.class);
+    }
+    @Bean
+    public EntityManager entityManager() {
+        EntityManager mock = Mockito.mock(EntityManager.class);
+        try {
+            Mockito.when(mock.findById(Mockito.same(Account.class), Mockito.anyLong())).thenReturn(_accountDao.findById(AccountVO.ACCOUNT_ID_SYSTEM));
+            Mockito.when(mock.findById(Mockito.same(User.class), Mockito.anyLong())).thenReturn(_userDao.findById(UserVO.UID_SYSTEM));
+            Mockito.when(mock.findById(Mockito.same(NetworkOffering.class), Mockito.any(Long.class))).thenAnswer(
+                new Answer<NetworkOffering>()
+                {
+                     @Override
+                     public NetworkOffering answer(final InvocationOnMock invocation) throws Throwable
+                     {
+                          Long id = (Long) invocation.getArguments()[1];
+                          return _networkOfferingDao.findById(id);
+                     }
+                }
+             );
+            Mockito.when(mock.findById(Mockito.same(IpAddress.class), Mockito.any(Long.class))).thenAnswer(
+                new Answer<IpAddress>()
+                {
+                     @Override
+                     public IpAddress answer(final InvocationOnMock invocation) throws Throwable
+                     {
+                          Long id = (Long) invocation.getArguments()[1];
+                          return _ipAddressDao.findById(id);
+                     }
+                }
+             );
+            Mockito.when(mock.findById(Mockito.same(DataCenter.class), Mockito.any(Long.class))).thenAnswer(
+                new Answer<DataCenter>()
+                {
+                     @Override
+                     public DataCenter answer(final InvocationOnMock invocation) throws Throwable
+                     {
+                          Long id = (Long) invocation.getArguments()[1];
+                          return _zoneDao.findById(id);
+                     }
+                }
+             );
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        CallContext.init(mock);
+        return mock;
+    }
+    @Bean
+    public ExternalDeviceUsageManager externalDeviceUsageManager() {
+        return Mockito.mock(ExternalDeviceUsageManager.class);
+    }
+    @Bean
+    public GlobalLoadBalancingRulesService globalLoadBalancingRulesService() {
+        return Mockito.mock(GlobalLoadBalancingRulesService.class);
+    }
+    @Bean
+    public HighAvailabilityManager highAvailabilityManager()  {
+        return Mockito.mock(HighAvailabilityManager.class);
+    }
+    @Bean
+    public HostAllocator hostAllocator() {
+        return Mockito.mock(HostAllocator.class);
+    }
+    @Bean
+    public IdentityService identityService() {
+        return Mockito.mock(IdentityService.class);
+    }
+    @Bean
+    public InternalLoadBalancerVMManager internalLoadBalancerVMManager() {
+        return Mockito.mock(InternalLoadBalancerVMManager.class);
+    }
+    @Bean
+    public InternalLoadBalancerVMService internalLoadBalancerVMService() {
+        return Mockito.mock(InternalLoadBalancerVMService.class);
+    }
+    @Bean
+    public ApplicationLoadBalancerService applicationLoadBalancerService() {
+        return Mockito.mock(ApplicationLoadBalancerService.class);
+    }
+    @Bean
+    public ManagementServer managementServer() {
+        return Mockito.mock(ManagementServer.class);
+    }
+    @Bean
+    public NetworkACLService networkACLService() {
+        return Mockito.mock(NetworkACLService.class);
+    }
+    @Bean
+    public NetworkUsageService networkUsageService() {
+        return Mockito.mock(NetworkUsageService.class);
+    }
+    @Bean
+    public OrchestrationService orchSrvc() {
+        return Mockito.mock(OrchestrationService.class);
+    }
+    @Bean
+    public PodAllocator podAllocator() {
+        return Mockito.mock(PodAllocator.class);
+    }
+    @Bean
+    public QueryService queryService() {
+        return Mockito.mock(QueryService.class);
+    }
+    @Bean
+    public RegionManager regionManager() {
+        return Mockito.mock(RegionManager.class);
+    }
+    @Bean
+    public RemoteAccessVpnService remoteAccessVpnService() {
+        return Mockito.mock(RemoteAccessVpnService.class);
+    }
+    @Bean
+    public ResourceLimitService resourceLimitService() {
+        return Mockito.mock(ResourceLimitService.class);
+    }
+    @Bean
+    public ResourceManager resourceManager() {
+        return Mockito.mock(ResourceManager.class);
+    }
+    @Bean
+    public ResourceMetaDataService resourceMetaDataService() {
+        return Mockito.mock(ResourceMetaDataService.class);
+    }
+    @Bean
+    public SecondaryStorageVmManager secondaryStorageVmManager() {
+        return Mockito.mock(SecondaryStorageVmManager.class);
+    }
+    @Bean
+    public Site2SiteVpnManager  site2SiteVpnManager() {
+        return Mockito.mock(Site2SiteVpnManager.class);
+    }
+    @Bean
+    public Site2SiteVpnServiceProvider site2SiteVpnServiceProvider() {
+        return Mockito.mock(Site2SiteVpnServiceProvider.class);
+    }
+    @Bean
+    public SnapshotApiService snapshotApiService() {
+        return Mockito.mock(SnapshotApiService.class);
+    }
+    @Bean
+    public SnapshotManager snapshotManager() {
+        return Mockito.mock(SnapshotManager.class);
+    }
+    @Bean
+    public StorageManager storageManager() {
+        return Mockito.mock(StorageManager.class);
+    }
+    @Bean
+    public StorageNetworkManager storageNetworkManager() {
+        return Mockito.mock(StorageNetworkManager.class);
+    }
+    @Bean
+    public StorageNetworkService storageNetworkService() {
+        return Mockito.mock(StorageNetworkService.class);
+    }
+    @Bean
+    public StoragePoolAllocator storagePoolAllocator() {
+        return Mockito.mock(StoragePoolAllocator.class);
+    }
+    @Bean
+    public SyncQueueManager syncQueueManager() {
+        return Mockito.mock(SyncQueueManager.class);
+    }
+    @Bean
+    public TaggedResourceService taggedResourceService() {
+        return Mockito.mock(TaggedResourceService.class);
+    }
+    @Bean
+    public TemplateDataFactory templateDataFactory() {
+        return Mockito.mock(TemplateDataFactory.class);
+    }
+    @Bean
+    public TemplateApiService templateApiService() {
+        return Mockito.mock(TemplateApiService.class);
+    }
+    @Bean
+    public TemplateManager templateManager() {
+        return Mockito.mock(TemplateManager.class);
+    }
+    @Bean
+    public TemplateService templateService() {
+        return Mockito.mock(TemplateService.class);
+    }
+    @Bean
+    public UsageService usageService() {
+        return Mockito.mock(UsageService.class);
+    }
+    @Bean
+    public UserAuthenticator userAuthenticator() {
+        return Mockito.mock(UserAuthenticator.class);
+    }
+    @Bean
+    public VMSnapshotManager vMSnapshotManager() {
+        return Mockito.mock(VMSnapshotManager.class);
+    }
+    @Bean
+    public VolumeApiService volumeApiService() {
+        return Mockito.mock(VolumeApiService.class);
+    }
+    @Bean
+    public VolumeDataFactory volumeDataFactory() {
+        return Mockito.mock(VolumeDataFactory.class);
+    }
+    @Bean 
+    public VolumeOrchestrationService volumeOrchestrationService() {
+        return Mockito.mock(VolumeOrchestrationService.class);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7099686b/plugins/network-elements/juniper-contrail/test/net/juniper/contrail/management/TestDbSetup.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/juniper-contrail/test/net/juniper/contrail/management/TestDbSetup.java b/plugins/network-elements/juniper-contrail/test/net/juniper/contrail/management/TestDbSetup.java
new file mode 100644
index 0000000..8d48163
--- /dev/null
+++ b/plugins/network-elements/juniper-contrail/test/net/juniper/contrail/management/TestDbSetup.java
@@ -0,0 +1,141 @@
+package net.juniper.contrail.management;
+
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.io.IOException;
+import java.io.File;
+import java.io.*;
+import java.util.Properties;
+import org.apache.commons.configuration.PropertiesConfiguration;
+import java.nio.file.Paths;
+
+import org.apache.log4j.Logger;
+
+public class TestDbSetup {
+
+    public static int findFreePort() throws Exception {
+
+       int port;
+       ServerSocket socket= new ServerSocket(0);
+       port = socket.getLocalPort();
+       socket.close();
+
+       return port;
+    }
+
+    public static void startMysqlServer(int port, String startMysqlScript) throws Exception {
+
+       try {
+
+            String cwd = Paths.get(".").toAbsolutePath().toString();
+            Runtime r = Runtime.getRuntime();
+            String script = startMysqlScript;
+            if (script == null) {
+                script = "test/resources/mysql_db_start.sh "  + port; 
+            }
+            Process mysql_server_process = r.exec("sh " + cwd + "/" + script);
+            System.out.println("new sql server instance launched on port: " + port);
+            /* sleep 5 seconds for server to get started */
+            Thread.sleep(5000);
+       } catch (Exception e) {
+
+            String cause = e.getMessage();
+            if (cause.equals("sh: not found"))
+                System.out.println("No sh interpreter found.");
+            throw e;
+       }
+    }
+
+    public static void stopMysqlServer(int port, String stopMysqlScript) throws Exception {
+
+       try {
+            Runtime r = Runtime.getRuntime();
+            String script = stopMysqlScript;
+            if (script == null) {
+                script = "test/resources/mysql_db_stop.sh "  + port; 
+            }
+            Process mysql_server_process = r.exec("sh " + script);
+            System.out.println("sql server instance running at port " + port + " stopped");
+            /* sleep 3 seconds for server to get started */
+            Thread.sleep(3000);
+       } catch (Exception e) {
+
+            String cause = e.getMessage();
+            if (cause.equals("sh: not found"))
+                System.out.println("No sh interpreter found.");
+            throw e;
+       }
+    }
+
+    /* this is required for deploying db with new set of sql server parameters */
+    public static void copyDbPropertiesFile() throws Exception {
+       Runtime.getRuntime().exec("cp ../../../utils/conf/db.properties ../../../utils/conf/db.properties.override");
+    }
+
+    public static void updateSqlPort(int port, String propertyFileOverride) throws Exception {
+
+       PropertiesConfiguration config = new PropertiesConfiguration(propertyFileOverride);
+       System.out.println("File: " + propertyFileOverride + "; old: db.properties port: " + 
+                            config.getProperty("db.cloud.port") + ", new port: " + port);
+       config.setProperty("db.cloud.port", "" + port);
+       config.setProperty("db.cloud.username", System.getProperty("user.name"));
+       config.setProperty("db.cloud.password", "");
+
+       config.setProperty("db.usage.port", "" + port);
+       config.setProperty("db.usage.username", System.getProperty("user.name"));
+       config.setProperty("db.usage.password", "");
+
+       config.setProperty("db.awsapi.port", "" + port);
+       config.setProperty("db.awsapi.username", System.getProperty("user.name"));
+       config.setProperty("db.awsapi.password", "");
+
+       config.setProperty("db.simulator.port", "" + port);
+       config.setProperty("db.simulator.username", System.getProperty("user.name"));
+       config.setProperty("db.simulator.password", "");
+
+       config.save();
+    }
+    
+    public static void initCloudstackDb() throws Exception {
+       try {
+            File dir = new File("../../../");
+            Runtime r = Runtime.getRuntime();
+            Process mysql_server_process = r.exec("mvn -P developer -pl developer -Ddeploydb ", null, dir);
+            dumpProcessOutput(mysql_server_process);
+            /* sleep 3 seconds for server to get started */
+            Thread.sleep(3000);
+       } catch (Exception e) {
+            String cause = e.getMessage();
+            System.out.println("e: " + cause);
+            throw e;
+       }
+
+    }
+
+
+    public static void dumpProcessOutput(Process p) throws Exception {
+
+       BufferedReader istream = null;
+       istream = new BufferedReader(new InputStreamReader(p.getInputStream()));
+       String line = null;
+       while ((line = istream.readLine()) != null) {
+            System.out.println(line);
+       }
+    }
+
+    public static int init(String startScript) throws Exception {
+        int port = TestDbSetup.findFreePort();
+        TestDbSetup.startMysqlServer(port, startScript);
+        copyDbPropertiesFile();  
+        /* both of these files needs to have mysql port, username password details */
+        TestDbSetup.updateSqlPort(port, "db.properties");  /* for cloudstack runtime */
+        TestDbSetup.updateSqlPort(port, "../../../utils/conf/db.properties.override"); /* for deploying db */
+        TestDbSetup.initCloudstackDb();
+        return port;
+    } 
+
+    public static void destroy(int port, String stopScript) throws Exception {
+        TestDbSetup.stopMysqlServer(port, stopScript);
+    } 
+}
+

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7099686b/plugins/network-elements/juniper-contrail/test/net/juniper/contrail/management/VirtualNetworkModelTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/juniper-contrail/test/net/juniper/contrail/management/VirtualNetworkModelTest.java b/plugins/network-elements/juniper-contrail/test/net/juniper/contrail/management/VirtualNetworkModelTest.java
new file mode 100644
index 0000000..dccd0ff
--- /dev/null
+++ b/plugins/network-elements/juniper-contrail/test/net/juniper/contrail/management/VirtualNetworkModelTest.java
@@ -0,0 +1,44 @@
+package net.juniper.contrail.management;
+
+import java.util.UUID;
+
+import net.juniper.contrail.model.VirtualNetworkModel;
+
+import org.apache.log4j.Logger;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import com.cloud.network.Networks.TrafficType;
+import com.cloud.network.dao.NetworkVO;
+
+import junit.framework.TestCase;
+
+public class VirtualNetworkModelTest extends TestCase {
+    private static final Logger s_logger =
+            Logger.getLogger(VirtualNetworkModelTest.class);
+
+    @Test
+    public void testDBLookup() {
+        ModelDatabase db = new ModelDatabase();
+        NetworkVO network = Mockito.mock(NetworkVO.class);
+        VirtualNetworkModel storageModel = new VirtualNetworkModel(network, null, ContrailManager.managementNetworkName,
+                TrafficType.Storage);
+        db.getVirtualNetworks().add(storageModel);
+        VirtualNetworkModel mgmtModel = new VirtualNetworkModel(network, null, ContrailManager.managementNetworkName,
+                TrafficType.Management);
+        db.getVirtualNetworks().add(mgmtModel);
+        VirtualNetworkModel guestModel1 = new VirtualNetworkModel(network, UUID.randomUUID().toString(), "test",
+                TrafficType.Guest);
+        db.getVirtualNetworks().add(guestModel1);
+        VirtualNetworkModel guestModel2 = new VirtualNetworkModel(network, UUID.randomUUID().toString(), "test",
+                TrafficType.Guest);
+        db.getVirtualNetworks().add(guestModel2);
+        s_logger.debug("networks: " + db.getVirtualNetworks().size());
+        assertEquals(4, db.getVirtualNetworks().size());
+        assertSame(storageModel, db.lookupVirtualNetwork(null, storageModel.getName(), TrafficType.Storage));
+        assertSame(mgmtModel, db.lookupVirtualNetwork(null, mgmtModel.getName(), TrafficType.Management));
+        assertSame(guestModel1, db.lookupVirtualNetwork(guestModel1.getUuid(), null, TrafficType.Guest));
+        assertSame(guestModel2, db.lookupVirtualNetwork(guestModel2.getUuid(), null, TrafficType.Guest));
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7099686b/plugins/network-elements/juniper-contrail/test/resources/contrail.properties
----------------------------------------------------------------------
diff --git a/plugins/network-elements/juniper-contrail/test/resources/contrail.properties b/plugins/network-elements/juniper-contrail/test/resources/contrail.properties
new file mode 100644
index 0000000..2769c9f
--- /dev/null
+++ b/plugins/network-elements/juniper-contrail/test/resources/contrail.properties
@@ -0,0 +1,2 @@
+api.hostname = 
+api.port = 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7099686b/plugins/network-elements/juniper-contrail/test/resources/db.properties
----------------------------------------------------------------------
diff --git a/plugins/network-elements/juniper-contrail/test/resources/db.properties b/plugins/network-elements/juniper-contrail/test/resources/db.properties
new file mode 100644
index 0000000..04a7175
--- /dev/null
+++ b/plugins/network-elements/juniper-contrail/test/resources/db.properties
@@ -0,0 +1,50 @@
+
+cluster.servlet.port=9090
+
+# CloudStack database settings
+db.cloud.username=cloud
+db.cloud.password=cloud
+db.root.password=
+db.cloud.host=localhost
+db.cloud.port=3306
+db.cloud.name=cloud
+
+# CloudStack database tuning parameters
+db.cloud.maxActive=250
+db.cloud.maxIdle=30
+db.cloud.maxWait=10000
+db.cloud.autoReconnect=true
+db.cloud.validationQuery=SELECT 1
+db.cloud.testOnBorrow=true
+db.cloud.testWhileIdle=true
+db.cloud.timeBetweenEvictionRunsMillis=40000
+db.cloud.minEvictableIdleTimeMillis=240000
+db.cloud.poolPreparedStatements=false
+db.cloud.url.params=prepStmtCacheSize=517&cachePrepStmts=true&prepStmtCacheSqlLimit=4096
+
+# usage database settings
+db.usage.username=cloud
+db.usage.password=cloud
+db.usage.host=localhost
+db.usage.port=3306
+db.usage.name=cloud_usage
+
+# usage database tuning parameters
+db.usage.maxActive=100
+db.usage.maxIdle=30
+db.usage.maxWait=10000
+db.usage.autoReconnect=true
+
+# awsapi database settings
+db.awsapi.name=cloudbridge
+
+# Simulator database settings
+db.simulator.username=cloud
+db.simulator.password=cloud
+db.simulator.host=localhost
+db.simulator.port=3306
+db.simulator.name=simulator
+db.simulator.maxActive=250
+db.simulator.maxIdle=30
+db.simulator.maxWait=10000
+db.simulator.autoReconnect=true

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7099686b/plugins/network-elements/juniper-contrail/test/resources/log4j.properties
----------------------------------------------------------------------
diff --git a/plugins/network-elements/juniper-contrail/test/resources/log4j.properties b/plugins/network-elements/juniper-contrail/test/resources/log4j.properties
new file mode 100644
index 0000000..a482e6f
--- /dev/null
+++ b/plugins/network-elements/juniper-contrail/test/resources/log4j.properties
@@ -0,0 +1,35 @@
+# 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.
+
+log4j.appender.stdout=org.apache.log4j.ConsoleAppender
+log4j.appender.stdout.Target=System.out
+log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
+log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
+log4j.appender.stdout.threshold=INFO
+log4j.rootLogger=INFO, stdout, rolling
+log4j.appender.rolling=org.apache.log4j.DailyRollingFileAppender
+log4j.appender.rolling.layout=org.apache.log4j.PatternLayout
+log4j.appender.rolling.layout.ConversionPattern=%d %-5p [%c{3}] (%t:%x) %m%n
+log4j.appender.rolling.file.threshold=DEBUG
+log4j.appender.rolling.File=./logs/testclient.log
+log4j.appender.rolling.DatePattern='.'yyy-MM-dd
+log4j.appender.rolling.file.append=false
+log4j.category.org.apache=INFO, rolling, stdout
+#log4j.category.com.cloud.utils.db.Transaction=ALL
+log4j.category.net.juniper.contrail=ALL
+log4j.category.com.cloud.network=ALL
+

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7099686b/plugins/network-elements/juniper-contrail/test/resources/mysql_db_start.sh
----------------------------------------------------------------------
diff --git a/plugins/network-elements/juniper-contrail/test/resources/mysql_db_start.sh b/plugins/network-elements/juniper-contrail/test/resources/mysql_db_start.sh
new file mode 100644
index 0000000..cf033a6
--- /dev/null
+++ b/plugins/network-elements/juniper-contrail/test/resources/mysql_db_start.sh
@@ -0,0 +1,23 @@
+if [ "$#" -ne 1 ] ; then
+   echo "Usage: $0 <port>" >&2
+   exit 1
+fi
+
+echo "starting mysql on port: "$1
+
+echo "creating temporary mysql db directories /tmp/mysql"$1 
+mkdir /tmp/mysql$1
+mkdir /tmp/mysql$1/data
+
+echo "install db";
+
+mysql_install_db --user=$USER --datadir=/tmp/mysql$1/data
+mysqld_safe --datadir=/tmp/mysql$1/data --socket=/tmp/mysql$1/mysqld.sock --port=$1 --log-error=/tmp/mysql$1/mysql.log --pid-file=/tmp/mysql$1/mysql.pid --user=$USER &
+
+echo "new mysql server is started on port "$1
+
+sleep 3
+
+echo "commands ...."
+echo "to connect(from local host): mysql -h 127.0.0.1 -P "$1 
+echo "to stop: mysqladmin -S /tmp/mysql"$1"/mysqld.sock shutdown -u root"

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7099686b/plugins/network-elements/juniper-contrail/test/resources/mysql_db_stop.sh
----------------------------------------------------------------------
diff --git a/plugins/network-elements/juniper-contrail/test/resources/mysql_db_stop.sh b/plugins/network-elements/juniper-contrail/test/resources/mysql_db_stop.sh
new file mode 100644
index 0000000..90aa07d
--- /dev/null
+++ b/plugins/network-elements/juniper-contrail/test/resources/mysql_db_stop.sh
@@ -0,0 +1,14 @@
+if [ "$#" -ne 1 ] ; then
+   echo "Usage: $0 <port>" >&2
+   exit 1
+fi
+
+echo "Stopping mysql server on port "$1
+
+mysqladmin -S /tmp/mysql$1/mysqld.sock shutdown -u root
+
+rm -rf /tmp/mysql$1
+
+echo "Deleting db directories"
+
+


Mime
View raw message