http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/utils/CommandRetryUtility.java ---------------------------------------------------------------------- diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/utils/CommandRetryUtility.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/utils/CommandRetryUtility.java new file mode 100644 index 0000000..92c198a --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/utils/CommandRetryUtility.java @@ -0,0 +1,89 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.network.utils; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.log4j.Logger; + +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.Command; +import com.cloud.resource.ServerResource; + +public class CommandRetryUtility { + + private static final Logger s_logger = Logger.getLogger(CommandRetryUtility.class); + + private static final int ZERO = 0; + private static CommandRetryUtility instance; + + static { + instance = new CommandRetryUtility(); + } + + private final ConcurrentHashMap<Command, Integer> commandsToRetry; + private ServerResource serverResource; + + private CommandRetryUtility() { + commandsToRetry = new ConcurrentHashMap<Command, Integer>(); + } + + public static CommandRetryUtility getInstance() { + return instance; + } + + public void setServerResource(final ServerResource serverResource) { + this.serverResource = serverResource; + } + + public boolean addRetry(final Command command, final int retries) { + if (commandsToRetry.containsKey(command)) { + // A retry already exists for this command, do not add it again. + // Once all retries are executed, the command will be removed from the map. + return false; + } + commandsToRetry.put(command, retries); + return true; + } + + public Answer retry(final Command command, final Class<? extends Answer> answerClass, final Exception error) { + if (commandsToRetry.containsKey(command)) { + Integer numRetries = commandsToRetry.get(command); + + if (numRetries > ZERO) { + commandsToRetry.put(command, --numRetries); + + s_logger.warn("Retrying " + command.getClass().getSimpleName() + ". Number of retries remaining: " + numRetries); + + return serverResource.executeRequest(command); + } else { + commandsToRetry.remove(command); + } + } + try { + final Constructor<? extends Answer> answerConstructor = answerClass.getConstructor(Command.class, Exception.class); + return answerConstructor.newInstance(command, error); + } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + return Answer.createUnsupportedCommandAnswer(command); + } + } +} \ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/resources/META-INF/cloudstack/nvp/module.properties ---------------------------------------------------------------------- diff --git a/plugins/network-elements/nicira-nvp/src/main/resources/META-INF/cloudstack/nvp/module.properties b/plugins/network-elements/nicira-nvp/src/main/resources/META-INF/cloudstack/nvp/module.properties new file mode 100644 index 0000000..5085fce --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/main/resources/META-INF/cloudstack/nvp/module.properties @@ -0,0 +1,21 @@ +# +# 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. +# + +name=nvp +parent=network \ No newline at end of file http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/resources/META-INF/cloudstack/nvp/spring-nvp-context.xml ---------------------------------------------------------------------- diff --git a/plugins/network-elements/nicira-nvp/src/main/resources/META-INF/cloudstack/nvp/spring-nvp-context.xml b/plugins/network-elements/nicira-nvp/src/main/resources/META-INF/cloudstack/nvp/spring-nvp-context.xml new file mode 100644 index 0000000..cd8a2c9 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/main/resources/META-INF/cloudstack/nvp/spring-nvp-context.xml @@ -0,0 +1,42 @@ +<!-- + + 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: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/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" + > + + <bean id="niciraNvpDaoImpl" class="com.cloud.network.dao.NiciraNvpDaoImpl" /> + <bean id="niciraNvpNicMappingDaoImpl" class="com.cloud.network.dao.NiciraNvpNicMappingDaoImpl" /> + <bean id="niciraNvpRouterMappingDaoImpl" class="com.cloud.network.dao.NiciraNvpRouterMappingDaoImpl" /> + <bean id="NiciraNvpGuestNetworkGuru" class="com.cloud.network.guru.NiciraNvpGuestNetworkGuru"> + <property name="name" value="NiciraNvpGuestNetworkGuru" /> + </bean> + <bean id="NiciraNvp" class="com.cloud.network.element.NiciraNvpElement"> + <property name="name" value="NiciraNvp" /> + </bean> + +</beans> http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/element/NiciraNvpElementTest.java ---------------------------------------------------------------------- diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/element/NiciraNvpElementTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/element/NiciraNvpElementTest.java new file mode 100644 index 0000000..bf8ce18 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/element/NiciraNvpElementTest.java @@ -0,0 +1,217 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.network.element; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.argThat; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.naming.ConfigurationException; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentMatcher; + +import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService; + +import com.cloud.agent.AgentManager; +import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterAnswer; +import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterCommand; +import com.cloud.deploy.DeployDestination; +import com.cloud.domain.Domain; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.host.HostVO; +import com.cloud.host.dao.HostDao; +import com.cloud.network.IpAddress; +import com.cloud.network.Network; +import com.cloud.network.Network.GuestType; +import com.cloud.network.Network.Provider; +import com.cloud.network.Network.Service; +import com.cloud.network.NetworkModel; +import com.cloud.network.Networks.BroadcastDomainType; +import com.cloud.network.Networks.TrafficType; +import com.cloud.network.NiciraNvpDeviceVO; +import com.cloud.network.NiciraNvpRouterMappingVO; +import com.cloud.network.PublicIpAddress; +import com.cloud.network.dao.NetworkServiceMapDao; +import com.cloud.network.dao.NiciraNvpDao; +import com.cloud.network.dao.NiciraNvpRouterMappingDao; +import com.cloud.offering.NetworkOffering; +import com.cloud.resource.ResourceManager; +import com.cloud.user.Account; +import com.cloud.utils.net.Ip; +import com.cloud.vm.ReservationContext; + +public class NiciraNvpElementTest { + + private static final long NETWORK_ID = 42L; + NiciraNvpElement element = new NiciraNvpElement(); + NetworkOrchestrationService networkManager = mock(NetworkOrchestrationService.class); + NetworkModel networkModel = mock(NetworkModel.class); + NetworkServiceMapDao ntwkSrvcDao = mock(NetworkServiceMapDao.class); + AgentManager agentManager = mock(AgentManager.class); + HostDao hostDao = mock(HostDao.class); + NiciraNvpDao niciraNvpDao = mock(NiciraNvpDao.class); + NiciraNvpRouterMappingDao niciraNvpRouterMappingDao = mock(NiciraNvpRouterMappingDao.class); + + @Before + public void setUp() throws ConfigurationException { + element.resourceMgr = mock(ResourceManager.class); + element.networkManager = networkManager; + element.ntwkSrvcDao = ntwkSrvcDao; + element.networkModel = networkModel; + element.agentMgr = agentManager; + element.hostDao = hostDao; + element.niciraNvpDao = niciraNvpDao; + element.niciraNvpRouterMappingDao = niciraNvpRouterMappingDao; + + // Standard responses + when(networkModel.isProviderForNetwork(Provider.NiciraNvp, NETWORK_ID)).thenReturn(true); + + element.configure("NiciraNvpTestElement", Collections.<String, Object> emptyMap()); + } + + @Test + public void canHandleTest() { + final Network net = mock(Network.class); + when(net.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch); + when(net.getId()).thenReturn(NETWORK_ID); + + when(ntwkSrvcDao.canProviderSupportServiceInNetwork(NETWORK_ID, Service.Connectivity, Provider.NiciraNvp)).thenReturn(true); + // Golden path + assertTrue(element.canHandle(net, Service.Connectivity)); + + when(net.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Vlan); + // Only broadcastdomaintype lswitch is supported + assertFalse(element.canHandle(net, Service.Connectivity)); + + when(net.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch); + when(ntwkSrvcDao.canProviderSupportServiceInNetwork(NETWORK_ID, Service.Connectivity, Provider.NiciraNvp)).thenReturn(false); + // No nvp provider in the network + assertFalse(element.canHandle(net, Service.Connectivity)); + + when(networkModel.isProviderForNetwork(Provider.NiciraNvp, NETWORK_ID)).thenReturn(false); + when(ntwkSrvcDao.canProviderSupportServiceInNetwork(NETWORK_ID, Service.Connectivity, Provider.NiciraNvp)).thenReturn(true); + // NVP provider does not provide Connectivity for this network + assertFalse(element.canHandle(net, Service.Connectivity)); + + when(networkModel.isProviderForNetwork(Provider.NiciraNvp, NETWORK_ID)).thenReturn(true); + // Only service Connectivity is supported + assertFalse(element.canHandle(net, Service.Dhcp)); + + } + + @Test + public void implementTest() throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { + final Network network = mock(Network.class); + when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch); + when(network.getId()).thenReturn(NETWORK_ID); + + final NetworkOffering offering = mock(NetworkOffering.class); + when(offering.getId()).thenReturn(NETWORK_ID); + when(offering.getTrafficType()).thenReturn(TrafficType.Guest); + when(offering.getGuestType()).thenReturn(GuestType.Isolated); + + mock(DeployDestination.class); + + final Domain dom = mock(Domain.class); + when(dom.getName()).thenReturn("domain"); + final Account acc = mock(Account.class); + when(acc.getAccountName()).thenReturn("accountname"); + final ReservationContext context = mock(ReservationContext.class); + when(context.getDomain()).thenReturn(dom); + when(context.getAccount()).thenReturn(acc); + } + + @Test + public void applyIpTest() throws ResourceUnavailableException { + final Network network = mock(Network.class); + when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch); + when(network.getId()).thenReturn(NETWORK_ID); + when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID); + + final NetworkOffering offering = mock(NetworkOffering.class); + when(offering.getId()).thenReturn(NETWORK_ID); + when(offering.getTrafficType()).thenReturn(TrafficType.Guest); + when(offering.getGuestType()).thenReturn(GuestType.Isolated); + + final List<PublicIpAddress> ipAddresses = new ArrayList<PublicIpAddress>(); + final PublicIpAddress pipReleased = mock(PublicIpAddress.class); + final PublicIpAddress pipAllocated = mock(PublicIpAddress.class); + final Ip ipReleased = new Ip("42.10.10.10"); + final Ip ipAllocated = new Ip("10.10.10.10"); + when(pipAllocated.getState()).thenReturn(IpAddress.State.Allocated); + when(pipAllocated.getAddress()).thenReturn(ipAllocated); + when(pipAllocated.getNetmask()).thenReturn("255.255.255.0"); + when(pipReleased.getState()).thenReturn(IpAddress.State.Releasing); + when(pipReleased.getAddress()).thenReturn(ipReleased); + when(pipReleased.getNetmask()).thenReturn("255.255.255.0"); + ipAddresses.add(pipAllocated); + ipAddresses.add(pipReleased); + + final Set<Service> services = new HashSet<Service>(); + services.add(Service.SourceNat); + services.add(Service.StaticNat); + services.add(Service.PortForwarding); + + final List<NiciraNvpDeviceVO> deviceList = new ArrayList<NiciraNvpDeviceVO>(); + final NiciraNvpDeviceVO nndVO = mock(NiciraNvpDeviceVO.class); + final NiciraNvpRouterMappingVO nnrmVO = mock(NiciraNvpRouterMappingVO.class); + when(niciraNvpRouterMappingDao.findByNetworkId(NETWORK_ID)).thenReturn(nnrmVO); + when(nnrmVO.getLogicalRouterUuid()).thenReturn("abcde"); + when(nndVO.getHostId()).thenReturn(NETWORK_ID); + final HostVO hvo = mock(HostVO.class); + when(hvo.getId()).thenReturn(NETWORK_ID); + when(hvo.getDetail("l3gatewayserviceuuid")).thenReturn("abcde"); + when(hostDao.findById(NETWORK_ID)).thenReturn(hvo); + deviceList.add(nndVO); + when(niciraNvpDao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(deviceList); + + final ConfigurePublicIpsOnLogicalRouterAnswer answer = mock(ConfigurePublicIpsOnLogicalRouterAnswer.class); + when(answer.getResult()).thenReturn(true); + when(agentManager.easySend(eq(NETWORK_ID), any(ConfigurePublicIpsOnLogicalRouterCommand.class))).thenReturn(answer); + + assertTrue(element.applyIps(network, ipAddresses, services)); + + verify(agentManager, atLeast(1)).easySend(eq(NETWORK_ID), argThat(new ArgumentMatcher<ConfigurePublicIpsOnLogicalRouterCommand>() { + @Override + public boolean matches(final Object argument) { + final ConfigurePublicIpsOnLogicalRouterCommand command = (ConfigurePublicIpsOnLogicalRouterCommand)argument; + if (command.getPublicCidrs().size() == 1) + return true; + return false; + } + })); + } +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/guru/NiciraNvpGuestNetworkGuruTest.java ---------------------------------------------------------------------- diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/guru/NiciraNvpGuestNetworkGuruTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/guru/NiciraNvpGuestNetworkGuruTest.java new file mode 100644 index 0000000..36e4643 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/guru/NiciraNvpGuestNetworkGuruTest.java @@ -0,0 +1,476 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.network.guru; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyLong; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Arrays; +import java.util.Collections; + +import org.junit.Before; +import org.junit.Test; + +import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService; + +import com.cloud.agent.AgentManager; +import com.cloud.agent.api.Command; +import com.cloud.agent.api.CreateLogicalSwitchAnswer; +import com.cloud.agent.api.DeleteLogicalSwitchAnswer; +import com.cloud.dc.DataCenter; +import com.cloud.dc.DataCenter.NetworkType; +import com.cloud.dc.DataCenterVO; +import com.cloud.dc.dao.DataCenterDao; +import com.cloud.deploy.DeployDestination; +import com.cloud.deploy.DeploymentPlan; +import com.cloud.domain.Domain; +import com.cloud.exception.InsufficientVirtualNetworkCapacityException; +import com.cloud.host.HostVO; +import com.cloud.host.dao.HostDao; +import com.cloud.network.Network; +import com.cloud.network.Network.GuestType; +import com.cloud.network.Network.Service; +import com.cloud.network.Network.State; +import com.cloud.network.NetworkModel; +import com.cloud.network.NetworkProfile; +import com.cloud.network.Networks.BroadcastDomainType; +import com.cloud.network.Networks.TrafficType; +import com.cloud.network.NiciraNvpDeviceVO; +import com.cloud.network.dao.NetworkDao; +import com.cloud.network.dao.NetworkVO; +import com.cloud.network.dao.NiciraNvpDao; +import com.cloud.network.dao.PhysicalNetworkDao; +import com.cloud.network.dao.PhysicalNetworkVO; +import com.cloud.offering.NetworkOffering; +import com.cloud.offerings.dao.NetworkOfferingServiceMapDao; +import com.cloud.user.Account; +import com.cloud.vm.ReservationContext; + +public class NiciraNvpGuestNetworkGuruTest { + private static final long NETWORK_ID = 42L; + PhysicalNetworkDao physnetdao = mock(PhysicalNetworkDao.class); + NiciraNvpDao nvpdao = mock(NiciraNvpDao.class); + DataCenterDao dcdao = mock(DataCenterDao.class); + NetworkOfferingServiceMapDao nosd = mock(NetworkOfferingServiceMapDao.class); + AgentManager agentmgr = mock(AgentManager.class); + NetworkOrchestrationService netmgr = mock(NetworkOrchestrationService.class); + NetworkModel netmodel = mock(NetworkModel.class); + + HostDao hostdao = mock(HostDao.class); + NetworkDao netdao = mock(NetworkDao.class); + NiciraNvpGuestNetworkGuru guru; + + @Before + public void setUp() { + guru = new NiciraNvpGuestNetworkGuru(); + ((GuestNetworkGuru)guru)._physicalNetworkDao = physnetdao; + guru.physicalNetworkDao = physnetdao; + guru.niciraNvpDao = nvpdao; + guru._dcDao = dcdao; + guru.ntwkOfferingSrvcDao = nosd; + guru.networkModel = netmodel; + guru.hostDao = hostdao; + guru.agentMgr = agentmgr; + guru.networkDao = netdao; + + final DataCenterVO dc = mock(DataCenterVO.class); + when(dc.getNetworkType()).thenReturn(NetworkType.Advanced); + when(dc.getGuestNetworkCidr()).thenReturn("10.1.1.1/24"); + + when(dcdao.findById((Long)any())).thenReturn(dc); + } + + @Test + public void testCanHandle() { + final NetworkOffering offering = mock(NetworkOffering.class); + when(offering.getId()).thenReturn(NETWORK_ID); + when(offering.getTrafficType()).thenReturn(TrafficType.Guest); + when(offering.getGuestType()).thenReturn(GuestType.Isolated); + + final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT", "VXLAN"})); + when(physnet.getId()).thenReturn(NETWORK_ID); + + when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(true); + + assertTrue(guru.canHandle(offering, NetworkType.Advanced, physnet) == true); + + // Supported: IsolationMethod == VXLAN + when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"VXLAN"})); + assertTrue(guru.canHandle(offering, NetworkType.Advanced, physnet) == true); + + // Not supported TrafficType != Guest + when(offering.getTrafficType()).thenReturn(TrafficType.Management); + assertFalse(guru.canHandle(offering, NetworkType.Advanced, physnet) == true); + + // Not supported: GuestType Shared + when(offering.getTrafficType()).thenReturn(TrafficType.Guest); + when(offering.getGuestType()).thenReturn(GuestType.Shared); + assertFalse(guru.canHandle(offering, NetworkType.Advanced, physnet) == true); + + // Not supported: Basic networking + when(offering.getGuestType()).thenReturn(GuestType.Isolated); + assertFalse(guru.canHandle(offering, NetworkType.Basic, physnet) == true); + + // Not supported: IsolationMethod != STT, VXLAN + when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"VLAN"})); + assertFalse(guru.canHandle(offering, NetworkType.Advanced, physnet) == true); + + } + + @Test + public void testDesign() { + final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + when(physnetdao.findById((Long)any())).thenReturn(physnet); + when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT", "VXLAN"})); + when(physnet.getId()).thenReturn(NETWORK_ID); + + final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); + when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device})); + when(device.getId()).thenReturn(1L); + + final NetworkOffering offering = mock(NetworkOffering.class); + when(offering.getId()).thenReturn(NETWORK_ID); + when(offering.getTrafficType()).thenReturn(TrafficType.Guest); + when(offering.getGuestType()).thenReturn(GuestType.Isolated); + + when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(true); + + final DeploymentPlan plan = mock(DeploymentPlan.class); + final Network network = mock(Network.class); + final Account account = mock(Account.class); + + final Network designednetwork = guru.design(offering, plan, network, account); + assertTrue(designednetwork != null); + assertTrue(designednetwork.getBroadcastDomainType() == BroadcastDomainType.Lswitch); + } + + @Test + public void testDesignNoElementOnPhysicalNetwork() { + final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + when(physnetdao.findById((Long)any())).thenReturn(physnet); + when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT", "VXLAN"})); + when(physnet.getId()).thenReturn(NETWORK_ID); + + mock(NiciraNvpDeviceVO.class); + when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Collections.<NiciraNvpDeviceVO> emptyList()); + + final NetworkOffering offering = mock(NetworkOffering.class); + when(offering.getId()).thenReturn(NETWORK_ID); + when(offering.getTrafficType()).thenReturn(TrafficType.Guest); + when(offering.getGuestType()).thenReturn(GuestType.Isolated); + + final DeploymentPlan plan = mock(DeploymentPlan.class); + final Network network = mock(Network.class); + final Account account = mock(Account.class); + + final Network designednetwork = guru.design(offering, plan, network, account); + assertTrue(designednetwork == null); + } + + @Test + public void testDesignNoIsolationMethodSTT() { + final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + when(physnetdao.findById((Long)any())).thenReturn(physnet); + when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"VLAN"})); + when(physnet.getId()).thenReturn(NETWORK_ID); + + mock(NiciraNvpDeviceVO.class); + when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Collections.<NiciraNvpDeviceVO> emptyList()); + + final NetworkOffering offering = mock(NetworkOffering.class); + when(offering.getId()).thenReturn(NETWORK_ID); + when(offering.getTrafficType()).thenReturn(TrafficType.Guest); + when(offering.getGuestType()).thenReturn(GuestType.Isolated); + + final DeploymentPlan plan = mock(DeploymentPlan.class); + final Network network = mock(Network.class); + final Account account = mock(Account.class); + + final Network designednetwork = guru.design(offering, plan, network, account); + assertTrue(designednetwork == null); + } + + @Test + public void testDesignNoConnectivityInOffering() { + final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + when(physnetdao.findById((Long)any())).thenReturn(physnet); + when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT", "VXLAN"})); + when(physnet.getId()).thenReturn(NETWORK_ID); + + final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); + when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device})); + when(device.getId()).thenReturn(1L); + + final NetworkOffering offering = mock(NetworkOffering.class); + when(offering.getId()).thenReturn(NETWORK_ID); + when(offering.getTrafficType()).thenReturn(TrafficType.Guest); + when(offering.getGuestType()).thenReturn(GuestType.Isolated); + + when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(false); + + final DeploymentPlan plan = mock(DeploymentPlan.class); + final Network network = mock(Network.class); + final Account account = mock(Account.class); + + final Network designednetwork = guru.design(offering, plan, network, account); + assertTrue(designednetwork == null); + } + + @Test + public void testImplement() throws InsufficientVirtualNetworkCapacityException { + final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + when(physnetdao.findById((Long)any())).thenReturn(physnet); + when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT", "VXLAN"})); + when(physnet.getId()).thenReturn(NETWORK_ID); + + final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); + when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device})); + when(device.getId()).thenReturn(1L); + + final NetworkOffering offering = mock(NetworkOffering.class); + when(offering.getId()).thenReturn(NETWORK_ID); + when(offering.getTrafficType()).thenReturn(TrafficType.Guest); + when(offering.getGuestType()).thenReturn(GuestType.Isolated); + + when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(false); + + mock(DeploymentPlan.class); + + final NetworkVO network = mock(NetworkVO.class); + when(network.getName()).thenReturn("testnetwork"); + when(network.getState()).thenReturn(State.Implementing); + when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID); + + final DeployDestination dest = mock(DeployDestination.class); + + final DataCenter dc = mock(DataCenter.class); + when(dest.getDataCenter()).thenReturn(dc); + + final HostVO niciraHost = mock(HostVO.class); + when(hostdao.findById(anyLong())).thenReturn(niciraHost); + when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa"); + when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt"); + when(niciraHost.getId()).thenReturn(NETWORK_ID); + + when(netmodel.findPhysicalNetworkId(anyLong(), (String)any(), (TrafficType)any())).thenReturn(NETWORK_ID); + final Domain dom = mock(Domain.class); + when(dom.getName()).thenReturn("domain"); + final Account acc = mock(Account.class); + when(acc.getAccountName()).thenReturn("accountname"); + final ReservationContext res = mock(ReservationContext.class); + when(res.getDomain()).thenReturn(dom); + when(res.getAccount()).thenReturn(acc); + + final CreateLogicalSwitchAnswer answer = mock(CreateLogicalSwitchAnswer.class); + when(answer.getResult()).thenReturn(true); + when(answer.getLogicalSwitchUuid()).thenReturn("aaaaa"); + when(agentmgr.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer); + + final Network implementednetwork = guru.implement(network, offering, dest, res); + assertTrue(implementednetwork != null); + verify(agentmgr, times(1)).easySend(eq(NETWORK_ID), (Command)any()); + } + + @Test + public void testImplementWithCidr() throws InsufficientVirtualNetworkCapacityException { + final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + when(physnetdao.findById((Long)any())).thenReturn(physnet); + when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT"})); + when(physnet.getId()).thenReturn(NETWORK_ID); + + final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); + when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device})); + when(device.getId()).thenReturn(1L); + + final NetworkOffering offering = mock(NetworkOffering.class); + when(offering.getId()).thenReturn(NETWORK_ID); + when(offering.getTrafficType()).thenReturn(TrafficType.Guest); + when(offering.getGuestType()).thenReturn(GuestType.Isolated); + + when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(false); + + mock(DeploymentPlan.class); + + final NetworkVO network = mock(NetworkVO.class); + when(network.getName()).thenReturn("testnetwork"); + when(network.getState()).thenReturn(State.Implementing); + when(network.getGateway()).thenReturn("10.1.1.1"); + when(network.getCidr()).thenReturn("10.1.1.0/24"); + when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID); + + final DeployDestination dest = mock(DeployDestination.class); + + final DataCenter dc = mock(DataCenter.class); + when(dest.getDataCenter()).thenReturn(dc); + + final HostVO niciraHost = mock(HostVO.class); + when(hostdao.findById(anyLong())).thenReturn(niciraHost); + when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa"); + when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt"); + when(niciraHost.getId()).thenReturn(NETWORK_ID); + + when(netmodel.findPhysicalNetworkId(anyLong(), (String)any(), (TrafficType)any())).thenReturn(NETWORK_ID); + final Domain dom = mock(Domain.class); + when(dom.getName()).thenReturn("domain"); + final Account acc = mock(Account.class); + when(acc.getAccountName()).thenReturn("accountname"); + final ReservationContext res = mock(ReservationContext.class); + when(res.getDomain()).thenReturn(dom); + when(res.getAccount()).thenReturn(acc); + + final CreateLogicalSwitchAnswer answer = mock(CreateLogicalSwitchAnswer.class); + when(answer.getResult()).thenReturn(true); + when(answer.getLogicalSwitchUuid()).thenReturn("aaaaa"); + when(agentmgr.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer); + + final Network implementednetwork = guru.implement(network, offering, dest, res); + assertTrue(implementednetwork != null); + assertTrue(implementednetwork.getCidr().equals("10.1.1.0/24")); + assertTrue(implementednetwork.getGateway().equals("10.1.1.1")); + verify(agentmgr, times(1)).easySend(eq(NETWORK_ID), (Command)any()); + } + + @Test + public void testImplementURIException() throws InsufficientVirtualNetworkCapacityException { + final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + when(physnetdao.findById((Long)any())).thenReturn(physnet); + when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT"})); + when(physnet.getId()).thenReturn(NETWORK_ID); + + final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); + when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device})); + when(device.getId()).thenReturn(1L); + + final NetworkOffering offering = mock(NetworkOffering.class); + when(offering.getId()).thenReturn(NETWORK_ID); + when(offering.getTrafficType()).thenReturn(TrafficType.Guest); + when(offering.getGuestType()).thenReturn(GuestType.Isolated); + + when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(false); + + mock(DeploymentPlan.class); + + final NetworkVO network = mock(NetworkVO.class); + when(network.getName()).thenReturn("testnetwork"); + when(network.getState()).thenReturn(State.Implementing); + when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID); + + final DeployDestination dest = mock(DeployDestination.class); + + final DataCenter dc = mock(DataCenter.class); + when(dest.getDataCenter()).thenReturn(dc); + + final HostVO niciraHost = mock(HostVO.class); + when(hostdao.findById(anyLong())).thenReturn(niciraHost); + when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa"); + when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt"); + when(niciraHost.getId()).thenReturn(NETWORK_ID); + + when(netmodel.findPhysicalNetworkId(anyLong(), (String)any(), (TrafficType)any())).thenReturn(NETWORK_ID); + final Domain dom = mock(Domain.class); + when(dom.getName()).thenReturn("domain"); + final Account acc = mock(Account.class); + when(acc.getAccountName()).thenReturn("accountname"); + final ReservationContext res = mock(ReservationContext.class); + when(res.getDomain()).thenReturn(dom); + when(res.getAccount()).thenReturn(acc); + + final CreateLogicalSwitchAnswer answer = mock(CreateLogicalSwitchAnswer.class); + when(answer.getResult()).thenReturn(true); + //when(answer.getLogicalSwitchUuid()).thenReturn("aaaaa"); + when(agentmgr.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer); + + final Network implementednetwork = guru.implement(network, offering, dest, res); + assertTrue(implementednetwork == null); + verify(agentmgr, times(1)).easySend(eq(NETWORK_ID), (Command)any()); + } + + @Test + public void testShutdown() throws InsufficientVirtualNetworkCapacityException, URISyntaxException { + final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + when(physnetdao.findById((Long)any())).thenReturn(physnet); + when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT", "VXLAN"})); + when(physnet.getId()).thenReturn(NETWORK_ID); + + final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); + when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device})); + when(device.getId()).thenReturn(1L); + + final NetworkOffering offering = mock(NetworkOffering.class); + when(offering.getId()).thenReturn(NETWORK_ID); + when(offering.getTrafficType()).thenReturn(TrafficType.Guest); + when(offering.getGuestType()).thenReturn(GuestType.Isolated); + + when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(false); + + mock(DeploymentPlan.class); + + final NetworkVO network = mock(NetworkVO.class); + when(network.getName()).thenReturn("testnetwork"); + when(network.getState()).thenReturn(State.Implementing); + when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch); + when(network.getBroadcastUri()).thenReturn(new URI("lswitch:aaaaa")); + when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID); + when(netdao.findById(NETWORK_ID)).thenReturn(network); + + final DeployDestination dest = mock(DeployDestination.class); + + final DataCenter dc = mock(DataCenter.class); + when(dest.getDataCenter()).thenReturn(dc); + + final HostVO niciraHost = mock(HostVO.class); + when(hostdao.findById(anyLong())).thenReturn(niciraHost); + when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa"); + when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt"); + when(niciraHost.getId()).thenReturn(NETWORK_ID); + + when(netmodel.findPhysicalNetworkId(anyLong(), (String)any(), (TrafficType)any())).thenReturn(NETWORK_ID); + final Domain dom = mock(Domain.class); + when(dom.getName()).thenReturn("domain"); + final Account acc = mock(Account.class); + when(acc.getAccountName()).thenReturn("accountname"); + final ReservationContext res = mock(ReservationContext.class); + when(res.getDomain()).thenReturn(dom); + when(res.getAccount()).thenReturn(acc); + + final DeleteLogicalSwitchAnswer answer = mock(DeleteLogicalSwitchAnswer.class); + when(answer.getResult()).thenReturn(true); + when(agentmgr.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer); + + final NetworkProfile implementednetwork = mock(NetworkProfile.class); + when(implementednetwork.getId()).thenReturn(NETWORK_ID); + when(implementednetwork.getBroadcastUri()).thenReturn(new URI("lswitch:aaaa")); + when(offering.getSpecifyVlan()).thenReturn(false); + + guru.shutdown(implementednetwork, offering); + verify(agentmgr, times(1)).easySend(eq(NETWORK_ID), (Command)any()); + verify(implementednetwork, times(1)).setBroadcastUri(null); + } +} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NatRuleTest.java ---------------------------------------------------------------------- diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NatRuleTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NatRuleTest.java new file mode 100644 index 0000000..d4c6596 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NatRuleTest.java @@ -0,0 +1,55 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.network.nicira; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import com.google.gson.FieldNamingPolicy; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public class NatRuleTest { + + @Test + public void testNatRuleEncoding() { + final Gson gson = + new GsonBuilder().registerTypeAdapter(NatRule.class, new NiciraNvpApi.NatRuleAdapter()) + .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) + .create(); + + final DestinationNatRule rn1 = new DestinationNatRule(); + rn1.setToDestinationIpAddress("10.10.10.10"); + rn1.setToDestinationPort(80); + final Match mr1 = new Match(); + mr1.setSourceIpAddresses("11.11.11.11/24"); + mr1.setEthertype("IPv4"); + mr1.setProtocol(6); + rn1.setMatch(mr1); + + final String jsonString = gson.toJson(rn1); + final NatRule dnr = gson.fromJson(jsonString, NatRule.class); + + assertTrue(dnr instanceof DestinationNatRule); + assertTrue(rn1.equals(dnr)); + } + +} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiIT.java ---------------------------------------------------------------------- diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiIT.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiIT.java new file mode 100644 index 0000000..3bb4b9d --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiIT.java @@ -0,0 +1,347 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.network.nicira; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import java.util.UUID; + +import org.junit.Before; +import org.junit.Test; + +import com.cloud.utils.PropertiesUtil; + +public class NiciraNvpApiIT { + + protected NiciraNvpApi api; + + protected long timestamp = System.currentTimeMillis(); + + @Before + public void setup() throws IOException { + final Properties properties = PropertiesUtil.loadFromFile(PropertiesUtil.findConfigFile("config.properties")); + api = new NiciraNvpApi(); + api.setControllerAddress(properties.getProperty("nvp.host")); + api.setAdminCredentials(properties.getProperty("nvp.admin.user"), + properties.getProperty("nvp.admin.pwd")); + } + + @Test + public void testCRUDSecurityProfile() throws NiciraNvpApiException { + SecurityProfile sProfile = new SecurityProfile(); + sProfile.setDisplayName("SecProfile"+timestamp); + + final List<SecurityRule> egressRules = new ArrayList<SecurityRule>(); + sProfile.setLogicalPortEgressRules(egressRules); + egressRules.add(new SecurityRule(SecurityRule.ETHERTYPE_IPV4, "1.10.10.0", null, 80, 88, 6)); + egressRules.add(new SecurityRule(SecurityRule.ETHERTYPE_IPV6, "2a80:34ac::1", null, 90, 98, 6)); + + final List<SecurityRule> ingressRules = new ArrayList<SecurityRule>(); + sProfile.setLogicalPortIngressRules(ingressRules); + ingressRules.add(new SecurityRule(SecurityRule.ETHERTYPE_IPV4, "1.10.10.0", null, 50, 58, 6)); + ingressRules.add(new SecurityRule(SecurityRule.ETHERTYPE_IPV6, "280a:3ac4::1", null, 60, 68, 6)); + + final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>(); + sProfile.setTags(tags); + tags.add(new NiciraNvpTag("nvp", "MyTag1")); + tags.add(new NiciraNvpTag("nicira", "MyTag2")); + // In the creation we don't get to specify UUID, href or schema: they don't exist yet + + try { + sProfile = api.createSecurityProfile(sProfile); + + // We can now update the new entity + sProfile.setDisplayName("UpdatedSecProfile"+timestamp); + api.updateSecurityProfile(sProfile, sProfile.getUuid()); + + // Read them all + NiciraNvpList<SecurityProfile> profiles = api.findSecurityProfile(); + SecurityProfile scInList = null; + for(final SecurityProfile iProfile : profiles.getResults()) { + if (iProfile.getUuid().equalsIgnoreCase(sProfile.getUuid())) { + scInList = iProfile; + } + } + assertEquals("Read a Security Profile different from the one just created and updated", + sProfile, scInList); + + // Read them filtered by uuid (get one) + profiles = api.findSecurityProfile(sProfile.getUuid()); + assertEquals("Read a Security Profile different from the one just created and updated", + sProfile, + profiles.getResults().get(0)); + assertEquals("Read a Security Profile filtered by unique id (UUID) with more than one item", + 1, profiles.getResults().size()); + + // We can now delete the new entity + api.deleteSecurityProfile(sProfile.getUuid()); + } catch (final NiciraNvpApiException e) { + e.printStackTrace(); + assertTrue("Errors in Security Profile CRUD", false); + } + } + + @Test + public void testCRUDAcl() throws NiciraNvpApiException { + Acl acl = new Acl(); + acl.setDisplayName("Acl"+timestamp); + + // Note that if the protocol is 6 (TCP) then you cannot put ICMP code and type + // Note that if the protocol is 1 (ICMP) then you cannot put ports + final List<AclRule> egressRules = new ArrayList<AclRule>(); + acl.setLogicalPortEgressRules(egressRules); + egressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 1, "allow", null, null, + "1.10.10.0", "1.10.10.1", null, null, null, null, 0, 0, 5)); + egressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 6, "allow", null, null, + "1.10.10.6", "1.10.10.7", 80, 80, 80, 80, 1, null, null)); + + final List<AclRule> ingressRules = new ArrayList<AclRule>(); + acl.setLogicalPortIngressRules(ingressRules); + ingressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 1, "allow", null, null, + "1.10.10.0", "1.10.10.1", null, null, null, null, 0, 0, 5)); + ingressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 6, "allow", null, null, + "1.10.10.6", "1.10.10.7", 80, 80, 80, 80, 1, null, null)); + + final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>(); + acl.setTags(tags); + tags.add(new NiciraNvpTag("nvp", "MyTag1")); + tags.add(new NiciraNvpTag("nicira", "MyTag2")); + // In the creation we don't get to specify UUID, href or schema: they don't exist yet + + try { + acl = api.createAcl(acl); + + // We can now update the new entity + acl.setDisplayName("UpdatedAcl"+timestamp); + api.updateAcl(acl, acl.getUuid()); + + // Read them all + NiciraNvpList<Acl> acls = api.findAcl(); + Acl scInList = null; + for(final Acl iAcl : acls.getResults()) { + if (iAcl.getUuid().equalsIgnoreCase(acl.getUuid())) { + scInList = iAcl; + } + } + assertEquals("Read a ACL different from the one just created and updated", + acl, scInList); + + // Read them filtered by uuid (get one) + acls = api.findAcl(acl.getUuid()); + assertEquals("Read a ACL different from the one just created and updated", + acl, + acls.getResults().get(0)); + assertEquals("Read a ACL filtered by unique id (UUID) with more than one item", + 1, acls.getResults().size()); + + // We can now delete the new entity + api.deleteAcl(acl.getUuid()); + } catch (final NiciraNvpApiException e) { + e.printStackTrace(); + assertTrue("Errors in ACL CRUD", false); + } + } + + @Test + public void testCRUDLogicalSwitch() throws NiciraNvpApiException { + LogicalSwitch logicalSwitch = new LogicalSwitch(); + logicalSwitch.setDisplayName("LogicalSwitch"+timestamp); + logicalSwitch.setPortIsolationEnabled(true); + logicalSwitch.setReplicationMode("service"); + logicalSwitch.setTags(new ArrayList<NiciraNvpTag>()); + logicalSwitch.getTags().add(new NiciraNvpTag("anto", "hugo")); + + // In the creation we don't get to specify UUID, href or schema: they don't exist yet + + try { + logicalSwitch = api.createLogicalSwitch(logicalSwitch); + + // We can now update the new entity + logicalSwitch.setDisplayName("UpdatedLogicalSwitch"+timestamp); + api.updateLogicalSwitch(logicalSwitch, logicalSwitch.getUuid()); + + // Read them all + NiciraNvpList<LogicalSwitch> logicalSwitches = api.findLogicalSwitch(); + for(final LogicalSwitch iLogicalSwitch : logicalSwitches.getResults()) { + if (iLogicalSwitch.getUuid().equalsIgnoreCase(logicalSwitch.getUuid())) { + assertEquals("Read a LogicalSwitch different from the one just created and updated", + logicalSwitch, iLogicalSwitch); + } + } + + // Read them filtered by uuid (get one) + logicalSwitches = api.findLogicalSwitch(logicalSwitch.getUuid()); + assertEquals("Read a LogicalSwitch different from the one just created and updated", + logicalSwitch, + logicalSwitches.getResults().get(0)); + assertEquals("Read a LogicalSwitch filtered by unique id (UUID) with more than one item", + 1, logicalSwitches.getResults().size()); + + // Before deleting the test LogicalSwitch, test its ports + final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>(); + tags.add(new NiciraNvpTag("cs_account", "OwnerName")); + + LogicalSwitchPort logicalSwitchPort = new LogicalSwitchPort("LSwitchPort"+timestamp, tags, true); + logicalSwitchPort = api.createLogicalSwitchPort(logicalSwitch.getUuid(), logicalSwitchPort); + + logicalSwitchPort.setDisplayName("UpdatedLSwitchPort"+timestamp); + api.updateLogicalSwitchPort(logicalSwitch.getUuid(), logicalSwitchPort); + + final NiciraNvpList<LogicalSwitchPort> logicalSwitchePorts = + api.findLogicalSwitchPortsByUuid(logicalSwitch.getUuid(), logicalSwitchPort.getUuid()); + for(final LogicalSwitchPort iLSwitchPort : logicalSwitchePorts.getResults()) { + if (iLSwitchPort.getUuid().equalsIgnoreCase(logicalSwitchPort.getUuid())) { + assertEquals("Read a LogicalSwitchPort different from the one just created and updated", + logicalSwitchPort, iLSwitchPort); + } + } + + // And finally test attachments + final String attachmentUuid = UUID.randomUUID().toString(); + final VifAttachment vifAttachment = new VifAttachment(attachmentUuid); + api.updateLogicalSwitchPortAttachment(logicalSwitch.getUuid(), logicalSwitchPort.getUuid(), + vifAttachment); + + assertEquals("Read a LogicalSwitchPort by vifAttachment different than expected", + api.findLogicalSwitchPortUuidByVifAttachmentUuid(logicalSwitch.getUuid(), vifAttachment.getVifUuid()), + logicalSwitchPort.getUuid()); + + api.deleteLogicalSwitchPort(logicalSwitch.getUuid(), logicalSwitchPort.getUuid()); + + // We can now delete the new entity + api.deleteLogicalSwitch(logicalSwitch.getUuid()); + } catch (final NiciraNvpApiException e) { + e.printStackTrace(); + assertTrue("Errors in LogicalSwitch CRUD", false); + } + } + + @Test + public void testCRUDLogicalRouter() throws NiciraNvpApiException { + LogicalRouter logicalRouter = new LogicalRouter(); + logicalRouter.setDisplayName("LogicalRouter"+timestamp); + logicalRouter.setDistributed(true); + logicalRouter.setNatSynchronizationEnabled(true); + logicalRouter.setReplicationMode(LogicalRouter.REPLICATION_MODE_SERVICE); + final RoutingConfig routingConfig = new SingleDefaultRouteImplicitRoutingConfig( + new RouterNextHop("192.168.10.20")); + logicalRouter.setRoutingConfig(routingConfig); + + // In the creation we don't get to specify UUID, href or schema: they don't exist yet + + try { + logicalRouter = api.createLogicalRouter(logicalRouter); + + // We can now update the new entity + logicalRouter.setDisplayName("UpdatedLogicalSwitch"+timestamp); + api.updateLogicalRouter(logicalRouter, logicalRouter.getUuid()); + + // Read them all + NiciraNvpList<LogicalRouter> logicalRouters = api.findLogicalRouter(); + LogicalRouter lsInList = null; + for(final LogicalRouter iLogicalRouter : logicalRouters.getResults()) { + if (iLogicalRouter.getUuid().equalsIgnoreCase(logicalRouter.getUuid())) { + lsInList = iLogicalRouter; + } + } + assertEquals("Read a LogicalRouter different from the one just created and updated", + logicalRouter, lsInList); + + // Read them filtered by uuid (get one) + logicalRouters = api.findLogicalRouter(logicalRouter.getUuid()); + assertEquals("Read a LogicalRouter different from the one just created and updated", + logicalRouter, + logicalRouters.getResults().get(0)); + assertEquals("Read a LogicalRouter filtered by unique id (UUID) with more than one item", + 1, logicalRouters.getResults().size()); + + assertEquals("", logicalRouters.getResults().get(0), + api.findOneLogicalRouterByUuid(logicalRouter.getUuid())); + + // Before deleting the test LogicalRouter, test its ports + final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>(); + tags.add(new NiciraNvpTag("cs_account", "OwnerName")); + + LogicalRouterPort logicalRouterPort = new LogicalRouterPort(); + logicalRouterPort.setDisplayName("LRouterPort"+timestamp); + logicalRouterPort.setTags(tags); + logicalRouterPort.setAdminStatusEnabled(true); + logicalRouterPort.setPortno(1024); + logicalRouterPort.setMacAddress("00:00:00:00:00:00"); + + final List<String> ipAddresses = new ArrayList<String>(); + // Add some ips to this list + logicalRouterPort.setIpAddresses(ipAddresses); + logicalRouterPort = api.createLogicalRouterPort(logicalRouter.getUuid(), logicalRouterPort); + + logicalRouterPort.setDisplayName("UpdatedLRouterPort"+timestamp); + api.updateLogicalRouterPort(logicalRouter.getUuid(), logicalRouterPort); + + final NiciraNvpList<LogicalRouterPort> logicalRouterePorts = + api.findLogicalRouterPortsByUuid(logicalRouter.getUuid(), logicalRouterPort.getUuid()); + for(final LogicalRouterPort iLRouterPort : logicalRouterePorts.getResults()) { + if (iLRouterPort.getUuid().equalsIgnoreCase(logicalRouterPort.getUuid())) { + assertEquals("Read a LogicalRouterPort different from the one just created and updated", + logicalRouterPort, iLRouterPort); + } + } + + UUID.randomUUID().toString(); + + // Test CRUD for Nat Rules + SourceNatRule snr = new SourceNatRule(); + snr.setToSourceIpAddressMin("192.168.10.10"); + snr.setToSourceIpAddressMax("192.168.10.20"); + snr.setOrder(200); + final Match match = new Match(); + match.setSourceIpAddresses("192.168.150.150"); + snr.setMatch(match); + snr = (SourceNatRule) api.createLogicalRouterNatRule(logicalRouter.getUuid(), snr); + snr.setToSourceIpAddressMax("192.168.10.30"); + api.updateLogicalRouterNatRule(logicalRouter.getUuid(), snr); + + api.findNatRulesByLogicalRouterUuid(logicalRouter.getUuid()); + api.deleteLogicalRouterNatRule(logicalRouter.getUuid(), snr.getUuid()); + + api.deleteLogicalRouterPort(logicalRouter.getUuid(), logicalRouterPort.getUuid()); + + // We can now delete the new entity + api.deleteLogicalRouter(logicalRouter.getUuid()); + } catch (final NiciraNvpApiException e) { + e.printStackTrace(); + assertTrue("Errors in LogicalRouter CRUD", false); + } + } + + @Test + public void testGetControlClusterStatus() throws NiciraNvpApiException { + final ControlClusterStatus controlClusterStatus = api.getControlClusterStatus(); + final String clusterStatus = controlClusterStatus.getClusterStatus(); + final boolean correctStatus = (clusterStatus.equalsIgnoreCase("stable") || + clusterStatus.equalsIgnoreCase("joining") || clusterStatus.equalsIgnoreCase("unstable")); + assertTrue("Not recognizable cluster status", correctStatus); + } + +} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiTest.java ---------------------------------------------------------------------- diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiTest.java new file mode 100644 index 0000000..1435cc5 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiTest.java @@ -0,0 +1,339 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.network.nicira; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Matchers.any; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.HttpMethod; +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.httpclient.NameValuePair; +import org.apache.commons.httpclient.methods.DeleteMethod; +import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.commons.httpclient.methods.PostMethod; +import org.apache.commons.httpclient.methods.PutMethod; +import org.apache.commons.httpclient.params.HttpClientParams; +import org.junit.Before; +import org.junit.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import com.google.gson.Gson; +import com.google.gson.JsonParseException; +import com.cloud.utils.rest.RESTServiceConnector; +import com.cloud.utils.rest.RESTValidationStrategy; + +public class NiciraNvpApiTest { + protected static final String UUID = "aaaa"; + protected static final String UUID2 = "bbbb"; + protected static final String UUID_SEC_PROFILE_URI = NiciraNvpApi.SEC_PROFILE_URI_PREFIX + "/aaaa"; + protected static final String SCHEMA = "myTestSchema"; + protected static final String SCHEMA2 = "myTestSchema2"; + protected static final String HREF = "myTestHref"; + protected static final String HREF2 = "myTestHref2"; + protected static final String SEC_PROFILE_JSON_RESPONSE = + "{\"uuid\" : \"aaaa\"," + + "\"display_name\" : \"myTestName\"," + + "\"href\" : \"myTestHref\"," + + "\"schema\" : \"myTestSchema\"}"; + + protected static final String SEC_PROFILE_LIST_JSON_RESPONSE = "{\"results\" : [{\"uuid\" : \"aaaa\"," + + "\"display_name\" : \"myTestName\"," + + "\"href\" : \"myTestHref\"," + + "\"schema\" : \"myTestSchema\"}," + + "{ \"uuid\" : \"bbbb\"," + + "\"display_name\" : \"myTestName2\"," + + "\"href\" : \"myTestHref2\"," + + "\"schema\" : \"myTestSchema2\"}]," + + "\"result_count\": 2}"; + + NiciraNvpApi api; + HttpClient client = mock(HttpClient.class); + HttpMethod method; + String type; + String uri; + + @Before + public void setUp() { + final HttpClientParams hmp = mock(HttpClientParams.class); + when(client.getParams()).thenReturn(hmp); + api = new NiciraNvpApi(); + + api.restConnector = new RESTServiceConnector(new RESTValidationStrategy()) { + @Override + public HttpClient createHttpClient() { + return client; + } + + @Override + public HttpMethod createMethod(final String newType, final String newUri) { + type = newType; + uri = newUri; + return method; + } + }; + + api.setAdminCredentials("admin", "adminpass"); + api.setControllerAddress("localhost"); + } + + @Test + public void testFindSecurityProfile() throws NiciraNvpApiException, IOException { + // Prepare + method = mock(GetMethod.class); + when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK); + when(method.getResponseBodyAsString()).thenReturn(SEC_PROFILE_LIST_JSON_RESPONSE); + final NameValuePair[] queryString = new NameValuePair[]{ + new NameValuePair("fields","*")}; + + // Execute + final NiciraNvpList<SecurityProfile> actualProfiles = api.findSecurityProfile(); + + // Assert + verify(method, times(1)).releaseConnection(); + verify(method, times(1)).setQueryString(queryString); + assertEquals("Wrong Uuid in the newly created SecurityProfile", + UUID, actualProfiles.getResults().get(0).getUuid()); + assertEquals("Wrong Uuid in the newly created SecurityProfile", + HREF, actualProfiles.getResults().get(0).getHref()); + assertEquals("Wrong Schema in the newly created SecurityProfile", + SCHEMA, actualProfiles.getResults().get(0).getSchema()); + assertEquals("Wrong Uuid in the newly created SecurityProfile", + UUID2, actualProfiles.getResults().get(1).getUuid()); + assertEquals("Wrong Uuid in the newly created SecurityProfile", + HREF2, actualProfiles.getResults().get(1).getHref()); + assertEquals("Wrong Schema in the newly created SecurityProfile", + SCHEMA2, actualProfiles.getResults().get(1).getSchema()); + assertEquals("Wrong Schema in the newly created SecurityProfile", + 2, actualProfiles.getResultCount()); + assertEquals("Wrong URI for SecurityProfile creation REST service", + NiciraNvpApi.SEC_PROFILE_URI_PREFIX, uri); + assertEquals("Wrong URI for SecurityProfile creation REST service", + NiciraNvpApi.GET_METHOD_TYPE, type); + } + + @Test + public void testFindSecurityProfileByUuid() throws NiciraNvpApiException, IOException { + // Prepare + method = mock(GetMethod.class); + when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK); + when(method.getResponseBodyAsString()).thenReturn(SEC_PROFILE_LIST_JSON_RESPONSE); + final NameValuePair[] queryString = new NameValuePair[]{ + new NameValuePair("uuid", UUID), + new NameValuePair("fields","*") + }; + final List<NameValuePair> queryStringNvps = new ArrayList<>(); + doAnswer(new Answer<Void>() { + + @Override + public Void answer(InvocationOnMock invocation) throws Throwable { + final NameValuePair[] arguments = (NameValuePair[]) invocation.getArguments()[0]; + queryStringNvps.addAll(Arrays.asList(arguments)); + return null; + }}).when(method).setQueryString(any(NameValuePair[].class)); + + // Execute + final NiciraNvpList<SecurityProfile> actualProfiles = api.findSecurityProfile(UUID); + + // Assert + verify(method, times(1)).releaseConnection(); + assertTrue(queryStringNvps.containsAll(Arrays.asList(queryString))); + assertEquals(queryString.length, queryStringNvps.size()); + assertEquals("Wrong Uuid in the newly created SecurityProfile", + UUID, actualProfiles.getResults().get(0).getUuid()); + assertEquals("Wrong Uuid in the newly created SecurityProfile", + HREF, actualProfiles.getResults().get(0).getHref()); + assertEquals("Wrong Schema in the newly created SecurityProfile", + SCHEMA, actualProfiles.getResults().get(0).getSchema()); + assertEquals("Wrong Uuid in the newly created SecurityProfile", + UUID2, actualProfiles.getResults().get(1).getUuid()); + assertEquals("Wrong Uuid in the newly created SecurityProfile", + HREF2, actualProfiles.getResults().get(1).getHref()); + assertEquals("Wrong Schema in the newly created SecurityProfile", + SCHEMA2, actualProfiles.getResults().get(1).getSchema()); + assertEquals("Wrong Schema in the newly created SecurityProfile", + 2, actualProfiles.getResultCount()); + assertEquals("Wrong URI for SecurityProfile creation REST service", + NiciraNvpApi.SEC_PROFILE_URI_PREFIX, uri); + assertEquals("Wrong HTTP method for SecurityProfile creation REST service", + NiciraNvpApi.GET_METHOD_TYPE, type); + } + + @Test + public void testCreateSecurityProfile() throws NiciraNvpApiException, IOException { + // Prepare + final SecurityProfile inputSecProfile = new SecurityProfile(); + method = mock(PostMethod.class); + when(method.getStatusCode()).thenReturn(HttpStatus.SC_CREATED); + when(method.getResponseBodyAsString()).thenReturn(SEC_PROFILE_JSON_RESPONSE); + + // Execute + final SecurityProfile actualSecProfile = api.createSecurityProfile(inputSecProfile); + + // Assert + verify(method, times(1)).releaseConnection(); + assertEquals("Wrong Uuid in the newly created SecurityProfile", + UUID, actualSecProfile.getUuid()); + assertEquals("Wrong Uuid in the newly created SecurityProfile", + HREF, actualSecProfile.getHref()); + assertEquals("Wrong Schema in the newly created SecurityProfile", + SCHEMA, actualSecProfile.getSchema()); + assertEquals("Wrong URI for SecurityProfile creation REST service", + NiciraNvpApi.SEC_PROFILE_URI_PREFIX, uri); + assertEquals("Wrong HTTP method for SecurityProfile creation REST service", + NiciraNvpApi.POST_METHOD_TYPE, type); + } + + @Test + public void testUpdateSecurityProfile() throws NiciraNvpApiException, IOException { + // Prepare + final SecurityProfile inputSecProfile = new SecurityProfile(); + method = mock(PutMethod.class); + when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK); + + // Execute + api.updateSecurityProfile(inputSecProfile, UUID); + + // Assert + verify(method, times(1)).releaseConnection(); + assertEquals("Wrong URI for SecurityProfile creation REST service", + UUID_SEC_PROFILE_URI, uri); + assertEquals("Wrong HTTP method for SecurityProfile creation REST service", + NiciraNvpApi.PUT_METHOD_TYPE, type); + } + + @Test + public void testDeleteSecurityProfile() throws NiciraNvpApiException, IOException { + // Prepare + method = mock(DeleteMethod.class); + when(method.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT); + + // Execute + api.deleteSecurityProfile(UUID); + + // Assert + verify(method, times(1)).releaseConnection(); + assertEquals("Wrong URI for SecurityProfile deletion REST service", UUID_SEC_PROFILE_URI, uri); + assertEquals("Wrong HTTP method for SecurityProfile deletion REST service", NiciraNvpApi.DELETE_METHOD_TYPE, type); + } + + @Test(expected = JsonParseException.class) + public void testRoutingConfigAdapterNoType() throws NiciraNvpApiException, IOException { + // Prepare + final NiciraNvpApi api = new NiciraNvpApi(); + final Gson gson = api.restConnector.getGson(); + + // Execute + gson.fromJson("{}", RoutingConfig.class); + + // Assert: JsonParseException should be thrown + } + + @Test(expected = JsonParseException.class) + public void testRoutingConfigAdapterWrongType() throws NiciraNvpApiException, IOException { + // Prepare + final NiciraNvpApi api = new NiciraNvpApi(); + final Gson gson = api.restConnector.getGson(); + + // Execute + gson.fromJson("{type : \"WrongType\"}", RoutingConfig.class); + + // Assert: JsonParseException should be thrown + } + + @Test() + public void testRoutingConfigAdapter() throws NiciraNvpApiException, IOException { + // Prepare + final NiciraNvpApi api = new NiciraNvpApi(); + final Gson gson = api.restConnector.getGson(); + + // Execute + final SingleDefaultRouteImplicitRoutingConfig singleDefaultRouteImplicitRoutingConfig = + (SingleDefaultRouteImplicitRoutingConfig) gson.fromJson("{type : \"SingleDefaultRouteImplicitRoutingConfig\"}", RoutingConfig.class); + + // Assert: JsonParseException should be thrown + assertEquals("", SingleDefaultRouteImplicitRoutingConfig.class, singleDefaultRouteImplicitRoutingConfig.getClass()); + } + + @Test(expected = JsonParseException.class) + public void testNatRuleAdapterNoType() throws NiciraNvpApiException, IOException { + // Prepare + final NiciraNvpApi api = new NiciraNvpApi(); + final Gson gson = api.restConnector.getGson(); + + // Execute + gson.fromJson("{}", NatRule.class); + + // Assert: JsonParseException should be thrown + } + + @Test(expected = JsonParseException.class) + public void testNatRuleAdapterWrongType() throws NiciraNvpApiException, IOException { + // Prepare + final NiciraNvpApi api = new NiciraNvpApi(); + final Gson gson = api.restConnector.getGson(); + + // Execute + gson.fromJson("{type : \"WrongType\"}", NatRule.class); + + // Assert: JsonParseException should be thrown + } + + @Test() + public void testRoutingConfigAdapterWithSourceNatRule() throws NiciraNvpApiException, IOException { + // Prepare + final NiciraNvpApi api = new NiciraNvpApi(); + final Gson gson = api.restConnector.getGson(); + + // Execute + final SourceNatRule sourceNatRule = + (SourceNatRule) gson.fromJson("{type : \"SourceNatRule\"}", NatRule.class); + + // Assert: JsonParseException should be thrown + assertEquals("", SourceNatRule.class, sourceNatRule.getClass()); + } + + @Test() + public void testRoutingConfigAdapterWithDestinationNatRule() throws NiciraNvpApiException, IOException { + // Prepare + final NiciraNvpApi api = new NiciraNvpApi(); + final Gson gson = api.restConnector.getGson(); + + // Execute + final DestinationNatRule destinationNatRule = + (DestinationNatRule) gson.fromJson("{type : \"DestinationNatRule\"}", NatRule.class); + + // Assert: JsonParseException should be thrown + assertEquals("", DestinationNatRule.class, destinationNatRule.getClass()); + } + +} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraTagTest.java ---------------------------------------------------------------------- diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraTagTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraTagTest.java new file mode 100644 index 0000000..7a31264 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraTagTest.java @@ -0,0 +1,58 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.network.nicira; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class NiciraTagTest { + @Test + public void testCreateTag() { + final NiciraNvpTag tag = new NiciraNvpTag("scope", "tag"); + assertEquals("scope part set", "scope", tag.getScope()); + assertEquals("tag part set", "tag", tag.getTag()); + } + + @Test + public void testCreateLongTag() { + final NiciraNvpTag tag = new NiciraNvpTag("scope", "verylongtagthatshouldattheminimumexceedthefortycharacterlenght"); + assertEquals("scope part set", "scope", tag.getScope()); + assertEquals("tag part set", "verylongtagthatshouldattheminimumexceedt", tag.getTag()); + } + + @Test + public void testSetTag() { + final NiciraNvpTag tag = new NiciraNvpTag(); + tag.setScope("scope"); + tag.setTag("tag"); + assertEquals("scope part set", "scope", tag.getScope()); + assertEquals("tag part set", "tag", tag.getTag()); + } + + @Test + public void testSetLongTag() { + final NiciraNvpTag tag = new NiciraNvpTag(); + tag.setScope("scope"); + tag.setTag("verylongtagthatshouldattheminimumexceedthefortycharacterlenght"); + assertEquals("scope part set", "scope", tag.getScope()); + assertEquals("tag part set", "verylongtagthatshouldattheminimumexceedt", tag.getTag()); + } +} \ No newline at end of file
