From 4979f95a957e6c239b95fc2c99f12856286b9c10 Mon Sep 17 00:00:00 2001 From: Tomas Cechvala Date: Fri, 13 May 2016 12:11:46 +0200 Subject: [PATCH] Neutron-mapper uses only DTOs from neutron.yang Change-Id: I16481115ddf18628d624dfc51862b327a1b06317 Signed-off-by: Martin Sunal Signed-off-by: Tomas Cechvala --- .../groupbasedpolicy/dto/IndexedTenant.java | 141 +-- .../resolver/IndexedTenantTest.java | 39 +- neutron-mapper/pom.xml | 2 +- .../impl/NeutronMapperModule.java | 10 +- .../neutron/mapper/EndpointRegistrator.java | 131 +++ .../neutron/mapper/NeutronMapper.java | 335 +++++-- .../mapper/mapping/MappingProcessor.java | 24 - .../neutron/mapper/mapping/NeutronAware.java | 20 + .../mapping/NeutronFloatingIpAware.java | 94 +- .../mapper/mapping/NeutronListener.java | 141 --- .../mapper/mapping/NeutronNetworkAware.java | 222 +---- .../mapper/mapping/NeutronNetworkDao.java | 37 - .../mapper/mapping/NeutronPortAware.java | 847 +++++------------- .../mapper/mapping/NeutronRouterAware.java | 514 ++--------- .../mapping/NeutronSecurityGroupAware.java | 115 +++ .../mapper/mapping/NeutronSubnetAware.java | 221 ++--- .../neutron/mapper/mapping/StatusCode.java | 25 - .../group/NeutronSecurityGroupAware.java | 278 ------ .../mapper/mapping/group/SecGroupDao.java | 55 -- .../rule/NeutronGbpMapperServiceImpl.java | 29 +- .../rule/NeutronSecurityRuleAware.java | 402 ++++----- .../mapper/mapping/rule/SecRuleDao.java | 114 --- .../mapping/rule/SecRuleEntityDecoder.java | 140 ++- .../mapping/rule/SecRuleNameDecoder.java | 42 +- .../mapping/rule/SingleClassifierRule.java | 6 +- .../mapping/rule/SingleRuleContract.java | 6 +- .../neutron/mapper/util/MappingUtils.java | 88 +- .../neutron/mapper/util/NetworkUtils.java | 85 ++ .../mapper/util/NeutronMapperIidFactory.java | 26 - .../neutron/mapper/util/NeutronUtils.java | 26 - .../neutron/mapper/util/PortUtils.java | 105 +++ .../neutron/mapper/util/RouterUtils.java | 32 + .../mapper/util/SecurityGroupUtils.java | 43 + .../mapper/util/SecurityRuleUtils.java | 75 ++ .../neutron/mapper/util/SubnetUtils.java | 32 + neutron-mapper/src/main/yang/mapper.yang | 52 -- ...eutronSecurityGroupAwareDataStoreTest.java | 85 ++ ...eutronSecurityGroupAwareDataStoreTest.java | 216 ----- .../mapper/mapping/group/SecGroupDaoTest.java | 135 --- ...NeutronSecurityRuleAwareDataStoreTest.java | 330 ++++--- .../rule/NeutronSecurityRuleAwareTest.java | 68 +- .../mapper/mapping/rule/SecRuleDaoTest.java | 211 ----- .../rule/SecRuleEntityDecoderTest.java | 457 +++------- .../mapping/rule/SecRuleNameDecoderTest.java | 55 +- .../rule/SingleClassifierRuleTest.java | 13 +- .../mapping/rule/SingleRuleContractTest.java | 12 +- .../mapper/test/NeutronEntityFactory.java | 89 +- .../neutron/mapper/test/PolicyAssert.java | 45 +- .../neutron/mapper/util/MappingUtilsTest.java | 221 ----- .../util/NeutronMapperIidFactoryTest.java | 38 - .../renderer/ofoverlay/flow/GroupTable.java | 7 +- .../ofoverlay/flow/OrdinalFactory.java | 13 +- .../destination/DestinationMapperUtils.java | 7 +- .../mapper/external/ExternalMapper.java | 7 +- .../ingressnat/IngressNatMapperFlows.java | 4 +- .../ofoverlay/flow/ChainActionFlowsTest.java | 12 +- .../ofoverlay/flow/GroupTableTest.java | 10 +- .../ofoverlay/mapper/MapperUtilsTest.java | 21 +- .../DestinationMapperFlowsTest.java | 227 +++-- .../destination/DestinationMapperTest.java | 125 ++- .../DestinationMapperUtilsTest.java | 7 +- .../mapper/external/ExternalMapperTest.java | 5 +- .../ingressnat/IngressNatMapperFlowsTest.java | 24 +- .../mapper/source/SourceMapperFlowsTest.java | 22 +- .../mapper/source/SourceMapperTest.java | 7 +- 65 files changed, 2608 insertions(+), 4419 deletions(-) create mode 100644 neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/EndpointRegistrator.java delete mode 100644 neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/MappingProcessor.java create mode 100644 neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronAware.java delete mode 100644 neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronListener.java delete mode 100644 neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronNetworkDao.java create mode 100644 neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronSecurityGroupAware.java delete mode 100644 neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/StatusCode.java delete mode 100644 neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/group/NeutronSecurityGroupAware.java delete mode 100644 neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/group/SecGroupDao.java delete mode 100644 neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SecRuleDao.java create mode 100644 neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/NetworkUtils.java delete mode 100644 neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/NeutronMapperIidFactory.java delete mode 100644 neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/NeutronUtils.java create mode 100644 neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/PortUtils.java create mode 100644 neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/RouterUtils.java create mode 100644 neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/SecurityGroupUtils.java create mode 100644 neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/SecurityRuleUtils.java create mode 100644 neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/SubnetUtils.java delete mode 100644 neutron-mapper/src/main/yang/mapper.yang create mode 100644 neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronSecurityGroupAwareDataStoreTest.java delete mode 100644 neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/group/NeutronSecurityGroupAwareDataStoreTest.java delete mode 100644 neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/group/SecGroupDaoTest.java delete mode 100644 neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SecRuleDaoTest.java delete mode 100644 neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/MappingUtilsTest.java delete mode 100644 neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/NeutronMapperIidFactoryTest.java diff --git a/groupbasedpolicy/src/main/java/org/opendaylight/groupbasedpolicy/dto/IndexedTenant.java b/groupbasedpolicy/src/main/java/org/opendaylight/groupbasedpolicy/dto/IndexedTenant.java index 0bb490a5e..db3fe4457 100644 --- a/groupbasedpolicy/src/main/java/org/opendaylight/groupbasedpolicy/dto/IndexedTenant.java +++ b/groupbasedpolicy/src/main/java/org/opendaylight/groupbasedpolicy/dto/IndexedTenant.java @@ -21,6 +21,9 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ClassifierName; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ContractId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.EndpointGroupId; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2BridgeDomainId; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2FloodDomainId; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L3ContextId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.NetworkDomainId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.SubnetId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.NetworkDomain; @@ -40,7 +43,11 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev import com.google.common.base.Function; import com.google.common.collect.Collections2; +import com.google.common.collect.HashBasedTable; +import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableSet; +import com.google.common.collect.SetMultimap; +import com.google.common.collect.Table; /** * Wrap some convenient indexes around a {@link Tenant} object @@ -55,8 +62,7 @@ public class IndexedTenant { new HashMap<>(); private final Map contracts = new HashMap<>(); - private final Map networkDomains = - new HashMap<>(); + private final Table, NetworkDomain> networkDomains = HashBasedTable., NetworkDomain>create(); private final Map classifiers = new HashMap<>(); private final Map actions = @@ -107,22 +113,22 @@ public class IndexedTenant { private void processForwardingContext(ForwardingContext fwCtx) { if (fwCtx.getL3Context() != null) { for (L3Context c : fwCtx.getL3Context()) { - networkDomains.put(c.getId().getValue(), c); + networkDomains.put(c.getId().getValue(), L3ContextId.class, c); } } if (fwCtx.getL2BridgeDomain() != null) { for (L2BridgeDomain c : fwCtx.getL2BridgeDomain()) { - networkDomains.put(c.getId().getValue(), c); + networkDomains.put(c.getId().getValue(), L2BridgeDomainId.class, c); } } if (fwCtx.getL2FloodDomain() != null) { for (L2FloodDomain c : fwCtx.getL2FloodDomain()) { - networkDomains.put(c.getId().getValue(), c); + networkDomains.put(c.getId().getValue(), L2FloodDomainId.class, c); } } if (fwCtx.getSubnet() != null) { for (Subnet s : fwCtx.getSubnet()) { - networkDomains.put(s.getId().getValue(), s); + networkDomains.put(s.getId().getValue(), SubnetId.class, s); Set sset = subnetMap.get(s.getParent().getValue()); if (sset == null) { subnetMap.put(s.getParent().getValue(), sset = new HashSet()); @@ -147,41 +153,31 @@ public class IndexedTenant { public Set getExternalImplicitGroups() { return externalImplicitGroups; } - - /** - * Look up the network domain specified - * @param id the {@link NetworkDomainId} - * @return the {@link NetworkDomain} if it exists, or null - * otherwise - */ - public NetworkDomain getNetworkDomain(NetworkDomainId id) { - return networkDomains.get(id.getValue()); - } /** * Look up the endpoint group specified * @param id the {@link EndpointGroupId} - * @return the {@link EndpointGroup} if it exists, or null + * @return the {@link EndpointGroup} if it exists, or null * otherwise */ public EndpointGroup getEndpointGroup(EndpointGroupId id) { return endpointGroups.get(id); } - + /** * Look up the contract specified * @param id the {@link ContractId} - * @return the {@link Contract} if it exists, or null + * @return the {@link Contract} if it exists, or null * otherwise */ public Contract getContract(ContractId id) { return contracts.get(id); } - + /** * Look up the classifier instance specified * @param name the {@link ClassifierName} - * @return the {@link ClassifierInstance} if it exists, or null + * @return the {@link ClassifierInstance} if it exists, or null * otherwise */ public ClassifierInstance getClassifier(ClassifierName name) { @@ -191,7 +187,7 @@ public class IndexedTenant { /** * Look up the classifier instance specified * @param name the {@link ActionName} - * @return the {@link ActionInstance} if it exists, or null + * @return the {@link ActionInstance} if it exists, or null * otherwise */ public ActionInstance getAction(ActionName name) { @@ -199,45 +195,68 @@ public class IndexedTenant { } /** - * Get the layer 3 context for the specified network domain by walking + * Get the layer 3 context + * @param id the {@link L3ContextId} + * @return the {@link L3Context} or null if it does not exist + */ + public L3Context resolveL3Context(L3ContextId id) { + return resolveDomain(L3Context.class, id); + } + + /** + * Get the layer 3 context for the specified l2 bridge domain by walking * up the hierarchy - * @param id the {@link NetworkDomainId} for the network domain + * @param id the {@link L2BridgeDomainId} * @return the {@link L3Context} or null if it does not exist */ - public L3Context resolveL3Context(NetworkDomainId id) { + public L3Context resolveL3Context(L2BridgeDomainId id) { return resolveDomain(L3Context.class, id); } /** - * Get the layer 2 bridge domain for the specified network domain by walking + * Get the layer 3 context for the specified l2 flood domain by walking * up the hierarchy - * @param id the {@link NetworkDomainId} for the network domain - * @return the {@link L2BridgeDomain} or null if it does - * not exist + * @param id the {@link L2FloodDomainId} + * @return the {@link L3Context} or null if it does not exist + */ + public L3Context resolveL3Context(L2FloodDomainId id) { + return resolveDomain(L3Context.class, id); + } + + /** + * Get the layer 2 bridge domain + * @param id the {@link L2BridgeDomainId} + * @return the {@link L2BridgeDomain} or null if it does not exist */ - public L2BridgeDomain resolveL2BridgeDomain(NetworkDomainId id) { + public L2BridgeDomain resolveL2BridgeDomain(L2BridgeDomainId id) { return resolveDomain(L2BridgeDomain.class, id); } /** - * Get the layer 2 flood domain for the specified network domain by walking + * Get the layer 2 bridge domain for the specified l2 flood domain by walking * up the hierarchy - * @param id the {@link NetworkDomainId} for the network domain - * @return the {@link L2FloodDomain} or null if it does - * not exist + * @param id the {@link L2FloodDomainId} + * @return the {@link L2BridgeDomain} or null if it does not exist + */ + public L2BridgeDomain resolveL2BridgeDomain(L2FloodDomainId id) { + return resolveDomain(L2BridgeDomain.class, id); + } + + /** + * Get the layer 2 flood domain + * @param id the {@link L2FloodDomainId} + * @return the {@link L2FloodDomain} or null if it does not exist */ - public L2FloodDomain resolveL2FloodDomain(NetworkDomainId id) { + public L2FloodDomain resolveL2FloodDomain(L2FloodDomainId id) { return resolveDomain(L2FloodDomain.class, id); } /** * Get the subnet based on it's ID. Since subnet is on the bottom - * of the forwarding hierarchy, there is no other underlying domain - * from which {@link Subnet} could be resolved. That is why the - * argument refers directly to {@link SubnetId} and not - * {@link NetworkDomainId} + * of the forwarding hierarchy, there is no other upstream domain + * to resolved. * - * @param id of the {@link Subnet} + * @param id of the {@link SubnetId} * @return the {@link Subnet} or null if it does * not exist */ @@ -259,12 +278,12 @@ public class IndexedTenant { Set cursset = subnetMap.get(id.getValue()); if (cursset != null) sset.addAll(cursset); - NetworkDomain d = networkDomains.get(id.getValue()); + NetworkDomain d = networkDomains.get(id.getValue(), id.getClass()); if (d == null) break; if (d instanceof Subnet) { id = ((Subnet)d).getParent(); sset.add(((Subnet) d).getId()); - } + } else if (d instanceof L2BridgeDomain) id = ((L2BridgeDomain)d).getParent(); else if (d instanceof L2FloodDomain) @@ -275,7 +294,7 @@ public class IndexedTenant { return Collections2.transform(sset, new Function() { @Override public Subnet apply(SubnetId input) { - return (Subnet)networkDomains.get(input.getValue()); + return (Subnet)networkDomains.get(input.getValue(), SubnetId.class); } }); } @@ -283,7 +302,7 @@ public class IndexedTenant { // ****** // Object // ****** - + @Override public int hashCode() { return hashCode; @@ -310,23 +329,27 @@ public class IndexedTenant { // Implementation // ************** - private C resolveDomain(Class domainClass, - NetworkDomainId id) { - HashSet visited = new HashSet<>(); + @SuppressWarnings("unchecked") + private C resolveDomain(Class domainClass, I id) { + SetMultimap> visited = HashMultimap.create(); while (id != null) { - if (visited.contains(id)) return null; - visited.add(id); - NetworkDomain d = networkDomains.get(id.getValue()); - if (d == null) return null; - if (domainClass.isInstance(d)) return domainClass.cast(d); - if (d instanceof Subnet) - id = ((Subnet)d).getParent(); - else if (d instanceof L2BridgeDomain) - id = ((L2BridgeDomain)d).getParent(); - else if (d instanceof L2FloodDomain) - id = ((L2FloodDomain)d).getParent(); - else + // TODO condition + if (visited.get(id) != null && visited.containsEntry(id, id.getClass())) { + return null; + } + visited.put(id, id.getClass()); + NetworkDomain d = networkDomains.get(id.getValue(), id.getClass()); + if (d == null) + return null; + if (domainClass.isInstance(d)) + return domainClass.cast(d); + if (d instanceof L2BridgeDomain) { + id = (I) ((L2BridgeDomain) d).getParent(); + } else if (d instanceof L2FloodDomain) { + id = (I) ((L2FloodDomain) d).getParent(); + } else { id = null; + } } return null; } diff --git a/groupbasedpolicy/src/test/java/org/opendaylight/groupbasedpolicy/resolver/IndexedTenantTest.java b/groupbasedpolicy/src/test/java/org/opendaylight/groupbasedpolicy/resolver/IndexedTenantTest.java index 7efbe1a1f..b0fbaeb4f 100644 --- a/groupbasedpolicy/src/test/java/org/opendaylight/groupbasedpolicy/resolver/IndexedTenantTest.java +++ b/groupbasedpolicy/src/test/java/org/opendaylight/groupbasedpolicy/resolver/IndexedTenantTest.java @@ -89,13 +89,13 @@ public class IndexedTenantTest { .build(); IndexedTenant it = new IndexedTenant(t); - assertNotNull(it.getNetworkDomain(sid)); + assertNotNull(it.resolveSubnet(sid)); Collection sns = it.resolveSubnets(sid); assertTrue(sns.contains(s)); assertTrue(sns.contains(s2)); - assertEquals(l3id, it.resolveL3Context(sid).getId()); - assertEquals(bdid, it.resolveL2BridgeDomain(sid).getId()); - assertEquals(fdid, it.resolveL2FloodDomain(sid).getId()); + assertEquals(l3id, it.resolveL3Context(fdid).getId()); + assertEquals(bdid, it.resolveL2BridgeDomain(fdid).getId()); + assertEquals(fdid, it.resolveL2FloodDomain(fdid).getId()); } @Test @@ -111,31 +111,6 @@ public class IndexedTenantTest { when(policy.getContract()).thenReturn(contractList); ContractId contractId = mock(ContractId.class); when(contract.getId()).thenReturn(contractId); - - L3Context l3Context = mock(L3Context.class); - List l3ContextList = Arrays.asList(l3Context); - when(fwCtx.getL3Context()).thenReturn(l3ContextList); - L3ContextId l3ContextId = mock(L3ContextId.class); - when(l3Context.getId()).thenReturn(l3ContextId); - String l3ContextValue = "contextID"; - when(l3ContextId.getValue()).thenReturn(l3ContextValue); - - L2BridgeDomain l2BridgeDomain = mock(L2BridgeDomain.class); - List l2BridgeDomainList = Arrays.asList(l2BridgeDomain); - when(fwCtx.getL2BridgeDomain()).thenReturn(l2BridgeDomainList); - L2BridgeDomainId l2BridgeDomainId = mock(L2BridgeDomainId.class); - when(l2BridgeDomain.getId()).thenReturn(l2BridgeDomainId); - String l2BridgeDomainIdValue = "bridgeDomainID"; - when(l2BridgeDomainId.getValue()).thenReturn(l2BridgeDomainIdValue); - - L2FloodDomain l2FloodDomain = mock(L2FloodDomain.class); - List l2FloodDomainList = Arrays.asList(l2FloodDomain); - when(fwCtx.getL2FloodDomain()).thenReturn(l2FloodDomainList); - L2FloodDomainId l2FloodDomainId = mock(L2FloodDomainId.class); - when(l2FloodDomain.getId()).thenReturn(l2FloodDomainId); - String cValue = "floodDomainID"; - when(l2FloodDomainId.getValue()).thenReturn(cValue); - Subnet subnet = mock(Subnet.class); List subnetList = Arrays.asList(subnet); when(fwCtx.getSubnet()).thenReturn(subnetList); @@ -147,16 +122,13 @@ public class IndexedTenantTest { when(subnet.getParent()).thenReturn(sParent); String sParentValue = "sParentValue"; when(sParent.getValue()).thenReturn(sParentValue); - SubjectFeatureInstances sfi = mock(SubjectFeatureInstances.class); when(policy.getSubjectFeatureInstances()).thenReturn(sfi); - ClassifierInstance ci = mock(ClassifierInstance.class); List ciList = Arrays.asList(ci); when(sfi.getClassifierInstance()).thenReturn(ciList); ClassifierName ciName = mock(ClassifierName.class); when(ci.getName()).thenReturn(ciName); - ActionInstance ai = mock(ActionInstance.class); List actionList = Arrays.asList(ai); when(sfi.getActionInstance()).thenReturn(actionList); @@ -169,9 +141,6 @@ public class IndexedTenantTest { assertEquals(tenant, it.getTenant()); assertEquals(eg, it.getEndpointGroup(egId)); assertEquals(contract, it.getContract(contractId)); - assertEquals(l3Context, it.getNetworkDomain(l3ContextId)); - assertEquals(l2BridgeDomain, it.getNetworkDomain(l2BridgeDomainId)); - assertEquals(l2FloodDomain, it.getNetworkDomain(l2FloodDomainId)); assertEquals(ci, it.getClassifier(ciName)); assertEquals(ai, it.getAction(actionName)); } diff --git a/neutron-mapper/pom.xml b/neutron-mapper/pom.xml index d76ae547c..a0d0e8273 100644 --- a/neutron-mapper/pom.xml +++ b/neutron-mapper/pom.xml @@ -33,7 +33,7 @@ org.opendaylight.neutron - neutron-spi + model ${neutron.version} diff --git a/neutron-mapper/src/main/java/org/opendaylight/controller/config/yang/config/neutron_mapper/impl/NeutronMapperModule.java b/neutron-mapper/src/main/java/org/opendaylight/controller/config/yang/config/neutron_mapper/impl/NeutronMapperModule.java index 8922794cc..0d5434161 100644 --- a/neutron-mapper/src/main/java/org/opendaylight/controller/config/yang/config/neutron_mapper/impl/NeutronMapperModule.java +++ b/neutron-mapper/src/main/java/org/opendaylight/controller/config/yang/config/neutron_mapper/impl/NeutronMapperModule.java @@ -33,13 +33,11 @@ public class NeutronMapperModule extends org.opendaylight.controller.config.yang public java.lang.AutoCloseable createInstance() { final NeutronMapper neutronMapper = new NeutronMapper(getDataBrokerDependency(), getRpcRegistryDependency()); LOG.info("Neutron mapper started."); - return new AutoCloseable() { + return neutronMapper; + } - @Override - public void close() throws Exception { - neutronMapper.close(); - } - }; + public static boolean isDebugEnabled() { + return true; // TODO add to config-subsystem } } diff --git a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/EndpointRegistrator.java b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/EndpointRegistrator.java new file mode 100644 index 000000000..bc15b4045 --- /dev/null +++ b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/EndpointRegistrator.java @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.groupbasedpolicy.neutron.mapper; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutionException; + +import javax.annotation.Nullable; + +import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L3ContextId; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.NetworkDomainId; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.EndpointService; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterEndpointInput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterEndpointInputBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterL3PrefixEndpointInput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterL3PrefixEndpointInputBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.UnregisterEndpointInput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoint.fields.L3AddressBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoint.l3.prefix.fields.EndpointL3Gateways; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoint.l3.prefix.fields.EndpointL3GatewaysBuilder; +import org.opendaylight.yangtools.yang.common.RpcResult; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableList; + +public class EndpointRegistrator { + + private static final Logger LOG = LoggerFactory.getLogger(EndpointRegistrator.class); + private final EndpointService epService; + + public EndpointRegistrator(EndpointService epService) { + this.epService = Preconditions.checkNotNull(epService); + } + + public boolean registerEndpoint(RegisterEndpointInput regEndpointInput) { + try { + RpcResult rpcResult = epService.registerEndpoint(regEndpointInput).get(); + if (!rpcResult.isSuccessful()) { + LOG.warn("Illegal state - registerEndpoint was not successful. Input of RPC: {}", regEndpointInput); + return false; + } + return true; + } catch (InterruptedException | ExecutionException e) { + LOG.error("registerEndpoint failed. {}", regEndpointInput, e); + return false; + } + } + + public boolean unregisterEndpoint(UnregisterEndpointInput unregEndpointInput) { + try { + RpcResult rpcResult = epService.unregisterEndpoint(unregEndpointInput).get(); + if (!rpcResult.isSuccessful()) { + LOG.warn("Illegal state - unregisterEndpoint was not successful. Input of RPC: {}", unregEndpointInput); + return false; + } + return true; + } catch (InterruptedException | ExecutionException e) { + LOG.error("unregisterEndpoint failed. {}", unregEndpointInput, e); + return false; + } + } + + public boolean registerExternalL3PrefixEndpoint(IpPrefix ipPrefix, L3ContextId l3Context, + @Nullable IpAddress gatewayIp, TenantId tenantId) { + List l3Gateways = new ArrayList(); + if (gatewayIp != null) { + EndpointL3Gateways l3Gateway = + new EndpointL3GatewaysBuilder().setIpAddress(gatewayIp).setL3Context(l3Context).build(); + l3Gateways.add(l3Gateway); + } + RegisterL3PrefixEndpointInput registerL3PrefixEpRpcInput = new RegisterL3PrefixEndpointInputBuilder() + .setL3Context(l3Context) + .setIpPrefix(ipPrefix) + .setEndpointGroup(MappingUtils.EPG_EXTERNAL_ID) + .setTenant(tenantId) + .setEndpointL3Gateways(l3Gateways) + .setTimestamp(System.currentTimeMillis()) + .build(); + try { + RpcResult rpcResult = epService.registerL3PrefixEndpoint(registerL3PrefixEpRpcInput).get(); + if (!rpcResult.isSuccessful()) { + LOG.warn("Illegal state - registerExternalL3PrefixEndpoint was not successful. Input of RPC: {}", + registerL3PrefixEpRpcInput); + return false; + } + return true; + } catch (InterruptedException | ExecutionException e) { + LOG.error("registerExternalL3PrefixEndpoint failed. {}", registerL3PrefixEpRpcInput, e); + return false; + } + } + + public boolean registerL3EndpointAsExternalGateway(TenantId tenantId, IpAddress ipAddress, L3ContextId l3Context, + NetworkDomainId networkContainment) { + RegisterEndpointInput registerEndpointInput = + new RegisterEndpointInputBuilder() + .setL3Address(ImmutableList + .of(new L3AddressBuilder().setL3Context(l3Context).setIpAddress(ipAddress).build())) + .setTenant(tenantId) + .setNetworkContainment(networkContainment) + .setEndpointGroups(ImmutableList.of(MappingUtils.EPG_EXTERNAL_ID)) + .setTimestamp(System.currentTimeMillis()) + .build(); + try { + RpcResult rpcResult = epService.registerEndpoint(registerEndpointInput).get(); + if (!rpcResult.isSuccessful()) { + LOG.warn("Illegal state - registerL3EndpointAsExternalGateway was not successful. Input of RPC: {}", + registerEndpointInput); + return false; + } + } catch (InterruptedException | ExecutionException e) { + LOG.error("registerL3EndpointAsExternalGateway failed. {}", registerEndpointInput, e); + return false; + } + return true; + } + +} diff --git a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/NeutronMapper.java b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/NeutronMapper.java index f514f0016..ece7573cd 100644 --- a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/NeutronMapper.java +++ b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/NeutronMapper.java @@ -5,110 +5,309 @@ * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ - package org.opendaylight.groupbasedpolicy.neutron.mapper; -import static com.google.common.base.Preconditions.checkNotNull; - +import java.io.IOException; import java.util.ArrayList; +import java.util.Collection; import java.util.List; +import java.util.Set; + +import javax.annotation.Nullable; import org.opendaylight.controller.md.sal.binding.api.DataBroker; -import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RpcRegistration; +import org.opendaylight.controller.md.sal.binding.api.DataObjectModification; +import org.opendaylight.controller.md.sal.binding.api.DataObjectModification.ModificationType; +import org.opendaylight.controller.md.sal.binding.api.DataTreeChangeListener; +import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier; +import org.opendaylight.controller.md.sal.binding.api.DataTreeModification; +import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry; +import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.NeutronAware; import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.NeutronFloatingIpAware; -import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.NeutronListener; import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.NeutronNetworkAware; -import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.NeutronNetworkDao; import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.NeutronPortAware; import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.NeutronRouterAware; +import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.NeutronSecurityGroupAware; import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.NeutronSubnetAware; -import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.group.NeutronSecurityGroupAware; -import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.group.SecGroupDao; -import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.rule.NeutronGbpMapperServiceImpl; import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.rule.NeutronSecurityRuleAware; -import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.rule.SecRuleDao; +import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils; +import org.opendaylight.groupbasedpolicy.neutron.mapper.util.NetworkUtils; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.EndpointService; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.NeutronGbpMapperService; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.floatingips.attributes.Floatingips; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionEgress; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionIngress; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeV4; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeV6; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.floatingips.attributes.floatingips.Floatingip; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.Routers; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.routers.Router; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.Networks; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.networks.Network; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.Ports; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.NeutronBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.SecurityGroups; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.SecurityGroupsBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.security.groups.SecurityGroup; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.security.groups.SecurityGroupBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.SecurityRules; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.SecurityRulesBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRule; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.Subnets; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRuleBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet; +import org.opendaylight.yangtools.concepts.ListenerRegistration; +import org.opendaylight.yangtools.yang.binding.DataObject; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -import org.osgi.framework.ServiceRegistration; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument; + +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.collect.FluentIterable; +import com.google.common.collect.Iterators; +import com.google.common.collect.PeekingIterator; + +public class NeutronMapper implements DataTreeChangeListener, AutoCloseable { -public class NeutronMapper implements AutoCloseable { + private final static SecurityRuleBuilder EIG_INGRESS_IPV4_SEC_RULE_BUILDER = new SecurityRuleBuilder() + .setId(new Uuid("19b85ad2-bdfc-11e5-9912-ba0be0483c18")) + .setDirection(DirectionIngress.class) + .setEthertype(EthertypeV4.class) + .setSecurityGroupId(MappingUtils.EIG_UUID); + private final static SecurityRuleBuilder EIG_EGRESS_IPV4_SEC_RULE_BUILDER = new SecurityRuleBuilder() + .setId(new Uuid("19b85ad2-bdfc-11e5-9912-ba0be0483c18")) + .setDirection(DirectionEgress.class) + .setEthertype(EthertypeV4.class) + .setSecurityGroupId(MappingUtils.EIG_UUID); + private final static SecurityRuleBuilder EIG_INGRESS_IPV6_SEC_RULE_BUILDER = new SecurityRuleBuilder() + .setId(new Uuid("19b85ad2-bdfc-11e5-9912-ba0be0483c18")) + .setDirection(DirectionIngress.class) + .setEthertype(EthertypeV6.class) + .setSecurityGroupId(MappingUtils.EIG_UUID); + private final static SecurityRuleBuilder EIG_EGRESS_IPV6_SEC_RULE_BUILDER = new SecurityRuleBuilder() + .setId(new Uuid("19b85ad2-bdfc-11e5-9912-ba0be0483c18")) + .setDirection(DirectionEgress.class) + .setEthertype(EthertypeV6.class) + .setSecurityGroupId(MappingUtils.EIG_UUID); + private final static SecurityGroupBuilder EIG_SEC_GROUP_BUILDER = + new SecurityGroupBuilder().setUuid(MappingUtils.EIG_UUID).setDescription("EXTERNAL_group"); - private final List> registrations = new ArrayList>(); - private final DataBroker dataProvider; - private final RpcProviderRegistry providerRegistry; - private final EndpointService epService; - private RpcRegistration rpcRegistration; - private NeutronListener neutronListener; + private final NeutronNetworkAware networkAware; + private final NeutronSecurityGroupAware securityGroupAware; + private final NeutronSecurityRuleAware securityRuleAware; + private final NeutronSubnetAware subnetAware; + private final NeutronPortAware portAware; + private final NeutronRouterAware routerAware; + private final NeutronFloatingIpAware floatingIpAware; + + private final ListenerRegistration registerDataTreeChangeListener; + private Neutron neutronBefore; + private Neutron neutronAfter; public NeutronMapper(DataBroker dataProvider, RpcProviderRegistry rpcProvider) { - this.dataProvider = checkNotNull(dataProvider); - this.providerRegistry = checkNotNull(rpcProvider); - this.epService = rpcProvider.getRpcService(EndpointService.class); - neutronListener = new NeutronListener(dataProvider); - registerAwareProviders(); + EndpointService epService = rpcProvider.getRpcService(EndpointService.class); + EndpointRegistrator epRegistrator = new EndpointRegistrator(epService); + networkAware = new NeutronNetworkAware(dataProvider); + securityGroupAware = new NeutronSecurityGroupAware(dataProvider); + securityRuleAware = new NeutronSecurityRuleAware(dataProvider); + subnetAware = new NeutronSubnetAware(dataProvider, epRegistrator); + portAware = new NeutronPortAware(dataProvider, epRegistrator); + routerAware = new NeutronRouterAware(dataProvider, epRegistrator); + floatingIpAware = new NeutronFloatingIpAware(dataProvider); + registerDataTreeChangeListener = + dataProvider.registerDataTreeChangeListener(new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION, + InstanceIdentifier.builder(Neutron.class).build()), this); + } + + @Override + public void onDataTreeChanged(Collection> changes) { + for (DataTreeModification change : changes) { + DataObjectModification neutronModif = change.getRootNode(); + resolveAndSetNeutron(neutronModif); + // network + List> networkModifs = + findModifiedData(NeutronNetworkAware.NETWORK_WILDCARD_IID, neutronModif); + for (Uuid tenantFromCreatedRouterExternalNetwork : filterCreatedRouterExternalNetworksAndTransformToTenants( + networkModifs)) { + SecurityGroup eigSecGroup = + EIG_SEC_GROUP_BUILDER.setTenantId(tenantFromCreatedRouterExternalNetwork).build(); + securityGroupAware.onCreated(eigSecGroup, neutronAfter); + List eigSecRules = createEigSecurityRules(tenantFromCreatedRouterExternalNetwork); + for (SecurityRule eigSecRule : eigSecRules) { + securityRuleAware.onCreated(eigSecRule, neutronAfter); + } + } + onDataObjectModification(networkModifs, networkAware); + // security group + List> secGroupModifs = + findModifiedData(NeutronSecurityGroupAware.SECURITY_GROUP_WILDCARD_IID, neutronModif); + onDataObjectModification(secGroupModifs, securityGroupAware); + // security rules + List> secRuleModifs = + findModifiedData(NeutronSecurityRuleAware.SECURITY_RULE_WILDCARD_IID, neutronModif); + onDataObjectModification(secRuleModifs, securityRuleAware); + // subnet + List> subnetModifs = findModifiedData(NeutronSubnetAware.SUBNET_WILDCARD_IID, neutronModif); + onDataObjectModification(subnetModifs, subnetAware); + // port + List> portModifs = findModifiedData(NeutronPortAware.PORT_WILDCARD_IID, neutronModif); + onDataObjectModification(portModifs, portAware); + // router + List> routerModifs = findModifiedData(NeutronRouterAware.ROUTER_WILDCARD_IID, neutronModif); + onDataObjectModification(routerModifs, routerAware); + // floating IP + List> floatingIpModifs = findModifiedData(NeutronFloatingIpAware.FLOATING_IP_WILDCARD_IID, neutronModif); + onDataObjectModification(floatingIpModifs, floatingIpAware); + } } - private void registerAwareProviders() { - SecGroupDao secGroupDao = new SecGroupDao(); - SecRuleDao secRuleDao = new SecRuleDao(); - NeutronNetworkDao networkDao = new NeutronNetworkDao(); - NeutronSecurityRuleAware securityRuleAware = new NeutronSecurityRuleAware(dataProvider, secRuleDao, secGroupDao); - NeutronSecurityGroupAware securityGroupAware = new NeutronSecurityGroupAware(dataProvider, securityRuleAware, secGroupDao); - neutronListener.registerMappingProviders( - InstanceIdentifier.builder(Neutron.class).child(Floatingips.class).child(Floatingip.class).build(), - new NeutronFloatingIpAware(dataProvider)); - neutronListener.registerMappingProviders( - InstanceIdentifier.builder(Neutron.class).child(Ports.class).child(Port.class).build(), - new NeutronPortAware(dataProvider, epService, securityRuleAware, securityGroupAware)); - neutronListener.registerMappingProviders( - InstanceIdentifier.builder(Neutron.class).child(Routers.class).child(Router.class).build(), - new NeutronRouterAware(dataProvider, epService)); - neutronListener.registerMappingProviders( - InstanceIdentifier.builder(Neutron.class).child(SecurityRules.class).child(SecurityRule.class).build(), - securityRuleAware); - neutronListener.registerMappingProviders( - InstanceIdentifier.builder(Neutron.class).child(SecurityGroups.class).child(SecurityGroup.class).build(), - securityGroupAware); - neutronListener.registerMappingProviders( - InstanceIdentifier.builder(Neutron.class).child(Subnets.class).child(Subnet.class).build(), - new NeutronSubnetAware(dataProvider, networkDao)); - neutronListener.registerMappingProviders( - InstanceIdentifier.builder(Neutron.class).child(Networks.class).child(Network.class).build(), - new NeutronNetworkAware(dataProvider, securityGroupAware, networkDao)); - NeutronGbpMapperService neutronGbpMapperService = new NeutronGbpMapperServiceImpl(dataProvider, securityRuleAware); - rpcRegistration = providerRegistry.addRpcImplementation(NeutronGbpMapperService.class, neutronGbpMapperService); + private void onDataObjectModification(List> dataModifs, + NeutronAware neutronAware) { + for (DataObjectModification dataModif : dataModifs) { + switch (dataModif.getModificationType()) { + case DELETE: + neutronAware.onDeleted(dataModif.getDataBefore(), neutronBefore, neutronAfter); + break; + case SUBTREE_MODIFIED: + neutronAware.onUpdated(dataModif.getDataBefore(), dataModif.getDataAfter(), neutronBefore, + neutronAfter); + break; + case WRITE: + if (dataModif.getDataBefore() == null) { + neutronAware.onCreated(dataModif.getDataAfter(), neutronAfter); + } else { + neutronAware.onUpdated(dataModif.getDataBefore(), dataModif.getDataAfter(), neutronBefore, + neutronAfter); + } + break; + default: + throw new IllegalStateException("Unknown modification type within data " + dataModif); + } + } + } + + private Set filterCreatedRouterExternalNetworksAndTransformToTenants( + List> modifiedNetworks) { + return FluentIterable.from(modifiedNetworks).filter(new Predicate>() { + + @Override + public boolean apply(DataObjectModification modifiedNetwork) { + return (ModificationType.WRITE == modifiedNetwork.getModificationType() + && NetworkUtils.isRouterExternal(modifiedNetwork.getDataAfter())); + } + }).transform(new Function, Uuid>() { + + @Override + public Uuid apply(DataObjectModification modifiedNetwork) { + return modifiedNetwork.getDataAfter().getTenantId(); + } + }).toSet(); + } + + private void resolveAndSetNeutron(DataObjectModification originalNeutron) { + Neutron oldNeutronBefore = originalNeutron.getDataBefore(); + neutronBefore = resolveAndCreateNewNeutron(oldNeutronBefore); + Neutron oldNeutronAfter = originalNeutron.getDataAfter(); + neutronAfter = resolveAndCreateNewNeutron(oldNeutronAfter); + } + + private @Nullable Neutron resolveAndCreateNewNeutron(@Nullable Neutron originalNeutron) { + if (originalNeutron == null) { + return null; + } + NeutronBuilder newNeutronBuilder = new NeutronBuilder(originalNeutron); + resolveAndAddSecurityRulesAndGroups(originalNeutron, newNeutronBuilder); + return newNeutronBuilder.build(); + } + + private void resolveAndAddSecurityRulesAndGroups(Neutron originalNeutron, NeutronBuilder newNeutronBuilder) { + List eigSecRulesAndOriginalSecRules = new ArrayList<>(); + List eigSecGroupAndOriginalSecGroup = new ArrayList<>(); + // resolve EIG sec rules and groups + List routerExternalNetworks = NetworkUtils.findRouterExternalNetworks(originalNeutron.getNetworks()); + Set tenantsFromRouterExternalNetwork = resolveTenantsFromNetworks(routerExternalNetworks); + for (Uuid tenantFromRouterExternalNetwork : tenantsFromRouterExternalNetwork) { + eigSecRulesAndOriginalSecRules.addAll(createEigSecurityRules(tenantFromRouterExternalNetwork)); + eigSecGroupAndOriginalSecGroup + .add(EIG_SEC_GROUP_BUILDER.setTenantId(tenantFromRouterExternalNetwork).build()); + } + // set new sec rules + SecurityRules newSecRules = null; + if (originalNeutron.getSecurityRules() != null) { + List originalSecRules = originalNeutron.getSecurityRules().getSecurityRule(); + if (originalSecRules != null) { + eigSecRulesAndOriginalSecRules.addAll(originalSecRules); + } + newSecRules = new SecurityRulesBuilder(originalNeutron.getSecurityRules()) + .setSecurityRule(eigSecRulesAndOriginalSecRules).build(); + } else { + newSecRules = new SecurityRulesBuilder().setSecurityRule(eigSecRulesAndOriginalSecRules).build(); + } + newNeutronBuilder.setSecurityRules(newSecRules); + // set new sec groups + SecurityGroups newSecGroups = null; + if (originalNeutron.getSecurityGroups() != null) { + List originalSecGroups = originalNeutron.getSecurityGroups().getSecurityGroup(); + if (originalSecGroups != null) { + eigSecGroupAndOriginalSecGroup.addAll(originalSecGroups); + } + newSecGroups = new SecurityGroupsBuilder(originalNeutron.getSecurityGroups()) + .setSecurityGroup(eigSecGroupAndOriginalSecGroup).build(); + } else { + newSecGroups = new SecurityGroupsBuilder().setSecurityGroup(eigSecGroupAndOriginalSecGroup).build(); + } + newNeutronBuilder.setSecurityGroups(newSecGroups); + } + + private Set resolveTenantsFromNetworks(List networks) { + return FluentIterable.from(networks).transform(new Function() { + + @Override + public Uuid apply(Network network) { + return network.getTenantId(); + } + }).toSet(); + } + + private List createEigSecurityRules(Uuid tenant) { + List eigSecRules = new ArrayList<>(); + eigSecRules.add(EIG_INGRESS_IPV4_SEC_RULE_BUILDER.setTenantId(tenant).build()); + eigSecRules.add(EIG_EGRESS_IPV4_SEC_RULE_BUILDER.setTenantId(tenant).build()); + eigSecRules.add(EIG_INGRESS_IPV6_SEC_RULE_BUILDER.setTenantId(tenant).build()); + eigSecRules.add(EIG_EGRESS_IPV6_SEC_RULE_BUILDER.setTenantId(tenant).build()); + return eigSecRules; } /** - * @see java.lang.AutoCloseable#close() + * Finds all modified subnodes of given type in {@link Neutron} node. + * + * @param + * @param iid path to data in root node + * @param rootNode modified data of {@link Neutron} node + * @return {@link List} of modified subnodes */ - @Override - public void close() throws Exception { - for (ServiceRegistration registration : registrations) { - registration.unregister(); + private List> findModifiedData(InstanceIdentifier iid, + DataObjectModification rootNode) { + List> modDtos = new ArrayList<>(); + PeekingIterator pathArgs = Iterators.peekingIterator(iid.getPathArguments().iterator()); + DataObjectModification modifDto = rootNode; + while (pathArgs.hasNext()) { + pathArgs.next(); + for (DataObjectModification childDto : modifDto.getModifiedChildren()) { + if (pathArgs.hasNext() && childDto.getDataType().equals(pathArgs.peek().getType())) { + if (childDto.getDataType().equals(iid.getTargetType())) { + modDtos.add((DataObjectModification) childDto); + } else { + modifDto = childDto; + break; + } + } + } } - if (neutronListener != null) { - neutronListener.close(); - neutronListener = null; - } - rpcRegistration.close(); + return modDtos; + } + + @Override + public void close() throws IOException { + registerDataTreeChangeListener.close(); } } diff --git a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/MappingProcessor.java b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/MappingProcessor.java deleted file mode 100644 index 019fe62a8..000000000 --- a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/MappingProcessor.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.groupbasedpolicy.neutron.mapper.mapping; - -import org.opendaylight.neutron.spi.NeutronObject; -import org.opendaylight.yangtools.yang.binding.DataObject; - -public interface MappingProcessor { - - int canCreate(T t); - int canUpdate(T original, T delta); - int canDelete(T t); - - void updated(T t); - void created(T t); - void deleted(T t); - - T convertToNeutron(D d); -} diff --git a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronAware.java b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronAware.java new file mode 100644 index 000000000..9bc876f9d --- /dev/null +++ b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronAware.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.groupbasedpolicy.neutron.mapper.mapping; + +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron; +import org.opendaylight.yangtools.yang.binding.DataObject; + +public interface NeutronAware { + + void onCreated(T createdItem, Neutron neutron); + void onUpdated(T oldItem, T newItem, Neutron oldNeutron, Neutron newNeutron); + void onDeleted(T deletedItem, Neutron oldNeutron, Neutron newNeutron); + +} diff --git a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronFloatingIpAware.java b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronFloatingIpAware.java index 987ac7966..5288af85b 100644 --- a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronFloatingIpAware.java +++ b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronFloatingIpAware.java @@ -13,23 +13,26 @@ import static com.google.common.base.Preconditions.checkNotNull; import org.opendaylight.controller.md.sal.binding.api.DataBroker; import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction; import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; -import org.opendaylight.groupbasedpolicy.neutron.mapper.util.Utils; import org.opendaylight.groupbasedpolicy.util.DataStoreHelper; import org.opendaylight.groupbasedpolicy.util.IidFactory; -import org.opendaylight.neutron.spi.NeutronFloatingIP; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L3ContextId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.l3endpoint.rev151217.NatAddress; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.l3endpoint.rev151217.NatAddressBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.floatingips.attributes.Floatingips; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.floatingips.attributes.floatingips.Floatingip; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.base.Strings; +import com.google.common.base.Objects; -public class NeutronFloatingIpAware implements MappingProcessor { +public class NeutronFloatingIpAware implements NeutronAware { - public static final Logger LOG = LoggerFactory.getLogger(NeutronFloatingIpAware.class); + private static final Logger LOG = LoggerFactory.getLogger(NeutronFloatingIpAware.class); + public static final InstanceIdentifier FLOATING_IP_WILDCARD_IID = + InstanceIdentifier.builder(Neutron.class).child(Floatingips.class).child(Floatingip.class).build(); private final DataBroker dataProvider; public NeutronFloatingIpAware(DataBroker dataProvider) { @@ -37,90 +40,43 @@ public class NeutronFloatingIpAware implements MappingProcessor, Closeable { - - private final ListenerRegistration registerDataTreeChangeListener; - private final Map, MappingProcessor> dataChangeProviders = new LinkedHashMap<>(); - private static DataObjectModification neutron; - - public NeutronListener(DataBroker dataProvider) { - registerDataTreeChangeListener = dataProvider.registerDataTreeChangeListener(new DataTreeIdentifier<>( - LogicalDatastoreType.CONFIGURATION, InstanceIdentifier.builder(Neutron.class).build()), this); - } - - @Override - public void onDataTreeChanged(Collection> changes) { - for (DataTreeModification change : changes) { - neutron = change.getRootNode(); - for (InstanceIdentifier iid : dataChangeProviders.keySet()) { - for (DataObjectModification modifDto : findModifiedData(iid, change.getRootNode())) { - processChangedData(modifDto, modifDto.getModificationType(), getMappingProvider(iid)); - } - } - } - } - - /** - * Finds all modified subnodes of given type in {@link Neutron} node. - * - * @param iid path to data in root node - * @param rootNode modified data of {@link Neutron} node - * @return {@link List} of modified subnodes - */ - private List> findModifiedData( - InstanceIdentifier iid, DataObjectModification rootNode) { - List> modDtos = new ArrayList<>(); - PeekingIterator pathArgs = Iterators.peekingIterator(iid.getPathArguments().iterator()); - DataObjectModification modifDto = rootNode; - while (pathArgs.hasNext()) { - pathArgs.next(); - for (DataObjectModification childDto : modifDto.getModifiedChildren()) { - if (pathArgs.hasNext() && childDto.getDataType().equals(pathArgs.peek().getType())) { - if (childDto.getDataType().equals(iid.getTargetType())) { - modDtos.add(childDto); - } else { - modifDto = childDto; - break; - } - } - } - } - return modDtos; - } - - static Neutron getNeutronDataBefore() { - return neutron.getDataBefore(); - } - - static Neutron getNeutronDataAfter() { - return neutron.getDataAfter(); - } - - @SuppressWarnings("unchecked") - void processChangedData(DataObjectModification dto, - ModificationType m, MappingProcessor d) { - switch (m) { - case WRITE: { - T dataAfter = (T) dto.getDataAfter(); - X neutronObject = d.convertToNeutron(dataAfter); - if (StatusCode.OK == d.canCreate(neutronObject)) { - d.created(neutronObject); - } - break; - } - case SUBTREE_MODIFIED: { - X neutronObjectBefore = d.convertToNeutron((T) dto.getDataBefore()); - X neutronObjectAfter = d.convertToNeutron((T) dto.getDataAfter()); - if (StatusCode.OK == d.canUpdate(neutronObjectAfter, neutronObjectBefore)) { - d.updated(neutronObjectAfter); - } - break; - } - case DELETE: { - X neutronObjectBefore = d.convertToNeutron((T) dto.getDataBefore()); - if (StatusCode.OK == d.canDelete(neutronObjectBefore)) { - d.deleted(neutronObjectBefore); - } - break; - } - } - } - - public void registerMappingProviders( - InstanceIdentifier iid, MappingProcessor np) { - dataChangeProviders.put(iid, np); - } - - @SuppressWarnings("unchecked") - MappingProcessor getMappingProvider( - InstanceIdentifier iid) { - return (MappingProcessor) dataChangeProviders.get(iid); - } - - @Override - public void close() throws IOException { - registerDataTreeChangeListener.close(); - } - -} - diff --git a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronNetworkAware.java b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronNetworkAware.java index 8e218533e..1c0b349ca 100644 --- a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronNetworkAware.java +++ b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronNetworkAware.java @@ -9,11 +9,8 @@ package org.opendaylight.groupbasedpolicy.neutron.mapper.mapping; import static com.google.common.base.Preconditions.checkNotNull; -import java.util.ArrayList; import java.util.HashSet; -import java.util.List; import java.util.Set; -import java.util.UUID; import org.opendaylight.controller.md.sal.binding.api.DataBroker; import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction; @@ -22,18 +19,9 @@ import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; import org.opendaylight.groupbasedpolicy.neutron.gbp.util.NeutronGbpIidFactory; import org.opendaylight.groupbasedpolicy.neutron.mapper.infrastructure.NetworkClient; import org.opendaylight.groupbasedpolicy.neutron.mapper.infrastructure.NetworkService; -import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.group.NeutronSecurityGroupAware; -import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils; -import org.opendaylight.groupbasedpolicy.neutron.mapper.util.NeutronMapperIidFactory; -import org.opendaylight.groupbasedpolicy.neutron.mapper.util.NeutronUtils; -import org.opendaylight.groupbasedpolicy.neutron.mapper.util.Utils; +import org.opendaylight.groupbasedpolicy.neutron.mapper.util.NetworkUtils; import org.opendaylight.groupbasedpolicy.util.DataStoreHelper; import org.opendaylight.groupbasedpolicy.util.IidFactory; -import org.opendaylight.neutron.spi.NeutronNetwork; -import org.opendaylight.neutron.spi.NeutronNetwork_Segment; -import org.opendaylight.neutron.spi.NeutronSecurityGroup; -import org.opendaylight.neutron.spi.NeutronSecurityRule; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2BridgeDomainId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2FloodDomainId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L3ContextId; @@ -41,130 +29,62 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.mappings.neutron.by.gbp.mappings.provider.physical.networks.as.l2.flood.domains.ProviderPhysicalNetworkAsL2FloodDomain; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.mappings.neutron.by.gbp.mappings.provider.physical.networks.as.l2.flood.domains.ProviderPhysicalNetworkAsL2FloodDomainBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.mapper.rev150223.mappings.network.mappings.NetworkMapping; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.mapper.rev150223.mappings.network.mappings.NetworkMappingBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2BridgeDomain; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2BridgeDomainBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2FloodDomain; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2FloodDomainBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L3Context; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L3ContextBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.ExternalImplicitGroup; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.ExternalImplicitGroupBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.ext.rev150712.NetworkL3Extension; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeBase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeFlat; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeGre; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeVlan; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeVxlan; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.Networks; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.networks.Network; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.provider.ext.rev150712.NetworkProviderExtension; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.provider.ext.rev150712.neutron.networks.network.Segments; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Optional; import com.google.common.base.Strings; -import com.google.common.collect.ImmutableBiMap; -import com.google.common.collect.ImmutableList; -public class NeutronNetworkAware implements MappingProcessor { +public class NeutronNetworkAware implements NeutronAware { private static final Logger LOG = LoggerFactory.getLogger(NeutronNetworkAware.class); + public static final InstanceIdentifier NETWORK_WILDCARD_IID = + InstanceIdentifier.builder(Neutron.class).child(Networks.class).child(Network.class).build(); private final DataBroker dataProvider; private final Set tenantsWithRouterAndNetworkSeviceEntities = new HashSet<>(); - private final NeutronSecurityGroupAware secGrpAware; - private final NeutronNetworkDao networkDao; - public NeutronNetworkAware(DataBroker dataProvider, NeutronSecurityGroupAware secGrpAware, NeutronNetworkDao networkDao) { + public NeutronNetworkAware(DataBroker dataProvider) { this.dataProvider = checkNotNull(dataProvider); - this.secGrpAware = checkNotNull(secGrpAware); - this.networkDao = checkNotNull(networkDao); } - private static final ImmutableBiMap,String> NETWORK_MAP - = new ImmutableBiMap.Builder,String>() - .put(NetworkTypeFlat.class,"flat") - .put(NetworkTypeGre.class,"gre") - .put(NetworkTypeVlan.class,"vlan") - .put(NetworkTypeVxlan.class,"vxlan") - .build(); - @Override - public NeutronNetwork convertToNeutron(Network network) { - NeutronNetwork result = new NeutronNetwork(); - result.initDefaults(); - result.setAdminStateUp(network.isAdminStateUp()); - result.setNetworkName(network.getName()); - result.setShared(network.isShared()); - result.setStatus(network.getStatus()); - result.setTenantID(network.getTenantId()); - result.setID(network.getUuid().getValue()); - - NetworkL3Extension l3Extension = network.getAugmentation(NetworkL3Extension.class); - result.setRouterExternal(l3Extension.isExternal()); - - NetworkProviderExtension providerExtension = network.getAugmentation(NetworkProviderExtension.class); - result.setProviderPhysicalNetwork(providerExtension.getPhysicalNetwork()); - result.setProviderSegmentationID(providerExtension.getSegmentationId()); - result.setProviderNetworkType(NETWORK_MAP.get(providerExtension.getNetworkType())); - List segments = new ArrayList(); - if (providerExtension.getSegments() != null) { - for (Segments segment: providerExtension.getSegments()) { - NeutronNetwork_Segment neutronSegment = new NeutronNetwork_Segment(); - neutronSegment.setProviderPhysicalNetwork(segment.getPhysicalNetwork()); - neutronSegment.setProviderSegmentationID(segment.getSegmentationId()); - neutronSegment.setProviderNetworkType(NETWORK_MAP.get(segment.getNetworkType())); - segments.add(neutronSegment); - } - } - result.setSegments(segments); - return result; - } - - @Override - public int canCreate(NeutronNetwork network) { - LOG.trace("canCreate network - {}", network); - // nothing to consider - return StatusCode.OK; - } - - @Override - public void created(NeutronNetwork network) { + public void onCreated(Network network, Neutron neutron) { LOG.trace("created network - {}", network); ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction(); - L2FloodDomainId l2FdId = new L2FloodDomainId(network.getID()); - TenantId tenantId = new TenantId(Utils.normalizeUuid(network.getTenantID())); + L2FloodDomainId l2FdId = new L2FloodDomainId(network.getUuid().getValue()); + TenantId tenantId = new TenantId(network.getTenantId().getValue()); Name name = null; - if (network.getNetworkName() != null) { + if (!Strings.isNullOrEmpty(network.getName())) { try { - name = new Name(network.getNetworkName()); + name = new Name(network.getName()); } catch (Exception e) { name = null; - LOG.info("Name of Neutron Network '{}' is ignored.", network.getNetworkName()); + LOG.info("Name of Neutron Network '{}' is ignored.", network.getName()); LOG.debug("Name exception", e); } } - L3ContextId l3ContextId = new L3ContextId(UUID.randomUUID().toString()); + L3ContextId l3ContextId = new L3ContextId(l2FdId); L3Context l3Context = new L3ContextBuilder().setId(l3ContextId).setName(name).build(); - rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.l3ContextIid(tenantId, l3ContextId), l3Context, true); + rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.l3ContextIid(tenantId, l3Context.getId()), l3Context, true); - L2BridgeDomainId l2BdId = new L2BridgeDomainId(UUID.randomUUID().toString()); - L2BridgeDomain l2Bd = new L2BridgeDomainBuilder().setId(l2BdId).setParent(l3ContextId).setName(name).build(); + L2BridgeDomainId l2BdId = new L2BridgeDomainId(l2FdId); + L2BridgeDomain l2Bd = new L2BridgeDomainBuilder().setId(l2BdId).setParent(l3Context.getId()).setName(name).build(); rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.l2BridgeDomainIid(tenantId, l2BdId), l2Bd, true); L2FloodDomain l2Fd = new L2FloodDomainBuilder().setId(l2FdId).setParent(l2BdId).setName(name).build(); rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.l2FloodDomainIid(tenantId, l2FdId), l2Fd, true); - NetworkMapping networkMapping = new NetworkMappingBuilder().setNetworkId(l2FdId) - .setL2BridgeDomainId(l2BdId) - .setL3ContextId(l3ContextId) - .build(); - rwTx.put(LogicalDatastoreType.OPERATIONAL, NeutronMapperIidFactory.networkMappingIid(l2FdId), networkMapping, - true); - if (!tenantsWithRouterAndNetworkSeviceEntities.contains(tenantId)) { tenantsWithRouterAndNetworkSeviceEntities.add(tenantId); NetworkService.writeNetworkServiceEntitiesToTenant(tenantId, rwTx); @@ -176,58 +96,12 @@ public class NeutronNetworkAware implements MappingProcessor networkMappingIid = NeutronMapperIidFactory.networkMappingIid(l2FdId); - Optional potentionalNetworkMapping = - DataStoreHelper.readFromDs(LogicalDatastoreType.OPERATIONAL, networkMappingIid, rwTx); - if (!potentionalNetworkMapping.isPresent()) { - LOG.warn("Illegal state - network-mapping {} does not exist.", l2FdId.getValue()); - rwTx.cancel(); - return; - } - - NetworkMapping networkMapping = potentionalNetworkMapping.get(); - L2BridgeDomainId l2BdId = networkMapping.getL2BridgeDomainId(); - L3ContextId l3ContextId = networkMapping.getL3ContextId(); - if (l2BdId == null || l3ContextId == null) { - LOG.warn("Illegal state - network-mapping {} is not valid.", networkMapping); - rwTx.cancel(); - return; - } - + TenantId tenantId = new TenantId(network.getTenantId().getValue()); + L2FloodDomainId l2FdId = new L2FloodDomainId(network.getUuid().getValue()); Optional potentialL2Fd = DataStoreHelper.removeIfExists(LogicalDatastoreType.CONFIGURATION, IidFactory.l2FloodDomainIid(tenantId, l2FdId), rwTx); if (!potentialL2Fd.isPresent()) { LOG.warn("Illegal state - l2-flood-domain {} does not exist.", l2FdId.getValue()); - rwTx.cancel(); return; } + L2BridgeDomainId l2BdId = new L2BridgeDomainId(l2FdId); Optional potentialL2Bd = DataStoreHelper.removeIfExists(LogicalDatastoreType.CONFIGURATION, IidFactory.l2BridgeDomainIid(tenantId, l2BdId), rwTx); if (!potentialL2Bd.isPresent()) { LOG.warn("Illegal state - l2-bridge-domain {} does not exist.", l2BdId.getValue()); - rwTx.cancel(); - return; - } - - Optional potentialL3Context = DataStoreHelper.removeIfExists(LogicalDatastoreType.CONFIGURATION, - IidFactory.l3ContextIid(tenantId, l3ContextId), rwTx); - if (!potentialL3Context.isPresent()) { - LOG.warn("Illegal state - l3-context {} does not exist.", l3ContextId.getValue()); - rwTx.cancel(); return; } - rwTx.delete(LogicalDatastoreType.OPERATIONAL, networkMappingIid); - DataStoreHelper.submitToDs(rwTx); } + } diff --git a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronNetworkDao.java b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronNetworkDao.java deleted file mode 100644 index a79631ee0..000000000 --- a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronNetworkDao.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.groupbasedpolicy.neutron.mapper.mapping; - -import java.util.HashSet; -import java.util.Set; - -import org.opendaylight.neutron.spi.NeutronNetwork; - -import com.google.common.base.Preconditions; - -public class NeutronNetworkDao { - - private final Set externalNetworks = new HashSet<>(); - - public void addNetwork(NeutronNetwork network) { - Preconditions.checkNotNull(network); - if (network.getRouterExternal() != null && network.getRouterExternal() == true) { - externalNetworks.add(network.getID()); - } - } - - /** - * Checks if neutron network is external - * @param networkId UUID of the network - * @return {@code true} if {@link NeutronNetwork#getRouterExternal()} is {@code true}; {@code false} otherwise - */ - public boolean isExternalNetwork(String networkId) { - return externalNetworks.contains(networkId); - } - -} diff --git a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronPortAware.java b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronPortAware.java index 84acfb80c..e8cede6ee 100644 --- a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronPortAware.java +++ b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronPortAware.java @@ -10,311 +10,211 @@ package org.opendaylight.groupbasedpolicy.neutron.mapper.mapping; import static com.google.common.base.Preconditions.checkNotNull; import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; +import java.util.Collections; import java.util.List; import java.util.Set; -import java.util.concurrent.ExecutionException; + +import javax.annotation.Nullable; import org.opendaylight.controller.md.sal.binding.api.DataBroker; -import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction; import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction; import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; import org.opendaylight.groupbasedpolicy.neutron.gbp.util.NeutronGbpIidFactory; +import org.opendaylight.groupbasedpolicy.neutron.mapper.EndpointRegistrator; import org.opendaylight.groupbasedpolicy.neutron.mapper.infrastructure.NetworkClient; import org.opendaylight.groupbasedpolicy.neutron.mapper.infrastructure.NetworkService; -import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.group.NeutronSecurityGroupAware; -import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.rule.NeutronSecurityRuleAware; -import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils; -import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils.ForwardingCtx; -import org.opendaylight.groupbasedpolicy.neutron.mapper.util.Utils; +import org.opendaylight.groupbasedpolicy.neutron.mapper.util.PortUtils; +import org.opendaylight.groupbasedpolicy.neutron.mapper.util.SubnetUtils; import org.opendaylight.groupbasedpolicy.util.DataStoreHelper; import org.opendaylight.groupbasedpolicy.util.IidFactory; -import org.opendaylight.neutron.spi.NeutronPort; -import org.opendaylight.neutron.spi.NeutronPort_AllowedAddressPairs; -import org.opendaylight.neutron.spi.NeutronPort_ExtraDHCPOption; -import org.opendaylight.neutron.spi.NeutronPort_VIFDetail; -import org.opendaylight.neutron.spi.NeutronRouter; -import org.opendaylight.neutron.spi.NeutronRouter_Interface; -import org.opendaylight.neutron.spi.NeutronSecurityGroup; -import org.opendaylight.neutron.spi.NeutronSecurityRule; -import org.opendaylight.neutron.spi.Neutron_IPs; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.EndpointGroupId; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2BridgeDomainId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2FloodDomainId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L3ContextId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.NetworkDomainId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.SubnetId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.UniqueId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.EndpointService; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterEndpointInput; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterEndpointInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterL3PrefixEndpointInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterL3PrefixEndpointInputBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.UnregisterEndpointInput; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.UnregisterEndpointInputBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoint.fields.L3Address; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoint.fields.L3AddressBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoint.l3.prefix.fields.EndpointL3Gateways; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoint.l3.prefix.fields.EndpointL3GatewaysBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.Endpoint; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointL3; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointL3Builder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointL3Key; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointL3PrefixKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.unregister.endpoint.input.L2; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.unregister.endpoint.input.L2Builder; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.unregister.endpoint.input.L3; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.unregister.endpoint.input.L3Builder; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.mappings.gbp.by.neutron.mappings.endpoints.by.ports.EndpointByPort; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.mappings.neutron.by.gbp.mappings.external.gateways.as.l3.endpoints.ExternalGatewayAsL3Endpoint; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.mappings.neutron.by.gbp.mappings.ports.by.endpoints.PortByEndpoint; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.EndpointGroup; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.binding.rev150712.PortBindingExtension; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.binding.rev150712.binding.attributes.VifDetails; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.AllowedAddressPairs; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.ExtraDhcpOpts; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2BridgeDomain; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2BridgeDomainBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.FixedIps; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.Ports; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -import org.opendaylight.yangtools.yang.common.RpcResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.base.Function; import com.google.common.base.Optional; -import com.google.common.base.Strings; -import com.google.common.collect.Collections2; import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -public class NeutronPortAware implements MappingProcessor { +public class NeutronPortAware implements NeutronAware { - public static final Logger LOG = LoggerFactory.getLogger(NeutronPortAware.class); - private static final String DEVICE_OWNER_DHCP = "network:dhcp"; - private static final String DEVICE_OWNER_ROUTER_IFACE = "network:router_interface"; - private static final String DEVICE_OWNER_ROUTER_GATEWAY = "network:router_gateway"; - private static final String DEVICE_OWNER_FLOATING_IP = "network:floatingip"; + private static final Logger LOG = LoggerFactory.getLogger(NeutronPortAware.class); + public static final InstanceIdentifier PORT_WILDCARD_IID = + InstanceIdentifier.builder(Neutron.class).child(Ports.class).child(Port.class).build(); private final DataBroker dataProvider; - private final EndpointService epService; - private final NeutronSecurityRuleAware secRuleAware; - private final NeutronSecurityGroupAware secGrpAware; + private final EndpointRegistrator epRegistrator; - public NeutronPortAware(DataBroker dataProvider, EndpointService epService, NeutronSecurityRuleAware secRuleAware, NeutronSecurityGroupAware secGrpAware) { + public NeutronPortAware(DataBroker dataProvider, EndpointRegistrator epRegistrator) { this.dataProvider = checkNotNull(dataProvider); - this.epService = checkNotNull(epService); - this.secRuleAware = checkNotNull(secRuleAware); - this.secGrpAware = secGrpAware; + this.epRegistrator = checkNotNull(epRegistrator); } @Override - public NeutronPort convertToNeutron(Port port) { - return toNeutron(port); - } - - static NeutronPort toNeutron(Port port) { - NeutronPort result = new NeutronPort(); - result.setAdminStateUp(port.isAdminStateUp()); - if (port.getAllowedAddressPairs() != null) { - List pairs = new ArrayList(); - for (AllowedAddressPairs mdPair : port.getAllowedAddressPairs()) { - NeutronPort_AllowedAddressPairs pair = new NeutronPort_AllowedAddressPairs(); - pair.setIpAddress(mdPair.getIpAddress()); - pair.setMacAddress(mdPair.getMacAddress()); - pairs.add(pair); + public void onCreated(Port port, Neutron neutron) { + LOG.trace("created port - {}", port); + if (PortUtils.isRouterInterfacePort(port)) { + LOG.trace("Port is router interface port: {}", port.getUuid().getValue()); + // router interface port can have only one IP + Optional potentialPortIpWithSubnet = PortUtils.resolveFirstFixedIps(port); + if (!potentialPortIpWithSubnet.isPresent()) { + LOG.warn("Illegal state - router interface port does not contain fixed IPs {}", + port); + return; } - result.setAllowedAddressPairs(pairs); - } - result.setDeviceID(port.getDeviceId()); - result.setDeviceOwner(port.getDeviceOwner()); - if (port.getExtraDhcpOpts() != null) { - List options = new ArrayList(); - for (ExtraDhcpOpts opt : port.getExtraDhcpOpts()) { - NeutronPort_ExtraDHCPOption arg = new NeutronPort_ExtraDHCPOption(); - arg.setName(opt.getOptName()); - arg.setValue(opt.getOptValue()); - arg.setIpVersion(NeutronSubnetAware.IPV_MAP.get(opt.getIpVersion())); - options.add(arg); + FixedIps portIpWithSubnet = potentialPortIpWithSubnet.get(); + L3ContextId routerL3Context = new L3ContextId(port.getDeviceId()); + // change L3Context for all EPs with same subnet as router port + changeL3ContextForEpsInSubnet(portIpWithSubnet.getSubnetId(), neutron.getPorts(), routerL3Context); + // set L3Context as parent for bridge domain which is parent of subnet + TenantId tenantId = new TenantId(port.getTenantId().getValue()); + Optional potentialRouterPortSubnet = SubnetUtils.findSubnet(portIpWithSubnet.getSubnetId(), neutron.getSubnets()); + if (!potentialRouterPortSubnet.isPresent()) { + LOG.warn("Illegal state - router interface port is in subnet which does not exist. {}", + port); + return; } - result.setExtraDHCPOptions(options); - } - if (port.getFixedIps() != null) { - List ips = new ArrayList(); - for (FixedIps mdIP : port.getFixedIps()) { - Neutron_IPs ip = new Neutron_IPs(); - ip.setIpAddress(String.valueOf(mdIP.getIpAddress().getValue())); - ip.setSubnetUUID(mdIP.getSubnetId().getValue()); - ips.add(ip); + ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction(); + Subnet routerPortSubnet = potentialRouterPortSubnet.get(); + L2BridgeDomainId l2BdId = new L2BridgeDomainId(routerPortSubnet.getNetworkId().getValue()); + L2BridgeDomain l2Bd = new L2BridgeDomainBuilder().setId(l2BdId).setParent(routerL3Context).build(); + rwTx.merge(LogicalDatastoreType.CONFIGURATION, IidFactory.l2BridgeDomainIid(tenantId, l2BdId), l2Bd); + // set virtual router IP for subnet + org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.Subnet subnet = + NeutronSubnetAware.createSubnet(routerPortSubnet, portIpWithSubnet.getIpAddress()); + rwTx.merge(LogicalDatastoreType.CONFIGURATION, IidFactory.subnetIid(tenantId, subnet.getId()), subnet); + DataStoreHelper.submitToDs(rwTx); + } else if (PortUtils.isDhcpPort(port)) { + // process as normal port but put it to DHCP group + LOG.trace("Port is DHCP port: {}", port.getUuid().getValue()); + Optional firstFixedIps = PortUtils.resolveFirstFixedIps(port); + if (!firstFixedIps.isPresent()) { + LOG.warn("DHCP port does not have an IP address. {}", port); + return; } - result.setFixedIPs(ips); - } - result.setMacAddress(port.getMacAddress()); - result.setName(port.getName()); - result.setNetworkUUID(port.getNetworkId().getValue()); - if(port.getSecurityGroups() != null) { - result.setSecurityGroups(Lists.transform(port.getSecurityGroups(), - new Function() { - - @Override - public NeutronSecurityGroup apply(Uuid uuid) { - NeutronSecurityGroup sg = new NeutronSecurityGroup(); - sg.setID(uuid.getValue()); - return sg; - } - })); - } - result.setStatus(port.getStatus()); - if (port.getTenantId() != null) { - result.setTenantID(port.getTenantId()); - } - result.setID(port.getUuid().getValue()); - addExtensions(port, result); - return result; - } - - protected static void addExtensions(Port port, NeutronPort result) { - PortBindingExtension binding = port.getAugmentation(PortBindingExtension.class); - result.setBindinghostID(binding.getHostId()); - if (binding.getVifDetails() != null) { - List details = new ArrayList(); - for (VifDetails vifDetail : binding.getVifDetails()) { - NeutronPort_VIFDetail detail = new NeutronPort_VIFDetail(); - detail.setPortFilter(vifDetail.isPortFilter()); - detail.setOvsHybridPlug(vifDetail.isOvsHybridPlug()); - details.add(detail); + RegisterEndpointInputBuilder epInBuilder = createBasicEndpointInputBuilder(port); + // endpoint has only one network containment therefore only first IP is used + FixedIps ipWithSubnet = firstFixedIps.get(); + epInBuilder.setNetworkContainment(new SubnetId(ipWithSubnet.getSubnetId().getValue())); + L3Address l3Address = new L3AddressBuilder().setL3Context(new L3ContextId(port.getNetworkId().getValue())) + .setIpAddress(ipWithSubnet.getIpAddress()) + .build(); + epInBuilder.setL3Address(ImmutableList.of(l3Address)); + List epgsFromSecGroups = resolveEpgIdsFromSecGroups(port.getSecurityGroups()); + epgsFromSecGroups.add(NetworkService.EPG_ID); + epInBuilder.setEndpointGroups(epgsFromSecGroups); + registerEndpointAndStoreMapping(epInBuilder.build(), port); + } else if (PortUtils.isNormalPort(port)) { + LOG.trace("Port is normal port: {}", port.getUuid().getValue()); + RegisterEndpointInputBuilder epInBuilder = createBasicEndpointInputBuilder(port); + Optional firstFixedIps = PortUtils.resolveFirstFixedIps(port); + if (firstFixedIps.isPresent()) { + // endpoint has only one network containment therefore only first IP is used + FixedIps ipWithSubnet = firstFixedIps.get(); + epInBuilder.setNetworkContainment(new SubnetId(ipWithSubnet.getSubnetId().getValue())); + L3Address l3Address = resolveL3AddressFromPort(port, ipWithSubnet, neutron); + epInBuilder.setL3Address(ImmutableList.of(l3Address)); + } else { + epInBuilder.setNetworkContainment(new L2FloodDomainId(port.getNetworkId().getValue())); } - result.setVIFDetail(details); - } - result.setBindingvifType(binding.getVifType()); - result.setBindingvnicType(binding.getVnicType()); - } - - @Override - public int canCreate(NeutronPort port) { - LOG.trace("canCreate port - {}", port); - // TODO Li msunal this has to be rewrite when OFOverlay renderer will support l3-endpoints. - List fixedIPs = port.getFixedIPs(); - if (fixedIPs != null && fixedIPs.size() > 1) { - LOG.warn("Neutron mapper does not support multiple IPs on the same port."); - return StatusCode.BAD_REQUEST; - } - NeutronRouter router = (isRouterGatewayPort(port) || isRouterInterfacePort(port)) ? NeutronRouterAware.getRouterForPort(port.getDeviceID()) : null; - if (router != null) { - return NeutronRouterAware.canAttachInterface(router, createNeutronRouter_InterfaceFrom(port), dataProvider); - } - return StatusCode.OK; - } - - private static NeutronRouter_Interface createNeutronRouter_InterfaceFrom(NeutronPort port) { - NeutronRouter_Interface nri = new NeutronRouter_Interface(); - if (port.getID() != null) { - nri.setID(port.getID()); - nri.setPortUUID(port.getID()); - } - if (port.getTenantID() != null) { - nri.setTenantID(port.getTenantID()); - } - if (port.getFixedIPs() != null && port.getFixedIPs().size() == 1) { - // supported case - nri.setSubnetUUID(port.getFixedIPs().get(0).getSubnetUUID()); + List epgsFromSecGroups = resolveEpgIdsFromSecGroups(port.getSecurityGroups()); + epgsFromSecGroups.add(NetworkClient.EPG_ID); + epInBuilder.setEndpointGroups(epgsFromSecGroups); + registerEndpointAndStoreMapping(epInBuilder.build(), port); + } else if (PortUtils.isRouterGatewayPort(port)) { + // do nothing because actual trigger is attaching of port to router + LOG.trace("Port is router gateway port: {}", port.getUuid().getValue()); + } else if (PortUtils.isFloatingIpPort(port)) { + // do nothing because trigger is floating IP + LOG.trace("Port is floating ip: {}", port.getUuid().getValue()); + } else { + LOG.warn("Unknown port: {}", port); } - return nri; } - @Override - public void created(NeutronPort port) { - LOG.trace("created port - {}", port); - if (isRouterInterfacePort(port) || isRouterGatewayPort(port)) { - NeutronRouter router = NeutronRouterAware.getRouterForPort(port.getDeviceID()); - if (router != null) { - NeutronRouterAware.neutronRouterInterfaceAttached(router, createNeutronRouter_InterfaceFrom(port), - dataProvider, epService); - return; - } - } - if (isFloatingIpPort(port)) { - LOG.trace("Port is floating ip - {} device id - {}", port.getID(), port.getDeviceID()); - return; - } - ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction(); - TenantId tenantId = new TenantId(Utils.normalizeUuid(port.getTenantID())); - if (isDhcpPort(port)) { - LOG.trace("Port is DHCP port. - {}", port.getID()); - Neutron_IPs firstIp = MappingUtils.getFirstIp(port.getFixedIPs()); - if (firstIp == null) { - LOG.warn("Illegal state - DHCP port does not have an IP address."); - rwTx.cancel(); - return; - } - } else { - // this is here b/c stable/kilo sends sec-groups only with port - List secGroups = port.getSecurityGroups(); - if (secGroups != null) { - for (NeutronSecurityGroup secGroup : secGroups) { - EndpointGroupId epgId = new EndpointGroupId(secGroup.getSecurityGroupUUID()); - Optional potentialEpg = DataStoreHelper.readFromDs(LogicalDatastoreType.CONFIGURATION, - IidFactory.endpointGroupIid(tenantId, epgId), rwTx); - if (!potentialEpg.isPresent()) { - boolean isSecGroupCreated = secGrpAware.addNeutronSecurityGroup(secGroup, rwTx); - if (!isSecGroupCreated) { - rwTx.cancel(); - return; - } - } else { - List secRules = secGroup.getSecurityRules(); - if (secRules != null) { - for (NeutronSecurityRule secRule : secRules) { - secRuleAware.addNeutronSecurityRule(secRule, rwTx); - } - } - } + private void changeL3ContextForEpsInSubnet(Uuid subnetUuid, Ports ports, L3ContextId newl3Context) { + Set portsInSameSubnet = PortUtils.findPortsBySubnet(subnetUuid, ports); + for (Port portInSameSubnet : portsInSameSubnet) { + if (PortUtils.isNormalPort(portInSameSubnet) || PortUtils.isDhcpPort(portInSameSubnet)) { + // endpoints are created only from neutron normal port or DHCP port + Optional firstFixedIps = PortUtils.resolveFirstFixedIps(portInSameSubnet); + if (firstFixedIps.isPresent()) { + // endpoint has only one network containment therefore only first IP is used + FixedIps ipWithSubnet = firstFixedIps.get(); + RegisterEndpointInputBuilder epInBuilder = createBasicEndpointInputBuilder(portInSameSubnet); + epInBuilder.setNetworkContainment(new SubnetId(ipWithSubnet.getSubnetId().getValue())); + L3Address l3Address = new L3AddressBuilder().setL3Context(newl3Context) + .setIpAddress(ipWithSubnet.getIpAddress()) + .build(); + epInBuilder.setL3Address(ImmutableList.of(l3Address)); + List epgsFromSecGroups = + resolveEpgIdsFromSecGroups(portInSameSubnet.getSecurityGroups()); + epgsFromSecGroups.add(NetworkClient.EPG_ID); + epRegistrator.registerEndpoint(epInBuilder.build()); + // unregister L3EP + L3ContextId oldL3Context = new L3ContextId(portInSameSubnet.getNetworkId().getValue()); + L3 l3 = new L3Builder().setL3Context(oldL3Context).setIpAddress(ipWithSubnet.getIpAddress()) + .build(); + UnregisterEndpointInput epUnreg = new UnregisterEndpointInputBuilder().setL3(ImmutableList.of(l3)).build(); + epRegistrator.unregisterEndpoint(epUnreg); } } } - boolean isNeutronPortCreated = addNeutronPort(port, rwTx, epService); - if (!isNeutronPortCreated) { - rwTx.cancel(); - return; - } + } - DataStoreHelper.submitToDs(rwTx); + private static RegisterEndpointInputBuilder createBasicEndpointInputBuilder(Port port) { + return new RegisterEndpointInputBuilder().setL2Context(new L2BridgeDomainId(port.getNetworkId().getValue())) + .setMacAddress(new MacAddress(port.getMacAddress())) + .setTenant(new TenantId(port.getTenantId().getValue())) + .setTimestamp(System.currentTimeMillis()); } - public static boolean addNeutronPort(NeutronPort port, ReadWriteTransaction rwTx, EndpointService epService) { - TenantId tenantId = new TenantId(Utils.normalizeUuid(port.getTenantID())); - L2FloodDomainId l2FdId = new L2FloodDomainId(port.getNetworkUUID()); - ForwardingCtx fwCtx = MappingUtils.createForwardingContext(tenantId, l2FdId, rwTx); - boolean isFwCtxValid = validateForwardingCtx(fwCtx); - if (!isFwCtxValid) { - return false; + private static List resolveEpgIdsFromSecGroups(@Nullable List securityGroups) { + List epgIds = new ArrayList<>(); + if ((securityGroups == null || securityGroups.isEmpty())) { + return epgIds; } - EndpointKey epKey = new EndpointKey(fwCtx.getL2BridgeDomain().getId(), new MacAddress(port.getMacAddress())); - addNeutronGbpMapping(port, epKey, rwTx); - try { - RegisterEndpointInput registerEpRpcInput = createRegisterEndpointInput(port, fwCtx); - RpcResult rpcResult = epService.registerEndpoint(registerEpRpcInput).get(); - if (!rpcResult.isSuccessful()) { - LOG.warn("Illegal state - RPC registerEndpoint failed. Input of RPC: {}", registerEpRpcInput); - return false; - } - } catch (InterruptedException | ExecutionException e) { - LOG.error("addNeutronPort failed. {}", port, e); - return false; + for (Uuid secGrp : securityGroups) { + epgIds.add(new EndpointGroupId(secGrp.getValue())); } - return true; + return epgIds; } - private static void addNeutronGbpMapping(NeutronPort port, EndpointKey epKey, ReadWriteTransaction rwTx) { - UniqueId portId = new UniqueId(port.getID()); - if (!isRouterInterfacePort(port) && !isRouterGatewayPort(port) && !isFloatingIpPort(port)) { - LOG.trace("Adding Port-Endpoint mapping for port {} (device owner {}) and endpoint {}", port.getID(), - port.getDeviceOwner(), epKey); + private void registerEndpointAndStoreMapping(RegisterEndpointInput regEpInput, Port port) { + boolean isRegisteredEndpoint = epRegistrator.registerEndpoint(regEpInput); + if (isRegisteredEndpoint) { + ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction(); + UniqueId portId = new UniqueId(port.getUuid().getValue()); + EndpointKey epKey = new EndpointKey(new L2BridgeDomainId(port.getNetworkId().getValue()), + new MacAddress(port.getMacAddress())); + LOG.trace("Adding Port-Endpoint mapping for port {} (device owner {}) and endpoint {}", + port.getUuid().getValue(), port.getDeviceOwner(), epKey); EndpointByPort endpointByPort = MappingFactory.createEndpointByPort(epKey, portId); rwTx.put(LogicalDatastoreType.OPERATIONAL, NeutronGbpIidFactory.endpointByPortIid(portId), endpointByPort, true); @@ -322,412 +222,123 @@ public class NeutronPortAware implements MappingProcessor { rwTx.put(LogicalDatastoreType.OPERATIONAL, NeutronGbpIidFactory.portByEndpointIid(epKey.getL2Context(), epKey.getMacAddress()), portByEndpoint, true); + DataStoreHelper.submitToDs(rwTx); } } - public static boolean addL3EndpointForExternalGateway(TenantId tenantId, L3ContextId l3ContextId, - IpAddress ipAddress, NetworkDomainId networkContainment, ReadWriteTransaction rwTx) { - - EndpointL3Key epL3Key = new EndpointL3Key(ipAddress, l3ContextId); - addNeutronExtGwGbpMapping(epL3Key, rwTx); - List epgIds = new ArrayList<>(); - epgIds.add(MappingUtils.EPG_EXTERNAL_ID); - EndpointL3 epL3 = createL3Endpoint(tenantId, epL3Key, epgIds, networkContainment); - InstanceIdentifier iid_l3 = IidFactory.l3EndpointIid(l3ContextId, ipAddress); - rwTx.put(LogicalDatastoreType.OPERATIONAL, iid_l3, epL3, true); - return true; - } - - private static void addNeutronExtGwGbpMapping(EndpointL3Key epL3Key, ReadWriteTransaction rwTx) { - ExternalGatewayAsL3Endpoint externalGatewayL3Endpoint = MappingFactory.createExternalGatewayByL3Endpoint(epL3Key); - rwTx.put(LogicalDatastoreType.OPERATIONAL, NeutronGbpIidFactory.externalGatewayAsL3Endpoint(epL3Key.getL3Context(), epL3Key.getIpAddress()), - externalGatewayL3Endpoint, true); - } - - public static boolean addL3PrefixEndpoint(L3ContextId l3ContextId, IpPrefix ipPrefix, IpAddress ipAddress, TenantId tenantId, - EndpointService epService) { - EndpointL3PrefixKey epL3PrefixKey = new EndpointL3PrefixKey( ipPrefix, l3ContextId); - EndpointL3Key epL3Key = null; - List l3Gateways = new ArrayList<>(); - if (ipAddress != null) { - epL3Key = new EndpointL3Key(ipAddress, l3ContextId); - l3Gateways.add(epL3Key); - } - try { - RegisterL3PrefixEndpointInput registerL3PrefixEpRpcInput = createRegisterL3PrefixEndpointInput(epL3PrefixKey, l3Gateways,tenantId); - - RpcResult rpcResult = epService.registerL3PrefixEndpoint(registerL3PrefixEpRpcInput).get(); - if (!rpcResult.isSuccessful()) { - LOG.warn("Illegal state - RPC registerEndpoint failed. Input of RPC: {}", registerL3PrefixEpRpcInput); - return false; - } - } catch (InterruptedException | ExecutionException e) { - LOG.error("addPort - RPC invocation failed.", e); - return false; - } - return true; - - } - - private static boolean validateForwardingCtx(ForwardingCtx fwCtx) { - if (fwCtx.getL2FloodDomain() == null) { - LOG.warn("Illegal state - l2-flood-domain does not exist."); - return false; - } - if (fwCtx.getL2BridgeDomain() == null) { - LOG.warn("Illegal state - l2-bridge-domain does not exist."); - return false; - } - if (fwCtx.getL3Context() == null) { - LOG.warn("Illegal state - l3-context does not exist."); - return false; - } - return true; - } - @Override - public int canUpdate(NeutronPort delta, NeutronPort original) { - LOG.trace("catUpdate port - delta: {} original: {}", delta, original); - if (delta.getFixedIPs() == null || delta.getFixedIPs().isEmpty()) { - return StatusCode.OK; - } - // TODO Li msunal this has to be rewrite when OFOverlay renderer will support l3-endpoints. - List fixedIPs = delta.getFixedIPs(); - if (fixedIPs != null && fixedIPs.size() > 1) { - LOG.warn("Neutron mapper does not support multiple IPs on the same port."); - return StatusCode.BAD_REQUEST; - } - boolean wasRouterPort = isRouterGatewayPort(original) || isRouterInterfacePort(original); - boolean isRouterPort = isRouterGatewayPort(delta) || isRouterInterfacePort(delta); - if (wasRouterPort || isRouterPort) { - NeutronRouter router = NeutronRouterAware.getRouterForPort(delta.getDeviceID()); - if (router != null && !wasRouterPort && isRouterPort) { - return NeutronRouterAware. - canAttachInterface(router, createNeutronRouter_InterfaceFrom(delta), dataProvider); - } else if (router != null && wasRouterPort && !isRouterPort) { - return NeutronRouterAware.canDetachInterface(router, createNeutronRouter_InterfaceFrom(delta)); - } - } - return StatusCode.OK; + public void onUpdated(Port oldPort, Port newPort, Neutron oldNeutron, Neutron newNeutron) { + LOG.trace("updated port - OLD: {}\nNEW: {}", oldPort, newPort); + onDeleted(oldPort, oldNeutron, newNeutron); + onCreated(newPort, newNeutron); } @Override - public void updated(NeutronPort port) { - LOG.trace("updated port - {}", port); - NeutronPort original = null; - Ports ports = NeutronListener.getNeutronDataBefore().getPorts(); - boolean wasRouterPort = false; - if (ports != null) { - for (Port p : ports.getPort()) { - if (p.getUuid().getValue().equals(port.getID())) { - original = toNeutron(p); - wasRouterPort = isRouterGatewayPort(original) || isRouterInterfacePort(original); - } - } - } - boolean isRouterPort = isRouterGatewayPort(port) || isRouterInterfacePort(port); - if (original != null && (wasRouterPort || isRouterPort)) { - NeutronRouter router = NeutronRouterAware.getRouterForPort(port.getDeviceID()); - if (router != null && (!wasRouterPort && isRouterPort)) { - NeutronRouterAware.neutronRouterInterfaceAttached(router, createNeutronRouter_InterfaceFrom(port), - dataProvider, epService); - return; - } else if (router != null && (wasRouterPort && !isRouterPort)) { - NeutronRouterAware.neutronRouterInterfaceAttached(router, createNeutronRouter_InterfaceFrom(port), - dataProvider, epService); - return; - } - } - if (isFloatingIpPort(port)) { - LOG.trace("Port is floating ip - {}", port.getID()); - return; - } - if (Strings.isNullOrEmpty(port.getTenantID())) { - LOG.trace("REMOVE ME: Tenant is null - {}", port.getID()); - return; - } - - ReadOnlyTransaction rTx = dataProvider.newReadOnlyTransaction(); - TenantId tenantId = new TenantId(Utils.normalizeUuid(port.getTenantID())); - MacAddress macAddress = new MacAddress(port.getMacAddress()); - L2FloodDomainId l2FdId = new L2FloodDomainId(port.getNetworkUUID()); - ForwardingCtx fwCtx = MappingUtils.createForwardingContext(tenantId, l2FdId, rTx); - boolean isFwCtxValid = validateForwardingCtx(fwCtx); - if (!isFwCtxValid) { - rTx.close(); - return; - } - - Optional potentionalEp = DataStoreHelper.readFromDs(LogicalDatastoreType.OPERATIONAL, - IidFactory.endpointIid(fwCtx.getL2BridgeDomain().getId(), macAddress), rTx); - if (!potentionalEp.isPresent()) { - LOG.warn("Illegal state - endpoint {} does not exist.", new EndpointKey(fwCtx.getL2BridgeDomain().getId(), - macAddress)); - rTx.close(); - return; - } - - Endpoint ep = potentionalEp.get(); - if (isEpIpDifferentThanPortFixedIp(ep, port) || isEpgDifferentThanSecGrp(ep, port)) { - UnregisterEndpointInput unregisterEpRpcInput = createUnregisterEndpointInput(ep); - RegisterEndpointInput registerEpRpcInput = createRegisterEndpointInput(port, fwCtx); - try { - RpcResult rpcResult = epService.unregisterEndpoint(unregisterEpRpcInput).get(); - if (!rpcResult.isSuccessful()) { - LOG.warn("Illegal state - RPC unregisterEndpoint failed. Input of RPC: {}", unregisterEpRpcInput); - rTx.close(); - return; - } - rpcResult = epService.registerEndpoint(registerEpRpcInput).get(); - if (!rpcResult.isSuccessful()) { - LOG.warn("Illegal state - RPC registerEndpoint failed. Input of RPC: {}", registerEpRpcInput); - rTx.close(); - return; - } - } catch (InterruptedException | ExecutionException e) { - LOG.error("addPort - RPC invocation failed.", e); - rTx.close(); + public void onDeleted(Port port, Neutron oldNeutron, Neutron newNeutron) { + LOG.trace("deleted port - {}", port); + if (PortUtils.isRouterInterfacePort(port)) { + LOG.trace("Port is router interface port: {}", port.getUuid().getValue()); + // router interface port can have only one IP + Optional potentialPortIpWithSubnet = PortUtils.resolveFirstFixedIps(port); + if (!potentialPortIpWithSubnet.isPresent()) { + LOG.warn("Illegal state - router interface port does not contain fixed IPs {}", + port); return; } - } - rTx.close(); - } - - private boolean isEpIpDifferentThanPortFixedIp(Endpoint ep, NeutronPort port) { - List l3Addresses = ep.getL3Address(); - List fixedIPs = port.getFixedIPs(); - if ((l3Addresses == null || l3Addresses.isEmpty()) && (fixedIPs == null || fixedIPs.isEmpty())) { - return false; - } - if (l3Addresses != null && !l3Addresses.isEmpty() && fixedIPs != null && !fixedIPs.isEmpty()) { - if (fixedIPs.get(0).getIpAddress().equals(Utils.getStringIpAddress(l3Addresses.get(0).getIpAddress()))) { - return false; - } - } - return true; - } - - private boolean isEpgDifferentThanSecGrp(Endpoint ep, NeutronPort port) { - List epgIds = ep.getEndpointGroups(); - List secGroups = port.getSecurityGroups(); - if ((epgIds == null || epgIds.isEmpty()) && (secGroups == null || secGroups.isEmpty())) { - return false; - } - if (epgIds != null && !epgIds.isEmpty() && secGroups != null && !secGroups.isEmpty()) { - if (epgIds.size() != secGroups.size()) { - return true; - } - Collection epgIdsFromSecGroups = Collections2.transform(secGroups, - new Function() { - - @Override - public EndpointGroupId apply(NeutronSecurityGroup input) { - return new EndpointGroupId(input.getSecurityGroupUUID()); - } - }); - // order independent equals - Set one = new HashSet<>(epgIds); - Set two = new HashSet<>(epgIdsFromSecGroups); - if (one.equals(two)) { - return false; - } - } - return true; - } - - @Override - public int canDelete(NeutronPort port) { - LOG.trace("canDelete port - {}", port); - NeutronRouter router = (isRouterGatewayPort(port) || isRouterInterfacePort(port)) ? NeutronRouterAware.getRouterForPort(port.getDeviceID()) : null; - if (router != null) { - return NeutronRouterAware.canDetachInterface(router, createNeutronRouter_InterfaceFrom(port)); - } - return StatusCode.OK; - } - - @Override - public void deleted(NeutronPort port) { - LOG.trace("deleted port - {}", port); - if (isRouterInterfacePort(port) || isRouterGatewayPort(port)) { - NeutronRouter router = NeutronRouterAware.getRouterForPort(port.getDeviceID()); - if (router != null) { - NeutronRouterAware.neutronRouterInterfaceDetached(router, createNeutronRouter_InterfaceFrom(port), - dataProvider, epService); + FixedIps portIpWithSubnet = potentialPortIpWithSubnet.get(); + L3ContextId l3Context = new L3ContextId(port.getNetworkId().getValue()); + // change L3Context for all EPs with same subnet as router port + changeL3ContextForEpsInSubnet(portIpWithSubnet.getSubnetId(), oldNeutron.getPorts(), l3Context); + // set L3Context as parent for bridge domain which is parent of subnet + TenantId tenantId = new TenantId(port.getTenantId().getValue()); + Optional potentialRouterPortSubnet = SubnetUtils.findSubnet(portIpWithSubnet.getSubnetId(), oldNeutron.getSubnets()); + if (!potentialRouterPortSubnet.isPresent()) { + LOG.warn("Illegal state - router interface port is in subnet which does not exist. {}", + port); return; } - } - if (isFloatingIpPort(port)) { - LOG.trace("Port is floating ip - {} device id - {}", port.getID(), port.getDeviceID()); - return; - } - ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction(); - TenantId tenantId = new TenantId(Utils.normalizeUuid(port.getTenantID())); - L2FloodDomainId l2FdId = new L2FloodDomainId(port.getNetworkUUID()); - ForwardingCtx fwCtx = MappingUtils.createForwardingContext(tenantId, l2FdId, rwTx); - boolean isFwCtxValid = validateForwardingCtx(fwCtx); - if (!isFwCtxValid) { - rwTx.cancel(); - return; - } - - UnregisterEndpointInput unregisterEpRpcInput = createUnregisterEndpointInput(port, fwCtx); - boolean isEndpointUnregistered = false; - try { - isEndpointUnregistered = epService.unregisterEndpoint(unregisterEpRpcInput).get().isSuccessful(); - } catch (InterruptedException | ExecutionException e) { - LOG.error("unregisterEndpoint - RPC invocation failed.", e); - } - if (isEndpointUnregistered) { - EndpointKey epKey = new EndpointKey(fwCtx.getL2BridgeDomain().getId(), new MacAddress(port.getMacAddress())); - deleteNeutronGbpMapping(port, epKey, rwTx); + ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction(); + Subnet routerPortSubnet = potentialRouterPortSubnet.get(); + L2BridgeDomainId l2BdId = new L2BridgeDomainId(routerPortSubnet.getNetworkId().getValue()); + L2BridgeDomain l2Bd = new L2BridgeDomainBuilder().setId(l2BdId).setParent(l3Context).build(); + rwTx.merge(LogicalDatastoreType.CONFIGURATION, IidFactory.l2BridgeDomainIid(tenantId, l2BdId), l2Bd); + // remove virtual router IP for subnet + org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.Subnet subnet = + NeutronSubnetAware.createSubnet(routerPortSubnet, null); + rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.subnetIid(tenantId, subnet.getId()), subnet); DataStoreHelper.submitToDs(rwTx); + } else if (PortUtils.isDhcpPort(port)) { + LOG.trace("Port is DHCP port: {}", port.getUuid().getValue()); + UnregisterEndpointInput unregEpInput = createUnregisterEndpointInput(port, oldNeutron); + unregisterEndpointAndRemoveMapping(unregEpInput, port); + } else if (PortUtils.isNormalPort(port)) { + LOG.trace("Port is normal port: {}", port.getUuid().getValue()); + UnregisterEndpointInput unregEpInput = createUnregisterEndpointInput(port, oldNeutron); + unregisterEndpointAndRemoveMapping(unregEpInput, port); + } else if (PortUtils.isRouterGatewayPort(port)) { + // do nothing because actual trigger is detaching of port from router + LOG.trace("Port is router gateway port: {}", port.getUuid().getValue()); + } else if (PortUtils.isFloatingIpPort(port)) { + // do nothing because trigger is floating IP + LOG.trace("Port is floating ip: {}", port.getUuid().getValue()); } else { - LOG.warn("Illegal state - RPC unregisterEndpoint failed. Input of RPC: {}", unregisterEpRpcInput); - rwTx.cancel(); - } - } - - private static void deleteNeutronGbpMapping(NeutronPort port, EndpointKey epKey, ReadWriteTransaction rwTx) { - UniqueId portId = new UniqueId(port.getID()); - if (!isRouterInterfacePort(port) && !isRouterGatewayPort(port) && !isFloatingIpPort(port)) { - LOG.trace("Adding Port-Endpoint mapping for port {} (device owner {}) and endpoint {}", port.getID(), - port.getDeviceOwner(), epKey); - DataStoreHelper.removeIfExists(LogicalDatastoreType.OPERATIONAL, - NeutronGbpIidFactory.endpointByPortIid(portId), rwTx); - DataStoreHelper.removeIfExists(LogicalDatastoreType.OPERATIONAL, - NeutronGbpIidFactory.portByEndpointIid(epKey.getL2Context(), epKey.getMacAddress()), rwTx); - } - } - - private static RegisterL3PrefixEndpointInput createRegisterL3PrefixEndpointInput(EndpointL3PrefixKey key, List endpointL3Keys, TenantId tenantId) { - List l3Gateways = new ArrayList(); - for (EndpointL3Key epL3Key : endpointL3Keys) { - EndpointL3Gateways l3Gateway = new EndpointL3GatewaysBuilder().setIpAddress(epL3Key.getIpAddress()) - .setL3Context(epL3Key.getL3Context()) - .build(); - l3Gateways.add(l3Gateway); + LOG.warn("Unknown port: {}", port); } - RegisterL3PrefixEndpointInputBuilder inputBuilder = new RegisterL3PrefixEndpointInputBuilder() - .setL3Context(key.getL3Context()) - .setIpPrefix(key.getIpPrefix()) - .setEndpointGroup(MappingUtils.EPG_EXTERNAL_ID) - .setTenant(tenantId) - .setEndpointL3Gateways(l3Gateways) - .setTimestamp(System.currentTimeMillis()); - return inputBuilder.build(); - } - - private static EndpointL3 createL3Endpoint(TenantId tenantId, EndpointL3Key epL3Key, - List epgIds, NetworkDomainId containment) { - - EndpointL3Builder epL3Builder = new EndpointL3Builder() - .setTenant(tenantId) - .setNetworkContainment(containment) - .setIpAddress(epL3Key.getIpAddress()) - .setL3Context(epL3Key.getL3Context()) - .setEndpointGroups(epgIds) - .setTimestamp(System.currentTimeMillis()); - - return epL3Builder.build(); } - private static RegisterEndpointInput createRegisterEndpointInput(NeutronPort port, ForwardingCtx fwCtx) { - List epgIds = new ArrayList<>(); - if (isDhcpPort(port)) { - epgIds.add(NetworkService.EPG_ID); - } - - List securityGroups = port.getSecurityGroups(); - if ((securityGroups == null || securityGroups.isEmpty())) { - if (!isDhcpPort(port)) { - LOG.warn( - "Port {} does not contain any security group. The port should belong to 'default' security group at least.", - port.getID()); - } - } else { - for (NeutronSecurityGroup secGrp : securityGroups) { - epgIds.add(new EndpointGroupId(secGrp.getSecurityGroupUUID())); - } - epgIds.add(NetworkClient.EPG_ID); - } - RegisterEndpointInputBuilder inputBuilder = new RegisterEndpointInputBuilder().setL2Context( - fwCtx.getL2BridgeDomain().getId()) + private UnregisterEndpointInput createUnregisterEndpointInput(Port port, Neutron neutron) { + UnregisterEndpointInputBuilder inputBuilder = new UnregisterEndpointInputBuilder(); + L2 l2Ep = new L2Builder().setL2Context(new L2BridgeDomainId(port.getNetworkId().getValue())) .setMacAddress(new MacAddress(port.getMacAddress())) - .setTenant(new TenantId(Utils.normalizeUuid(port.getTenantID()))) - .setEndpointGroups(epgIds) - .setTimestamp(System.currentTimeMillis()); - List fixedIPs = port.getFixedIPs(); - // TODO Li msunal this getting of just first IP has to be rewrite when OFOverlay renderer - // will support l3-endpoints. Then we will register L2 and L3 endpoints separately. - Neutron_IPs firstIp = MappingUtils.getFirstIp(fixedIPs); - if (firstIp != null) { - inputBuilder.setNetworkContainment(new SubnetId(firstIp.getSubnetUUID())); - L3Address l3Address = new L3AddressBuilder().setIpAddress(Utils.createIpAddress(firstIp.getIpAddress())) - .setL3Context(fwCtx.getL3Context().getId()) + .build(); + inputBuilder.setL2(ImmutableList.of(l2Ep)); + // we've registered EP with only first IP so remove only EP with first IP + Optional potentialFirstIp = PortUtils.resolveFirstFixedIps(port); + if (!potentialFirstIp.isPresent()) { + FixedIps firstIp = potentialFirstIp.get(); + L3Address l3Address = resolveL3AddressFromPort(port, firstIp, neutron); + L3 l3 = new L3Builder().setIpAddress(l3Address.getIpAddress()) + .setL3Context(l3Address.getL3Context()) .build(); - inputBuilder.setL3Address(ImmutableList.of(l3Address)); - } - if (!Strings.isNullOrEmpty(port.getName())) { - + inputBuilder.setL3(ImmutableList.of(l3)); } return inputBuilder.build(); } - public static boolean isDhcpPort(NeutronPort port) { - return DEVICE_OWNER_DHCP.equals(port.getDeviceOwner()); - } - - public static boolean isRouterInterfacePort(NeutronPort port) { - return DEVICE_OWNER_ROUTER_IFACE.equals(port.getDeviceOwner()); - } - - public static boolean isRouterGatewayPort(NeutronPort port) { - return DEVICE_OWNER_ROUTER_GATEWAY.equals(port.getDeviceOwner()); - } - - public static boolean isFloatingIpPort(NeutronPort port) { - return DEVICE_OWNER_FLOATING_IP.equals(port.getDeviceOwner()); + private void unregisterEndpointAndRemoveMapping(UnregisterEndpointInput unregEpInput, Port port) { + boolean isUnregisteredEndpoint = epRegistrator.unregisterEndpoint(unregEpInput); + if (isUnregisteredEndpoint) { + ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction(); + UniqueId portId = new UniqueId(port.getUuid().getValue()); + EndpointKey epKey = new EndpointKey(new L2BridgeDomainId(port.getNetworkId().getValue()), + new MacAddress(port.getMacAddress())); + LOG.trace("Removing Port-Endpoint mapping for port {} (device owner {}) and endpoint {}", + port.getUuid().getValue(), port.getDeviceOwner(), epKey); + DataStoreHelper.removeIfExists(LogicalDatastoreType.OPERATIONAL, + NeutronGbpIidFactory.endpointByPortIid(portId), rwTx); + DataStoreHelper.removeIfExists(LogicalDatastoreType.OPERATIONAL, + NeutronGbpIidFactory.portByEndpointIid(epKey.getL2Context(), epKey.getMacAddress()), rwTx); + DataStoreHelper.submitToDs(rwTx); + } } - private UnregisterEndpointInput createUnregisterEndpointInput(Endpoint ep) { - UnregisterEndpointInputBuilder inputBuilder = new UnregisterEndpointInputBuilder(); - L2 l2Ep = new L2Builder().setL2Context(ep.getL2Context()).setMacAddress(ep.getMacAddress()).build(); - inputBuilder.setL2(ImmutableList.of(l2Ep)); - // TODO Li msunal this has to be rewrite when OFOverlay renderer will support l3-endpoints. - // Endpoint probably will not have l3-addresses anymore, because L2 and L3 endpoints should - // be registered separately. - if (ep.getL3Address() != null && !ep.getL3Address().isEmpty()) { - List l3Eps = new ArrayList<>(); - for (L3Address ip : ep.getL3Address()) { - l3Eps.add(new L3Builder().setL3Context(ip.getL3Context()).setIpAddress(ip.getIpAddress()).build()); + private static L3Address resolveL3AddressFromPort(Port port, FixedIps portFixedIPs, Neutron neutron) { + Set routerIfacePorts = PortUtils.findRouterInterfacePorts(neutron.getPorts()); + for (Port routerIfacePort : routerIfacePorts) { + Uuid routerIfacePortSubnet = routerIfacePort.getFixedIps().get(0).getSubnetId(); + // if port is in the same subnet as router interface then we want to use L3Context of + // router + if (portFixedIPs.getSubnetId().equals(routerIfacePortSubnet)) { + L3ContextId epL3ContextId = new L3ContextId(routerIfacePort.getDeviceId()); + LOG.trace("Router interface port was found in the same subnet as port have {}", port); + return new L3AddressBuilder().setL3Context(epL3ContextId) + .setIpAddress(portFixedIPs.getIpAddress()) + .build(); } - inputBuilder.setL3(l3Eps); } - return inputBuilder.build(); - } - - private UnregisterEndpointInput createUnregisterEndpointInput(NeutronPort port, ForwardingCtx fwCtx) { - UnregisterEndpointInputBuilder inputBuilder = new UnregisterEndpointInputBuilder(); - L2 l2Ep = new L2Builder().setL2Context(fwCtx.getL2BridgeDomain().getId()) - .setMacAddress(new MacAddress(port.getMacAddress())) + return new L3AddressBuilder().setL3Context(new L3ContextId(port.getNetworkId().getValue())) + .setIpAddress(portFixedIPs.getIpAddress()) .build(); - inputBuilder.setL2(ImmutableList.of(l2Ep)); - // TODO Li msunal this has to be rewrite when OFOverlay renderer will support l3-endpoints. - // Endpoint probably will not have l3-addresses anymore, because L2 and L3 endpoints should - // be registered separately. - if (port.getFixedIPs() != null && !port.getFixedIPs().isEmpty()) { - inputBuilder.setL3(createL3s(port.getFixedIPs(), fwCtx.getL3Context().getId())); - } - return inputBuilder.build(); } - private List createL3s(List neutronIps, L3ContextId l3ContextId) { - List l3s = new ArrayList<>(); - for (Neutron_IPs fixedIp : neutronIps) { - String ip = fixedIp.getIpAddress(); - L3 l3 = new L3Builder().setIpAddress(Utils.createIpAddress(ip)).setL3Context(l3ContextId).build(); - l3s.add(l3); - } - return l3s; - } } diff --git a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronRouterAware.java b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronRouterAware.java index 057001ecd..7da088ec9 100644 --- a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronRouterAware.java +++ b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronRouterAware.java @@ -10,505 +10,185 @@ package org.opendaylight.groupbasedpolicy.neutron.mapper.mapping; import static com.google.common.base.Preconditions.checkNotNull; -import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; +import java.util.concurrent.ExecutionException; import javax.annotation.Nonnull; -import javax.annotation.Nullable; import org.opendaylight.controller.md.sal.binding.api.DataBroker; -import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction; -import org.opendaylight.controller.md.sal.binding.api.ReadTransaction; import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction; import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; +import org.opendaylight.groupbasedpolicy.dto.IndexedTenant; +import org.opendaylight.groupbasedpolicy.neutron.gbp.util.NeutronGbpIidFactory; +import org.opendaylight.groupbasedpolicy.neutron.mapper.EndpointRegistrator; import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils; -import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils.ForwardingCtx; -import org.opendaylight.groupbasedpolicy.neutron.mapper.util.NeutronMapperIidFactory; -import org.opendaylight.groupbasedpolicy.neutron.mapper.util.Utils; +import org.opendaylight.groupbasedpolicy.neutron.mapper.util.PortUtils; +import org.opendaylight.groupbasedpolicy.neutron.mapper.util.SubnetUtils; import org.opendaylight.groupbasedpolicy.util.DataStoreHelper; import org.opendaylight.groupbasedpolicy.util.IidFactory; -import org.opendaylight.neutron.spi.INeutronPortCRUD; -import org.opendaylight.neutron.spi.INeutronSubnetCRUD; -import org.opendaylight.neutron.spi.NeutronCRUDInterfaces; -import org.opendaylight.neutron.spi.NeutronPort; -import org.opendaylight.neutron.spi.NeutronRoute; -import org.opendaylight.neutron.spi.NeutronRouter; -import org.opendaylight.neutron.spi.NeutronRouter_Interface; -import org.opendaylight.neutron.spi.NeutronRouter_NetworkReference; -import org.opendaylight.neutron.spi.NeutronSubnet; -import org.opendaylight.neutron.spi.Neutron_IPs; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.Description; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2FloodDomainId; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2BridgeDomainId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L3ContextId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.Name; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.NetworkDomainId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.SubnetId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.EndpointService; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.UnregisterEndpointInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.unregister.endpoint.input.L3; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.unregister.endpoint.input.L3Builder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.mapper.rev150223.mappings.network.mappings.NetworkMapping; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointL3Key; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.mappings.neutron.by.gbp.mappings.external.gateways.as.l3.endpoints.ExternalGatewayAsL3Endpoint; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.TenantBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.ForwardingContext; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2BridgeDomain; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2BridgeDomainBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2FloodDomain; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L3Context; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L3ContextBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.Subnet; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.SubnetBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.l3.attributes.Routes; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.Routers; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.routers.Router; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.routers.router.Interfaces; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.routers.router.external_gateway_info.ExternalFixedIps; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.Ports; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.FixedIps; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.Subnets; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Optional; import com.google.common.base.Strings; -import com.google.common.collect.ImmutableList; -public class NeutronRouterAware implements MappingProcessor { +public class NeutronRouterAware implements NeutronAware { private static final Logger LOG = LoggerFactory.getLogger(NeutronRouterAware.class); - private static final String DEFAULT_ROUTE = "0.0.0.0/0"; + public static final InstanceIdentifier ROUTER_WILDCARD_IID = + InstanceIdentifier.builder(Neutron.class).child(Routers.class).child(Router.class).build(); private final DataBroker dataProvider; - private final EndpointService epService; + private final EndpointRegistrator epRegistrator; - public NeutronRouterAware(DataBroker dataProvider, EndpointService epService) { + public NeutronRouterAware(DataBroker dataProvider, EndpointRegistrator epRegistrator) { this.dataProvider = checkNotNull(dataProvider); - this.epService = checkNotNull(epService); + this.epRegistrator = checkNotNull(epRegistrator); } @Override - public NeutronRouter convertToNeutron(Router router) { - return toNeutron(router); - } - - private static NeutronRouter toNeutron(Router router) { - NeutronRouter result = new NeutronRouter(); - result.setID(router.getUuid().getValue()); - result.setName(router.getName()); - result.setTenantID(router.getTenantId()); - result.setAdminStateUp(router.isAdminStateUp()); - result.setStatus(router.getStatus()); - result.setDistributed(router.isDistributed()); - if (router.getGatewayPortId() != null) { - result.setGatewayPortId(router.getGatewayPortId().getValue()); - } - if (router.getRoutes() != null) { - List routes = new ArrayList(); - for (Routes route : router.getRoutes()) { - NeutronRoute routerRoute = new NeutronRoute(); - routerRoute.setDestination(String.valueOf(route.getDestination().getValue())); - routerRoute.setNextHop(String.valueOf(route.getNexthop().getValue())); - routes.add(routerRoute); - } - result.setRoutes(routes); - } - if (router.getExternalGatewayInfo() != null) { - NeutronRouter_NetworkReference extGwInfo = new NeutronRouter_NetworkReference(); - extGwInfo.setNetworkID(router.getExternalGatewayInfo().getExternalNetworkId().getValue()); - extGwInfo.setEnableSNAT(router.getExternalGatewayInfo().isEnableSnat()); - if (router.getExternalGatewayInfo().getExternalFixedIps() != null) { - List fixedIPs = new ArrayList(); - for (ExternalFixedIps mdFixedIP : router.getExternalGatewayInfo().getExternalFixedIps()) { - Neutron_IPs fixedIP = new Neutron_IPs(); - fixedIP.setSubnetUUID(mdFixedIP.getSubnetId().getValue()); - fixedIP.setIpAddress(String.valueOf(mdFixedIP.getIpAddress().getValue())); - fixedIPs.add(fixedIP); - } - extGwInfo.setExternalFixedIPs(fixedIPs); - } - result.setExternalGatewayInfo(extGwInfo); - } - if (router.getInterfaces() != null) { - Map interfaces = new HashMap(); - for (Interfaces mdInterface : router.getInterfaces()) { - NeutronRouter_Interface pojoInterface = new NeutronRouter_Interface(); - String id = mdInterface.getUuid().getValue(); - pojoInterface.setID(id); - pojoInterface.setTenantID(mdInterface.getTenantId()); - pojoInterface.setSubnetUUID(mdInterface.getSubnetId().getValue()); - pojoInterface.setPortUUID(mdInterface.getPortId().getValue()); - interfaces.put(id, pojoInterface); - } - result.setInterfaces(interfaces); - } - return result; - } - - @Override - public int canCreate(NeutronRouter router) { - LOG.trace("canCreate router - {}", router); - // nothing to consider - return StatusCode.OK; - } - - @Override - public void created(NeutronRouter router) { + public void onCreated(Router router, Neutron neutron) { LOG.trace("created router - {}", router); - // TODO Li msunal external gateway - } - - @Override - public int canUpdate(NeutronRouter delta, NeutronRouter original) { - LOG.trace("canUpdate router - delta: {} original: {}", delta, original); - // TODO Li msunal external gateway - return StatusCode.OK; } @Override - public void updated(NeutronRouter router) { - LOG.trace("updated router - {}", router); - if (router.getExternalGatewayInfo() == null || router.getExternalGatewayInfo().getExternalFixedIPs() == null) { - LOG.trace("neutronRouterUpdated - not an external Gateway"); - return; - } - - NeutronCRUDInterfaces neutronCRUDInterface = new NeutronCRUDInterfaces().fetchINeutronPortCRUD(this); - INeutronPortCRUD portInterface = neutronCRUDInterface.getPortInterface(); - if (portInterface == null) { - LOG.warn("Illegal state - No provider for {}", INeutronPortCRUD.class.getName()); - return; - } + public void onUpdated(Router oldRouter, Router newRouter, Neutron oldNeutron, Neutron newNeutron) { + LOG.trace("updated router - OLD: {}\nNEW: {}", oldRouter, newRouter); ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction(); - TenantId tenantId = new TenantId(Utils.normalizeUuid(router.getTenantID())); - L3ContextId l3ContextIdFromRouterId = new L3ContextId(router.getID()); - InstanceIdentifier l3ContextIidForRouterId = IidFactory.l3ContextIid(tenantId, - l3ContextIdFromRouterId); - Optional potentialL3ContextForRouter = DataStoreHelper.readFromDs( - LogicalDatastoreType.CONFIGURATION, l3ContextIidForRouterId, rwTx); + TenantId tenantId = new TenantId(newRouter.getTenantId().getValue()); + L3ContextId l3ContextIdFromRouterId = new L3ContextId(newRouter.getUuid().getValue()); + InstanceIdentifier l3ContextIidForRouterId = + IidFactory.l3ContextIid(tenantId, l3ContextIdFromRouterId); + Optional potentialL3ContextForRouter = + DataStoreHelper.readFromDs(LogicalDatastoreType.CONFIGURATION, l3ContextIidForRouterId, rwTx); L3Context l3Context = null; if (potentialL3ContextForRouter.isPresent()) { l3Context = potentialL3ContextForRouter.get(); } else { // add L3 context if missing - l3Context = createL3ContextFromRouter(router); + l3Context = createL3ContextFromRouter(newRouter); rwTx.put(LogicalDatastoreType.CONFIGURATION, l3ContextIidForRouterId, l3Context); } - neutronCRUDInterface = neutronCRUDInterface.fetchINeutronSubnetCRUD(this); - INeutronSubnetCRUD subnetInterface = neutronCRUDInterface.getSubnetInterface(); - if (subnetInterface == null) { - LOG.warn("Illegal state - No provider for {}", INeutronSubnetCRUD.class.getName()); - return; - } - NeutronSubnet defaultSubnet = subnetInterface.getSubnet(router.getExternalGatewayInfo() - .getExternalFixedIPs() - .get(0) - .getSubnetUUID()); - IpAddress defaultGateway = null; - if (defaultSubnet != null) { - defaultGateway = Utils.createIpAddress(defaultSubnet.getGatewayIP()); - //Create L3Endpoint for defaultGateway and write to externalGateways to L3Endpoints in neutron-gbp datastore - NetworkDomainId containment = new NetworkDomainId(defaultSubnet.getID()); - NeutronPortAware.addL3EndpointForExternalGateway(tenantId, l3Context.getId(), defaultGateway, containment ,rwTx); - } - // Create L3Prefix Endpoints for all routes - if (router.getRoutes().isEmpty()) { - NeutronRoute defaultRoute = new NeutronRoute(); - defaultRoute.setDestination(DEFAULT_ROUTE); - defaultRoute.setNextHop(Utils.getStringIpAddress(defaultGateway)); - router.setRoutes(ImmutableList.of(defaultRoute)); - - } - if (defaultGateway != null) { - for (NeutronRoute route : router.getRoutes()) { - IpPrefix ipPrefix = Utils.createIpPrefix(route.getDestination()); - boolean addedL3Prefix = NeutronPortAware.addL3PrefixEndpoint(l3ContextIdFromRouterId, ipPrefix, - defaultGateway, tenantId, epService); - if (!addedL3Prefix) { - LOG.warn("Could not add EndpointL3Prefix for Neutron route {} for router {}", route, router.getID()); - rwTx.cancel(); - return; - } - } - } - for (Neutron_IPs externalFixedIp : router.getExternalGatewayInfo().getExternalFixedIPs()) { - NeutronPort routerPort = portInterface.getPort(router.getGatewayPortId()); - IpAddress ipAddress = Utils.createIpAddress(routerPort.getFixedIPs().get(0).getIpAddress()); - // External subnet associated with gateway port should use the gateway IP not router IP. - NeutronSubnet neutronSubnet = subnetInterface.getSubnet(externalFixedIp.getSubnetUUID()); - ipAddress = Utils.createIpAddress(neutronSubnet.getGatewayIP()); - SubnetId subnetId = new SubnetId(externalFixedIp.getSubnetUUID()); - Subnet subnet = resolveSubnetWithVirtualRouterIp(tenantId, subnetId, ipAddress, rwTx); - if (subnet == null) { + if (newRouter.getGatewayPortId() != null && oldRouter.getGatewayPortId() == null) { + // external network is attached to router + Uuid gatewayPortId = newRouter.getGatewayPortId(); + Optional potentialGwPort = PortUtils.findPort(gatewayPortId, newNeutron.getPorts()); + if (!potentialGwPort.isPresent()) { + LOG.warn("Illegal state - router gateway port {} does not exist for router {}.", + gatewayPortId.getValue(), newRouter); rwTx.cancel(); return; } - rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.subnetIid(tenantId, subnet.getId()), subnet); - - if (Strings.isNullOrEmpty(routerPort.getTenantID())) { - routerPort.setTenantID(router.getTenantID()); - } - boolean isSuccessful = setNewL3ContextToEpsFromSubnet(tenantId, l3Context, subnet, rwTx, epService); - if (!isSuccessful) { + Port gwPort = potentialGwPort.get(); + List fixedIpsFromGwPort = gwPort.getFixedIps(); + if (fixedIpsFromGwPort == null || fixedIpsFromGwPort.isEmpty()) { + LOG.warn("Illegal state - router gateway port {} does not contain fixed IPs {}", + gatewayPortId.getValue(), gwPort); rwTx.cancel(); return; } - } - DataStoreHelper.submitToDs(rwTx); - } - - @Override - public int canDelete(NeutronRouter router) { - LOG.trace("canDelete router - {}", router); - // nothing to consider - return StatusCode.OK; - } - - @Override - public void deleted(NeutronRouter router) { - LOG.trace("deleted router - {}", router); - } - - - static int canAttachInterface(NeutronRouter router, NeutronRouter_Interface routerInterface, DataBroker dataProvider) { - LOG.trace("canAttachInterface - router: {} interface: {}", router, routerInterface); - try (ReadOnlyTransaction rTx = dataProvider.newReadOnlyTransaction()) { - L3ContextId l3ContextIdFromRouterId = new L3ContextId(router.getID()); - TenantId tenantId = new TenantId(Utils.normalizeUuid(router.getTenantID())); - SubnetId subnetId = new SubnetId(routerInterface.getSubnetUUID()); - Optional potentialSubnet = DataStoreHelper.readFromDs(LogicalDatastoreType.CONFIGURATION, - IidFactory.subnetIid(tenantId, subnetId), rTx); + // router can have only one external network + FixedIps ipWithSubnetFromGwPort = fixedIpsFromGwPort.get(0); + Optional potentialSubnet = SubnetUtils.findSubnet(ipWithSubnetFromGwPort.getSubnetId(), newNeutron.getSubnets()); if (!potentialSubnet.isPresent()) { - LOG.warn("Illegal state - subnet {} does not exist.", subnetId.getValue()); - return StatusCode.NOT_FOUND; + LOG.warn("Illegal state - Subnet {} does not exist for router {}.", + ipWithSubnetFromGwPort.getSubnetId(), newRouter); + rwTx.cancel(); + return; } - Subnet subnet = potentialSubnet.get(); - L2FloodDomainId l2FdId = new L2FloodDomainId(subnet.getParent().getValue()); - ForwardingCtx fwCtx = MappingUtils.createForwardingContext(tenantId, l2FdId, rTx); - if (fwCtx.getL3Context() != null && fwCtx.getL3Context().getId().equals(l3ContextIdFromRouterId)) { - // TODO Be msunal - LOG.warn("Illegal state - Neutron mapper does not support multiple router interfaces in the same subnet yet."); - return StatusCode.FORBIDDEN; + IpAddress gatewayIp = potentialSubnet.get().getGatewayIp(); + boolean registeredExternalGateway = epRegistrator.registerL3EndpointAsExternalGateway(tenantId, gatewayIp, + l3ContextIdFromRouterId, new NetworkDomainId(ipWithSubnetFromGwPort.getSubnetId().getValue())); + if (!registeredExternalGateway) { + LOG.warn("Could not add L3Prefix as gateway of default route. Gateway port {}", gwPort); + rwTx.cancel(); + return; } - return StatusCode.OK; - } - } + EndpointL3Key epL3Key = new EndpointL3Key(gatewayIp, l3ContextIdFromRouterId); + addNeutronExtGwGbpMapping(epL3Key, rwTx); - static NeutronRouter getRouterForPort(String uuid) { - Routers routers = NeutronListener.getNeutronDataAfter().getRouters(); - if (routers != null) { - for (Router router : routers.getRouter()) { - if (router.getUuid().getValue().equals(uuid)) { - return toNeutron(router); - } + boolean registeredDefaultRoute = epRegistrator.registerExternalL3PrefixEndpoint(MappingUtils.DEFAULT_ROUTE, + l3ContextIdFromRouterId, gatewayIp, tenantId); + if (!registeredDefaultRoute) { + LOG.warn("Could not add EndpointL3Prefix as default route. Gateway port {}", gwPort); + rwTx.cancel(); + return; } - } - return null; - } - - static void neutronRouterInterfaceAttached(NeutronRouter router, NeutronRouter_Interface routerInterface, DataBroker dataProvider, EndpointService epService) { - LOG.trace("neutronRouterInterfaceAttached - router: {} interface: {}", router, routerInterface); - ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction(); - TenantId tenantId = new TenantId(Utils.normalizeUuid(router.getTenantID())); - L3ContextId l3ContextIdFromRouterId = new L3ContextId(router.getID()); - InstanceIdentifier l3ContextIidForRouterId = IidFactory.l3ContextIid(tenantId, - l3ContextIdFromRouterId); - Optional potentialL3ContextForRouter = DataStoreHelper.readFromDs( - LogicalDatastoreType.CONFIGURATION, l3ContextIidForRouterId, rwTx); - L3Context l3Context = null; - if (potentialL3ContextForRouter.isPresent()) { - l3Context = potentialL3ContextForRouter.get(); - } else { // add L3 context if missing - l3Context = createL3ContextFromRouter(router); - rwTx.put(LogicalDatastoreType.CONFIGURATION, l3ContextIidForRouterId, l3Context); - } - // Based on Neutron Northbound - Port representing router interface - // contains exactly on fixed IP - NeutronPort routerPort = null; - Ports ports = NeutronListener.getNeutronDataAfter().getPorts(); - if(ports != null) { - for(Port port : ports.getPort()) { - if(port.getUuid().getValue().equals(routerInterface.getPortUUID())) { - routerPort = NeutronPortAware.toNeutron(port); - break; - } + Subnet subnetWithGw = + new SubnetBuilder().setId(new SubnetId(ipWithSubnetFromGwPort.getSubnetId().getValue())) + .setVirtualRouterIp(gatewayIp) + .build(); + rwTx.merge(LogicalDatastoreType.CONFIGURATION, IidFactory.subnetIid(tenantId, subnetWithGw.getId()), + subnetWithGw); + L2BridgeDomainId l2BdId = new L2BridgeDomainId(potentialSubnet.get().getNetworkId().getValue()); + Optional optBd = DataStoreHelper.readFromDs(LogicalDatastoreType.CONFIGURATION, + IidFactory.l2BridgeDomainIid(tenantId, l2BdId), rwTx); + if (!optBd.isPresent()) { + LOG.warn( + "Could not read L2-Bridge-Domain {} Modifiaction of it's parent to L3-Context of router {} aborted.", + l2BdId, newRouter.getUuid()); + rwTx.cancel(); + return; } + L2BridgeDomain l2BdWithGw = new L2BridgeDomainBuilder(optBd.get()) + .setParent(new L3ContextId(l3ContextIdFromRouterId.getValue())) + .build(); + rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.l2BridgeDomainIid(tenantId, l2BdId), + l2BdWithGw); } - if (routerPort == null) { - rwTx.cancel(); - return; - } - SubnetId subnetId = new SubnetId(routerInterface.getSubnetUUID()); - IpAddress ipAddress = Utils.createIpAddress(routerPort.getFixedIPs().get(0).getIpAddress()); - Subnet subnet = resolveSubnetWithVirtualRouterIp(tenantId, subnetId, ipAddress, rwTx); - if (subnet == null) { - rwTx.cancel(); - return; - } - rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.subnetIid(tenantId, subnet.getId()), subnet); - - boolean isSuccessful = setNewL3ContextToEpsFromSubnet(tenantId, l3Context, subnet, rwTx, epService); - if (!isSuccessful) { - rwTx.cancel(); - return; - } - DataStoreHelper.submitToDs(rwTx); } - private static @Nonnull L3Context createL3ContextFromRouter(NeutronRouter router) { + private static @Nonnull L3Context createL3ContextFromRouter(Router router) { Name l3ContextName = null; if (!Strings.isNullOrEmpty(router.getName())) { l3ContextName = new Name(router.getName()); } - return new L3ContextBuilder().setId(new L3ContextId(router.getID())) + return new L3ContextBuilder().setId(new L3ContextId(router.getUuid().getValue())) .setName(l3ContextName) - .setDescription(new Description(MappingUtils.NEUTRON_ROUTER + router.getID())) + .setDescription(new Description(MappingUtils.NEUTRON_ROUTER + router.getUuid().getValue())) .build(); } - private static @Nullable Subnet resolveSubnetWithVirtualRouterIp(TenantId tenantId, SubnetId subnetId, - IpAddress ipAddress, ReadTransaction rTx) { - Optional potentialSubnet = DataStoreHelper.readFromDs(LogicalDatastoreType.CONFIGURATION, - IidFactory.subnetIid(tenantId, subnetId), rTx); - if (!potentialSubnet.isPresent()) { - LOG.warn("Illegal state - subnet {} does not exist.", subnetId.getValue()); - return null; - } - - // TODO: Li alagalah: Add gateways and prefixes instead of - // VirtualRouterID - return new SubnetBuilder(potentialSubnet.get()).setVirtualRouterIp(ipAddress).build(); - } - - public static boolean setNewL3ContextToEpsFromSubnet(TenantId tenantId, L3Context l3Context, Subnet subnet, - ReadWriteTransaction rwTx, EndpointService epService) { - if (subnet.getParent() == null) { - LOG.warn("Illegal state - subnet {} does not have a parent.", subnet.getId().getValue()); - return false; - } - - L2FloodDomainId l2FdId = new L2FloodDomainId(subnet.getParent().getValue()); - ForwardingCtx fwCtx = MappingUtils.createForwardingContext(tenantId, l2FdId, rwTx); - if (fwCtx.getL2BridgeDomain() == null) { - LOG.warn("Illegal state - l2-flood-domain {} does not have a parent.", l2FdId.getValue()); - return false; - } - - L2BridgeDomain l2BridgeDomain = new L2BridgeDomainBuilder(fwCtx.getL2BridgeDomain()).setParent( - l3Context.getId()).build(); - rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.l2BridgeDomainIid(tenantId, l2BridgeDomain.getId()), - l2BridgeDomain); - - List l3Eps = new ArrayList<>(); - L3ContextId oldL3ContextId = fwCtx.getL3Context().getId(); - NeutronSubnet neutronSubnet = new NeutronSubnet(); - Subnets subnets = NeutronListener.getNeutronDataAfter().getSubnets(); - for(org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet s : subnets.getSubnet()) { - if(s.getUuid().getValue().equals(subnet.getId().getValue())) { - neutronSubnet = NeutronSubnetAware.toNeutron(s); - break; - } - } - List portsInNeutronSubnet = neutronSubnet.getPortsInSubnet(); - if (portsInNeutronSubnet != null) { - for (NeutronPort port : portsInNeutronSubnet) { - if (NeutronPortAware.isRouterGatewayPort(port) || NeutronPortAware.isRouterInterfacePort(port)) { - continue; - } - boolean isPortAdded = NeutronPortAware.addNeutronPort(port, rwTx, epService); - if (!isPortAdded) { - return false; - } - // TODO Li msunal this has to be rewrite when OFOverlay renderer - // will support l3-endpoints. - Neutron_IPs firstIp = MappingUtils.getFirstIp(port.getFixedIPs()); - if (firstIp != null) { - l3Eps.add(new L3Builder().setL3Context(oldL3ContextId) - .setIpAddress(Utils.createIpAddress(firstIp.getIpAddress())) - .build()); - } - } - } - if (neutronSubnet.getGatewayIP() != null) { - l3Eps.add(new L3Builder().setL3Context(oldL3ContextId) - .setIpAddress(Utils.createIpAddress(neutronSubnet.getGatewayIP())) - .build()); - } - - if (!l3Eps.isEmpty()) { - epService.unregisterEndpoint(new UnregisterEndpointInputBuilder().setL3(l3Eps).build()); - } - return true; + private static void addNeutronExtGwGbpMapping(EndpointL3Key epL3Key, ReadWriteTransaction rwTx) { + ExternalGatewayAsL3Endpoint externalGatewayL3Endpoint = + MappingFactory.createExternalGatewayByL3Endpoint(epL3Key); + rwTx.put(LogicalDatastoreType.OPERATIONAL, + NeutronGbpIidFactory.externalGatewayAsL3Endpoint(epL3Key.getL3Context(), epL3Key.getIpAddress()), + externalGatewayL3Endpoint, true); } - public static int canDetachInterface(NeutronRouter router, NeutronRouter_Interface routerInterface) { - LOG.trace("canDetachInterface - router: {} interface: {}", router, routerInterface); - // nothing to consider - return StatusCode.OK; + @Override + public void onDeleted(Router router, Neutron oldNeutron, Neutron newNeutron) { + LOG.trace("deleted router - {}", router); } - public static void neutronRouterInterfaceDetached(NeutronRouter router, NeutronRouter_Interface routerInterface, DataBroker dataProvider, EndpointService epService) { - LOG.trace("neutronRouterInterfaceDetached - router: {} interface: {}", router, routerInterface); - ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction(); - TenantId tenantId = new TenantId(Utils.normalizeUuid(router.getTenantID())); - L3ContextId l3ContextId = new L3ContextId(router.getID()); - SubnetId subnetId = new SubnetId(routerInterface.getSubnetUUID()); - DataStoreHelper.removeIfExists(LogicalDatastoreType.CONFIGURATION, - IidFactory.l3ContextIid(tenantId, l3ContextId), rwTx); - - Optional potentialSubnet = DataStoreHelper.readFromDs(LogicalDatastoreType.CONFIGURATION, - IidFactory.subnetIid(tenantId, subnetId), rwTx); - if (!potentialSubnet.isPresent()) { - LOG.warn("Illegal state - subnet {} does not exist.", subnetId.getValue()); - rwTx.cancel(); - return; - } - - Subnet subnet = new SubnetBuilder(potentialSubnet.get()).setVirtualRouterIp(null).build(); - rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.subnetIid(tenantId, subnetId), subnet); - - L2FloodDomainId l2FdId = new L2FloodDomainId(subnet.getParent().getValue()); - ForwardingCtx fwCtx = MappingUtils.createForwardingContext(tenantId, l2FdId, rwTx); - if (fwCtx.getL2BridgeDomain() == null) { - LOG.warn("Illegal state - l2-flood-domain {} does not have a parent.", l2FdId.getValue()); - rwTx.cancel(); - return; - } - - Optional potentialNetworkMapping = DataStoreHelper.readFromDs(LogicalDatastoreType.OPERATIONAL, - NeutronMapperIidFactory.networkMappingIid(l2FdId), rwTx); - if (!potentialNetworkMapping.isPresent()) { - LOG.warn("Illegal state - network-mapping {} does not exist.", l2FdId.getValue()); - rwTx.cancel(); - return; - } - - L2BridgeDomain l2BridgeDomain = new L2BridgeDomainBuilder(fwCtx.getL2BridgeDomain()).setParent( - potentialNetworkMapping.get().getL3ContextId()).build(); - rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.l2BridgeDomainIid(tenantId, l2BridgeDomain.getId()), - l2BridgeDomain); - NeutronSubnet neutronSubnet = new NeutronSubnet(); - Subnets subnets = NeutronListener.getNeutronDataAfter().getSubnets(); - for (org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet s : subnets.getSubnet()) { - if (s.getUuid().getValue().equals(subnet.getId().getValue())) { - neutronSubnet = NeutronSubnetAware.toNeutron(s); - break; - } - } - List portsInNeutronSubnet = neutronSubnet.getPortsInSubnet(); - for (NeutronPort port : portsInNeutronSubnet) { - if (NeutronPortAware.isRouterGatewayPort(port) || NeutronPortAware.isRouterInterfacePort(port)) { - continue; - } - boolean isPortAdded = NeutronPortAware.addNeutronPort(port, rwTx, epService); - if (!isPortAdded) { - rwTx.cancel(); - return; - } - } - } } diff --git a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronSecurityGroupAware.java b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronSecurityGroupAware.java new file mode 100644 index 000000000..4fac58292 --- /dev/null +++ b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronSecurityGroupAware.java @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.groupbasedpolicy.neutron.mapper.mapping; + +import static com.google.common.base.Preconditions.checkNotNull; + +import org.opendaylight.controller.md.sal.binding.api.DataBroker; +import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction; +import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; +import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils; +import org.opendaylight.groupbasedpolicy.util.DataStoreHelper; +import org.opendaylight.groupbasedpolicy.util.IidFactory; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.Description; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.EndpointGroupId; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.Name; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.EndpointGroup; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.EndpointGroup.IntraGroupPolicy; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.EndpointGroupBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.ExternalImplicitGroup; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.ExternalImplicitGroupBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.SecurityGroups; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.security.groups.SecurityGroup; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.common.base.Optional; +import com.google.common.base.Strings; + +public class NeutronSecurityGroupAware implements NeutronAware { + + private static final Logger LOG = LoggerFactory.getLogger(NeutronSecurityGroupAware.class); + public static final InstanceIdentifier SECURITY_GROUP_WILDCARD_IID = + InstanceIdentifier.builder(Neutron.class).child(SecurityGroups.class).child(SecurityGroup.class).build(); + private final DataBroker dataProvider; + + public NeutronSecurityGroupAware(DataBroker dataProvider) { + this.dataProvider = checkNotNull(dataProvider); + } + + @Override + public void onCreated(SecurityGroup createdSecGroup, Neutron neutron) { + LOG.trace("created securityGroup - {}", createdSecGroup); + ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction(); + boolean isSecGroupCreated = addNeutronSecurityGroup(createdSecGroup, rwTx); + if (isSecGroupCreated) { + DataStoreHelper.submitToDs(rwTx); + } else { + rwTx.cancel(); + } + } + + public boolean addNeutronSecurityGroup(SecurityGroup secGroup, ReadWriteTransaction rwTx) { + TenantId tId = new TenantId(secGroup.getTenantId().getValue()); + EndpointGroupId epgId = new EndpointGroupId(secGroup.getUuid().getValue()); + if (epgId.getValue().equals(MappingUtils.EIG_UUID.getValue())) { + ExternalImplicitGroup eig = new ExternalImplicitGroupBuilder().setId(epgId).build(); + rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.externalImplicitGroupIid(tId, epgId), eig, true); + } + EndpointGroupBuilder epgBuilder = new EndpointGroupBuilder().setId(epgId); + if (!Strings.isNullOrEmpty(secGroup.getName())) { + try { + epgBuilder.setName(new Name(secGroup.getName())); + } catch (Exception e) { + LOG.info("Name '{}' of Neutron Security-group '{}' is ignored.", secGroup.getName(), + secGroup.getUuid().getValue()); + LOG.debug("Name exception", e); + } + } + if (!Strings.isNullOrEmpty(secGroup.getDescription())) { + try { + epgBuilder.setDescription(new Description(secGroup.getDescription())); + } catch (Exception e) { + LOG.info("Description '{}' of Neutron Security-group '{}' is ignored.", + secGroup.getDescription(), secGroup.getUuid().getValue()); + LOG.debug("Description exception", e); + } + } + epgBuilder.setIntraGroupPolicy(IntraGroupPolicy.RequireContract); + rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.endpointGroupIid(tId, epgId), + epgBuilder.build(), true); + return true; + } + + @Override + public void onUpdated(SecurityGroup oldItem, SecurityGroup newItem, Neutron oldNeutron, Neutron newNeutron) { + LOG.warn("updated securityGroup - Never should be called " + + "- neutron API does not allow UPDATE on neutron security group. \nSecurity group: {}", newItem); + } + + @Override + public void onDeleted(SecurityGroup deletedSecGroup, Neutron oldNeutron, Neutron newNeutron) { + LOG.trace("deleted securityGroup - {}", deletedSecGroup); + ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction(); + TenantId tenantId = new TenantId(deletedSecGroup.getTenantId().getValue()); + EndpointGroupId epgId = new EndpointGroupId(deletedSecGroup.getUuid().getValue()); + Optional potentialEpg = DataStoreHelper.removeIfExists(LogicalDatastoreType.CONFIGURATION, + IidFactory.endpointGroupIid(tenantId, epgId), rwTx); + if (!potentialEpg.isPresent()) { + LOG.warn("Illegal state - Endpoint group {} does not exist.", epgId.getValue()); + rwTx.cancel(); + return; + } + + DataStoreHelper.submitToDs(rwTx); + } + +} diff --git a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronSubnetAware.java b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronSubnetAware.java index 750f3624a..8fc2c843d 100644 --- a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronSubnetAware.java +++ b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronSubnetAware.java @@ -9,196 +9,131 @@ package org.opendaylight.groupbasedpolicy.neutron.mapper.mapping; import static com.google.common.base.Preconditions.checkNotNull; -import java.util.ArrayList; -import java.util.List; - import org.opendaylight.controller.md.sal.binding.api.DataBroker; import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction; import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; +import org.opendaylight.groupbasedpolicy.neutron.mapper.EndpointRegistrator; import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils; -import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils.ForwardingCtx; +import org.opendaylight.groupbasedpolicy.neutron.mapper.util.NetworkUtils; import org.opendaylight.groupbasedpolicy.neutron.mapper.util.Utils; import org.opendaylight.groupbasedpolicy.util.DataStoreHelper; import org.opendaylight.groupbasedpolicy.util.IidFactory; -import org.opendaylight.neutron.spi.NeutronSubnet; -import org.opendaylight.neutron.spi.NeutronSubnetIPAllocationPool; -import org.opendaylight.neutron.spi.NeutronSubnet_HostRoute; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ContextId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2FloodDomainId; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L3ContextId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.Name; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.NetworkDomainId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.SubnetId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.Subnet; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.SubnetBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.Dhcpv6Base; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.Dhcpv6Off; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.Dhcpv6Slaac; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.Dhcpv6Stateful; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.Dhcpv6Stateless; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.IpVersionBase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.IpVersionV4; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.IpVersionV6; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnet.attributes.AllocationPools; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnet.attributes.HostRoutes; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.networks.Network; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.Subnets; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Optional; import com.google.common.base.Strings; -import com.google.common.collect.ImmutableBiMap; -public class NeutronSubnetAware implements MappingProcessor { +public class NeutronSubnetAware implements + NeutronAware { private final static Logger LOG = LoggerFactory.getLogger(NeutronSubnetAware.class); + public static final InstanceIdentifier SUBNET_WILDCARD_IID = + InstanceIdentifier.builder(Neutron.class) + .child(Subnets.class) + .child(org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet.class) + .build(); private final DataBroker dataProvider; - private final NeutronNetworkDao networkDao; + private final EndpointRegistrator epRegistrator; - public NeutronSubnetAware(DataBroker dataProvider, NeutronNetworkDao networkDao) { + public NeutronSubnetAware(DataBroker dataProvider, EndpointRegistrator epRegistrator) { this.dataProvider = checkNotNull(dataProvider); - this.networkDao = checkNotNull(networkDao); + this.epRegistrator = checkNotNull(epRegistrator); } - // copied from Neutron's NeutronSubnetInterface - static final ImmutableBiMap,Integer> IPV_MAP - = new ImmutableBiMap.Builder,Integer>() - .put(IpVersionV4.class, 4) - .put(IpVersionV6.class, 6) - .build(); - - // copied from Neutron's NeutronSubnetInterface - private static final ImmutableBiMap,String> DHCPV6_MAP - = new ImmutableBiMap.Builder,String>() - .put(Dhcpv6Off.class,"off") - .put(Dhcpv6Stateful.class,"dhcpv6-stateful") - .put(Dhcpv6Slaac.class,"slaac") - .put(Dhcpv6Stateless.class,"dhcpv6-stateless") - .build(); - @Override - public NeutronSubnet convertToNeutron( - org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet subnet) { - return toNeutron(subnet); - } + public void onCreated( + org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet neutronSubnet, + Neutron neutron) { + LOG.trace("created subnet - {}", neutronSubnet); + ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction(); + TenantId tenantId = new TenantId(neutronSubnet.getTenantId().getValue()); - @SuppressWarnings("deprecation") - static NeutronSubnet toNeutron( - org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet subnet) { - NeutronSubnet result = new NeutronSubnet(); - result.setName(subnet.getName()); - result.setTenantID(subnet.getTenantId()); - result.setNetworkUUID(subnet.getNetworkId().getValue()); - result.setIpVersion(IPV_MAP.get(subnet.getIpVersion())); - result.setCidr(subnet.getCidr()); - if (subnet.getGatewayIp() != null) { - result.setGatewayIP(String.valueOf(subnet.getGatewayIp().getValue())); - } - if (subnet.getIpv6RaMode() != null) { - result.setIpV6RaMode(DHCPV6_MAP.get(subnet.getIpv6RaMode())); - } - if (subnet.getIpv6AddressMode() != null) { - result.setIpV6AddressMode(DHCPV6_MAP.get(subnet.getIpv6AddressMode())); - } - result.setEnableDHCP(subnet.isEnableDhcp()); - if (subnet.getAllocationPools() != null) { - List allocationPools = new ArrayList(); - for (AllocationPools allocationPool : subnet.getAllocationPools()) { - NeutronSubnetIPAllocationPool pool = new NeutronSubnetIPAllocationPool(); - pool.setPoolStart(allocationPool.getStart()); - pool.setPoolEnd(allocationPool.getEnd()); - allocationPools.add(pool); - } - result.setAllocationPools(allocationPools); - } - if (subnet.getDnsNameservers() != null) { - List dnsNameServers = new ArrayList(); - for (IpAddress dnsNameServer : subnet.getDnsNameservers()) { - dnsNameServers.add(String.valueOf(dnsNameServer.getValue())); - } - result.setDnsNameservers(dnsNameServers); + Optional potentialNetwork = + NetworkUtils.findNetwork(neutronSubnet.getNetworkId(), neutron.getNetworks()); + if (!potentialNetwork.isPresent()) { + LOG.warn("Illegal state - network {} does not exist for subnet {}.", + neutronSubnet.getNetworkId().getValue(), neutronSubnet); + rwTx.cancel(); + return; } - if (subnet.getHostRoutes() != null) { - List hostRoutes = new ArrayList(); - for (HostRoutes hostRoute : subnet.getHostRoutes()) { - NeutronSubnet_HostRoute nsHostRoute = new NeutronSubnet_HostRoute(); - nsHostRoute.setDestination(String.valueOf(hostRoute.getDestination().getValue())); - nsHostRoute.setNextHop(String.valueOf(hostRoute.getNexthop().getValue())); - hostRoutes.add(nsHostRoute); + + Network networkOfSubnet = potentialNetwork.get(); + Subnet subnet = null; + if (NetworkUtils.isProviderPhysicalNetwork(networkOfSubnet)) { + // add virtual router IP only in case it is provider physical network + subnet = createSubnet(neutronSubnet, neutronSubnet.getGatewayIp()); + IpAddress gatewayIp = neutronSubnet.getGatewayIp(); + boolean registeredDefaultRoute = epRegistrator.registerExternalL3PrefixEndpoint(MappingUtils.DEFAULT_ROUTE, + new L3ContextId(neutronSubnet.getNetworkId().getValue()), gatewayIp, tenantId); + if (!registeredDefaultRoute) { + LOG.warn("Could not add EndpointL3Prefix as default route. Subnet within provider physical network {}", + neutronSubnet); + rwTx.cancel(); + return; } - result.setHostRoutes(hostRoutes); + } else if (NetworkUtils.isRouterExternal(networkOfSubnet)) { + // virtual router IP is not set and it will be set when router gateway port is set + subnet = createSubnet(neutronSubnet, null); + } else { + // virtual router IP is not set and it will be set when router port is attached to + // network + subnet = createSubnet(neutronSubnet, null); } - result.setID(subnet.getUuid().getValue()); - return result; - } + rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.subnetIid(tenantId, subnet.getId()), subnet, true); - @Override - public int canCreate(NeutronSubnet subnet) { - LOG.trace("canCreate subnet - {}", subnet); - // nothing to consider - return StatusCode.OK; - } - - @Override - public void created(NeutronSubnet neutronSubnet) { - LOG.trace("created subnet - {}", neutronSubnet); - ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction(); - SubnetId subnetId = new SubnetId(Utils.normalizeUuid(neutronSubnet.getID())); - TenantId tenantId = new TenantId(Utils.normalizeUuid(neutronSubnet.getTenantID())); - Subnet subnet = createSubnet(neutronSubnet); - rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.subnetIid(tenantId, subnetId), subnet, true); DataStoreHelper.submitToDs(rwTx); - - rwTx = dataProvider.newReadWriteTransaction(); - if (networkDao.isExternalNetwork(neutronSubnet.getNetworkUUID())) { - LOG.trace("created - adding L3 Endpoint"); - L2FloodDomainId l2FdId = new L2FloodDomainId(subnet.getParent().getValue()); - ForwardingCtx fwCtx = MappingUtils.createForwardingContext(tenantId, l2FdId, rwTx); - IpAddress defaultGateway = Utils.createIpAddress(neutronSubnet.getGatewayIP()); - //Create L3Endpoint for defaultGateway - NetworkDomainId containment = new NetworkDomainId(neutronSubnet.getID()); - NeutronPortAware.addL3EndpointForExternalGateway(tenantId, fwCtx.getL3Context().getId(), defaultGateway, containment ,rwTx); - DataStoreHelper.submitToDs(rwTx); - } } - private Subnet createSubnet(NeutronSubnet neutronSubnet) { + public static Subnet createSubnet( + org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet neutronSubnet, + IpAddress virtualRouterIp) { SubnetBuilder subnetBuilder = new SubnetBuilder(); - subnetBuilder.setId(new SubnetId(neutronSubnet.getID())); - subnetBuilder.setParent(new ContextId(neutronSubnet.getNetworkUUID())); + subnetBuilder.setId(new SubnetId(neutronSubnet.getUuid().getValue())); + subnetBuilder.setParent(new ContextId(neutronSubnet.getNetworkId().getValue())); if (!Strings.isNullOrEmpty(neutronSubnet.getName())) { - subnetBuilder.setName(new Name(neutronSubnet.getName())); + try { + subnetBuilder.setName(new Name(neutronSubnet.getName())); + } catch (Exception e) { + LOG.info("Name '{}' of Neutron Subnet '{}' is ignored.", neutronSubnet.getName(), + neutronSubnet.getUuid().getValue()); + LOG.debug("Name exception", e); + } } subnetBuilder.setIpPrefix(Utils.createIpPrefix(neutronSubnet.getCidr())); + subnetBuilder.setVirtualRouterIp(virtualRouterIp); return subnetBuilder.build(); } @Override - public int canUpdate(NeutronSubnet delta, NeutronSubnet original) { - LOG.trace("canUpdate subnet - delta: {} original: {}", delta, original); - // nothing to consider - return StatusCode.OK; - } - - @Override - public void updated(NeutronSubnet subnet) { - LOG.trace("updated subnet - {}", subnet); - created(subnet); - } - - @Override - public int canDelete(NeutronSubnet subnet) { - LOG.trace("canDelete subnet - {}", subnet); - // nothing to consider - return StatusCode.OK; + public void onUpdated( + org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet oldItem, + org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet newItem, + Neutron oldNeutron, Neutron newNeutron) { + LOG.trace("updated subnet - {}", newItem); + onCreated(newItem, newNeutron); } @Override - public void deleted(NeutronSubnet neutronSubnet) { + public void onDeleted( + org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet neutronSubnet, + Neutron oldNeutron, Neutron newNeutron) { LOG.trace("deleted subnet - {}", neutronSubnet); ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction(); - SubnetId subnetId = new SubnetId(Utils.normalizeUuid(neutronSubnet.getID())); - TenantId tenantId = new TenantId(Utils.normalizeUuid(neutronSubnet.getTenantID())); + SubnetId subnetId = new SubnetId(neutronSubnet.getUuid().getValue()); + TenantId tenantId = new TenantId(neutronSubnet.getTenantId().getValue()); Optional potentialSubnet = DataStoreHelper.removeIfExists(LogicalDatastoreType.CONFIGURATION, IidFactory.subnetIid(tenantId, subnetId), rwTx); if (!potentialSubnet.isPresent()) { @@ -206,6 +141,10 @@ public class NeutronSubnetAware implements MappingProcessor { - - private static final Logger LOG = LoggerFactory.getLogger(NeutronSecurityGroupAware.class); - private final DataBroker dataProvider; - private final NeutronSecurityRuleAware secRuleAware; - private final SecGroupDao secGroupDao; - - public NeutronSecurityGroupAware(DataBroker dataProvider, NeutronSecurityRuleAware secRuleAware, - SecGroupDao secGroupDao) { - this.dataProvider = checkNotNull(dataProvider); - this.secRuleAware = checkNotNull(secRuleAware); - this.secGroupDao = checkNotNull(secGroupDao); - } - - @Override - public NeutronSecurityGroup convertToNeutron(SecurityGroup secGroup) { - NeutronSecurityGroup neutronSecGroup = new NeutronSecurityGroup(); - if (secGroup.getUuid() != null) { - neutronSecGroup.setID(secGroup.getUuid().getValue()); - } - if (secGroup.getName() != null) { - neutronSecGroup.setSecurityGroupName(secGroup.getName()); - } - if (secGroup.getTenantId() != null) { - neutronSecGroup.setTenantID(secGroup.getTenantId()); - } - if (secGroup.getSecurityRules() != null) { - neutronSecGroup.setSecurityRules(Lists.transform(secGroup.getSecurityRules(), - new Function() { - - @Override - public NeutronSecurityRule apply(Uuid uuid) { - NeutronSecurityRule rule = new NeutronSecurityRule(); - rule.setID(uuid.getValue()); - return rule; - } - })); - } - return neutronSecGroup; - } - - @Override - public int canCreate(NeutronSecurityGroup securityGroup) { - LOG.trace("canCreate securityGroup - {}", securityGroup); - // nothing to consider - return StatusCode.OK; - } - - @Override - public void created(NeutronSecurityGroup secGroup) { - LOG.trace("created securityGroup - {}", secGroup); - ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction(); - boolean isSecGroupCreated = addNeutronSecurityGroup(secGroup, rwTx); - if (isSecGroupCreated) { - DataStoreHelper.submitToDs(rwTx); - } else { - rwTx.cancel(); - } - } - - public boolean addNeutronSecurityGroup(NeutronSecurityGroup secGroup, ReadWriteTransaction rwTx) { - secGroupDao.addSecGroup(secGroup); - TenantId tenantId = new TenantId(Utils.normalizeUuid(secGroup.getSecurityGroupTenantID())); - EndpointGroupId providerEpgId = new EndpointGroupId(secGroup.getSecurityGroupUUID()); - EndpointGroupBuilder providerEpgBuilder = new EndpointGroupBuilder().setId(providerEpgId); - if (!Strings.isNullOrEmpty(secGroup.getSecurityGroupName())) { - try { - providerEpgBuilder.setName(new Name(secGroup.getSecurityGroupName())); - } catch (Exception e) { - LOG.info("Name '{}' of Neutron Security-group '{}' is ignored.", secGroup.getSecurityGroupName(), - secGroup.getSecurityGroupUUID()); - LOG.debug("Name exception", e); - } - } - if (!Strings.isNullOrEmpty(secGroup.getSecurityGroupDescription())) { - try { - providerEpgBuilder.setDescription(new Description(secGroup.getSecurityGroupDescription())); - } catch (Exception e) { - LOG.info("Description '{}' of Neutron Security-group '{}' is ignored.", - secGroup.getSecurityGroupDescription(), secGroup.getSecurityGroupUUID()); - LOG.debug("Description exception", e); - } - } - providerEpgBuilder.setIntraGroupPolicy(IntraGroupPolicy.RequireContract); - rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.endpointGroupIid(tenantId, providerEpgId), - providerEpgBuilder.build(), true); - List secRules = secGroup.getSecurityRules(); - SortedSecurityGroupRules sortedSecGrpRules = new SortedSecurityGroupRules(secRules); - ListMultimap secRuleByRemoteSecGrpId = sortedSecGrpRules.secRuleByRemoteSecGrpId; - for (EndpointGroupId consumerEpgId : secRuleByRemoteSecGrpId.keySet()) { - addEpgIfMissing(tenantId, consumerEpgId, rwTx); - boolean areSecRulesAdded = addNeutronSecurityRule(secRuleByRemoteSecGrpId.get(consumerEpgId), rwTx); - if (!areSecRulesAdded) { - return false; - } - } - ListMultimap secRuleByRemoteIpPrefix = sortedSecGrpRules.secRuleByRemoteIpPrefix; - for (IpPrefix remoteIpPrefex : secRuleByRemoteIpPrefix.keySet()) { - boolean areSecRulesAdded = addNeutronSecurityRule(secRuleByRemoteIpPrefix.get(remoteIpPrefex), rwTx); - if (!areSecRulesAdded) { - return false; - } - } - boolean areSecRulesAdded = addNeutronSecurityRule(sortedSecGrpRules.secRulesWithoutRemote, rwTx); - if (!areSecRulesAdded) { - return false; - } - return true; - } - - public static void addEpgIfMissing(TenantId tenantId, EndpointGroupId epgId, ReadWriteTransaction rwTx) { - InstanceIdentifier epgIid = IidFactory.endpointGroupIid(tenantId, epgId); - Optional potentialConsumerEpg = DataStoreHelper.readFromDs(LogicalDatastoreType.CONFIGURATION, - epgIid, rwTx); - if (!potentialConsumerEpg.isPresent()) { - EndpointGroup epg = new EndpointGroupBuilder().setId(epgId) - .setDescription( - new Description(MappingUtils.NEUTRON_GROUP - + "EPG was created just based on remote group ID from a security rule.")) - .setIntraGroupPolicy(IntraGroupPolicy.RequireContract) - .build(); - rwTx.put(LogicalDatastoreType.CONFIGURATION, epgIid, epg); - } - } - - private boolean addNeutronSecurityRule(List secRules, ReadWriteTransaction rwTx) { - for (NeutronSecurityRule secRule : secRules) { - boolean isSecRuleAdded = secRuleAware.addNeutronSecurityRule(secRule, rwTx); - if (!isSecRuleAdded) { - return false; - } - } - return true; - } - - @Override - public int canUpdate(NeutronSecurityGroup delta, NeutronSecurityGroup original) { - LOG.warn("canUpdate securityGroup - Never should be called " - + "- neutron API does not allow UPDATE on neutron security group. \nDelta: {} \nOriginal: {}", delta, - original); - return StatusCode.BAD_REQUEST; - } - - @Override - public void updated(NeutronSecurityGroup securityGroup) { - LOG.warn("updated securityGroup - Never should be called " - + "- neutron API does not allow UPDATE on neutron security group. \nSecurity group: {}", securityGroup); - } - - @Override - public int canDelete(NeutronSecurityGroup securityGroup) { - LOG.trace("canDelete securityGroup - {}", securityGroup); - // nothing to consider - return StatusCode.OK; - } - - @Override - public void deleted(NeutronSecurityGroup secGroup) { - LOG.trace("deleted securityGroup - {}", secGroup); - ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction(); - List secRules = secGroup.getSecurityRules(); - if (secRules != null) { - boolean areSecRulesDeleted = deleteNeutronSecurityRules(secRules, rwTx); - if (!areSecRulesDeleted) { - rwTx.cancel(); - return; - } - } - - TenantId tenantId = new TenantId(Utils.normalizeUuid(secGroup.getSecurityGroupTenantID())); - EndpointGroupId epgId = new EndpointGroupId(secGroup.getSecurityGroupUUID()); - secGroupDao.removeSecGroup(epgId); - - Optional potentialEpg = DataStoreHelper.removeIfExists(LogicalDatastoreType.CONFIGURATION, - IidFactory.endpointGroupIid(tenantId, epgId), rwTx); - if (!potentialEpg.isPresent()) { - LOG.warn("Illegal state - Endpoint group {} does not exist.", epgId.getValue()); - rwTx.cancel(); - return; - } - - DataStoreHelper.submitToDs(rwTx); - } - - private boolean deleteNeutronSecurityRules(List secRules, ReadWriteTransaction rwTx) { - for (NeutronSecurityRule secRule : secRules) { - boolean isSecRuleDeleted = secRuleAware.deleteNeutronSecurityRule(secRule, rwTx); - if (!isSecRuleDeleted) { - return false; - } - } - return true; - } - - private static final class SortedSecurityGroupRules { - - private final ListMultimap secRuleByRemoteSecGrpId; - private final ListMultimap secRuleByRemoteIpPrefix; - private final List secRulesWithoutRemote; - - private SortedSecurityGroupRules(List securityRules) { - Preconditions.checkNotNull(securityRules); - ListMultimap tmpSecRuleByRemoteSecGrpId = ArrayListMultimap.create(); - ListMultimap tmpSecRuleByRemoteIpPrefix = ArrayListMultimap.create(); - List tmpSecRulesWithoutRemote = new ArrayList<>(); - for (NeutronSecurityRule securityRule : securityRules) { - String remoteSecGroupId = securityRule.getSecurityRemoteGroupID(); - String remoteIpPrefix = securityRule.getSecurityRuleRemoteIpPrefix(); - boolean isRemoteSecGroupId = remoteSecGroupId != null && !"null".equals(remoteSecGroupId); - boolean isRemoteIpPrefix = remoteIpPrefix != null && !"null".equals(remoteIpPrefix); - if (isRemoteSecGroupId && isRemoteIpPrefix) { - throw new IllegalArgumentException("Either remote group id or ip prefix " - + "must be speciefied in neutron security group rule." + securityRule.toString()); - } - if (isRemoteSecGroupId) { - tmpSecRuleByRemoteSecGrpId.put(new EndpointGroupId(remoteSecGroupId), securityRule); - } else if (isRemoteIpPrefix) { - tmpSecRuleByRemoteIpPrefix.put(Utils.createIpPrefix(remoteIpPrefix), securityRule); - } else { - tmpSecRulesWithoutRemote.add(securityRule); - } - } - secRuleByRemoteSecGrpId = ImmutableListMultimap.copyOf(tmpSecRuleByRemoteSecGrpId); - secRuleByRemoteIpPrefix = ImmutableListMultimap.copyOf(tmpSecRuleByRemoteIpPrefix); - secRulesWithoutRemote = ImmutableList.copyOf(tmpSecRulesWithoutRemote); - } - } -} diff --git a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/group/SecGroupDao.java b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/group/SecGroupDao.java deleted file mode 100644 index 78355ae9c..000000000 --- a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/group/SecGroupDao.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.group; - -import static com.google.common.base.Preconditions.checkNotNull; - -import java.util.HashMap; -import java.util.Map; - -import org.opendaylight.groupbasedpolicy.neutron.mapper.util.Utils; -import org.opendaylight.neutron.spi.NeutronSecurityGroup; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.EndpointGroupId; - -import com.google.common.base.Strings; - -public class SecGroupDao { - - private final Map secGroupById = new HashMap<>(); - - public void addSecGroup(NeutronSecurityGroup secGrp) { - checkNotNull(secGrp); - secGroupById.put(new EndpointGroupId(Utils.normalizeUuid(secGrp.getSecurityGroupUUID())), secGrp); - } - - public NeutronSecurityGroup getSecGroupById(EndpointGroupId id) { - return secGroupById.get(id); - } - - /** - * @param id {@link EndpointGroupId} EndpointGroupId - * @return {@code empty string} if security group with given ID does not exist; returns - * {@code name of security group} if has some; otherwise security group id - */ - public String getNameOrIdOfSecGroup(EndpointGroupId id) { - NeutronSecurityGroup secGrp = secGroupById.get(checkNotNull(id)); - if (secGrp == null) { - return ""; - } - if (!Strings.isNullOrEmpty(secGrp.getSecurityGroupName())) { - return secGrp.getSecurityGroupName(); - } - return id.getValue(); - } - - public void removeSecGroup(EndpointGroupId id) { - secGroupById.remove(checkNotNull(id)); - } - -} diff --git a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/NeutronGbpMapperServiceImpl.java b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/NeutronGbpMapperServiceImpl.java index d6a545126..480831d82 100644 --- a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/NeutronGbpMapperServiceImpl.java +++ b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/NeutronGbpMapperServiceImpl.java @@ -11,21 +11,28 @@ package org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.rule; import static com.google.common.base.Preconditions.checkNotNull; import java.util.List; +import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.opendaylight.controller.md.sal.binding.api.DataBroker; import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction; +import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; +import org.opendaylight.groupbasedpolicy.neutron.mapper.util.SecurityRuleUtils; import org.opendaylight.groupbasedpolicy.util.DataStoreHelper; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.ChangeActionOfSecurityGroupRulesInput; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.NeutronGbpMapperService; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.change.action.of.security.group.rules.input.SecurityGroupRule; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRule; import org.opendaylight.yangtools.yang.common.RpcError.ErrorType; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; import org.opendaylight.yangtools.yang.common.RpcResult; import org.opendaylight.yangtools.yang.common.RpcResultBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.google.common.base.Optional; import com.google.common.util.concurrent.Futures; public class NeutronGbpMapperServiceImpl implements NeutronGbpMapperService { @@ -51,11 +58,31 @@ public class NeutronGbpMapperServiceImpl implements NeutronGbpMapperService { } ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction(); + Optional potentialNeutron; + try { + potentialNeutron = rwTx.read(LogicalDatastoreType.CONFIGURATION, InstanceIdentifier.builder(Neutron.class).build()).get(); + } catch (InterruptedException | ExecutionException e) { + LOG.error("Exception during neutron reading.", e); + return Futures.immediateFuture(RpcResultBuilder.failed() + .withError(ErrorType.PROTOCOL, "Cannot read from CONF DS.") + .build()); + } + if (!potentialNeutron.isPresent()) { + return Futures.immediateFuture(RpcResultBuilder.failed() + .withError(ErrorType.PROTOCOL, "No neutron data in CONF DS.") + .build()); + } + Neutron neutron = potentialNeutron.get(); for (SecurityGroupRule secGrpRule : securityGroupRules) { Uuid uuid = secGrpRule.getUuid(); + Optional potentialSecRule = SecurityRuleUtils.findSecurityRule(uuid, neutron.getSecurityRules()); + if (!potentialSecRule.isPresent()) { + LOG.warn("Security rule {} does not exist.", uuid); + continue; + } LOG.trace("Changing action to {} in security group rule {}", input.getAction().getActionChoice(), uuid); boolean isSuccessful = - secRuleAware.changeActionOfNeutronSecurityRule(uuid, input.getAction().getActionChoice(), rwTx); + secRuleAware.changeActionOfNeutronSecurityRule(potentialSecRule.get(), input.getAction().getActionChoice(), neutron, rwTx); if (!isSuccessful) { rwTx.cancel(); LOG.warn("Changing action to {} in security group rule {} was not successful.", diff --git a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/NeutronSecurityRuleAware.java b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/NeutronSecurityRuleAware.java index 867e8b542..096f0ad5a 100644 --- a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/NeutronSecurityRuleAware.java +++ b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/NeutronSecurityRuleAware.java @@ -12,19 +12,19 @@ import static com.google.common.base.Preconditions.checkNotNull; import java.util.Set; +import org.opendaylight.controller.config.yang.config.neutron_mapper.impl.NeutronMapperModule; import org.opendaylight.controller.md.sal.binding.api.DataBroker; import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction; import org.opendaylight.controller.md.sal.binding.api.WriteTransaction; import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; import org.opendaylight.groupbasedpolicy.api.sf.ChainActionDefinition; -import org.opendaylight.groupbasedpolicy.dto.EgKey; -import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.MappingProcessor; -import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.StatusCode; -import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.group.SecGroupDao; +import org.opendaylight.groupbasedpolicy.dto.EpgKeyDto; +import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.NeutronAware; import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils; +import org.opendaylight.groupbasedpolicy.neutron.mapper.util.SecurityGroupUtils; +import org.opendaylight.groupbasedpolicy.neutron.mapper.util.SecurityRuleUtils; import org.opendaylight.groupbasedpolicy.util.DataStoreHelper; import org.opendaylight.groupbasedpolicy.util.IidFactory; -import org.opendaylight.neutron.spi.NeutronSecurityRule; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ActionName; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ClauseName; @@ -46,130 +46,52 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.subject.feature.instances.ActionInstance; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.subject.feature.instances.ActionInstanceBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.subject.feature.instances.ClassifierInstance; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionBase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionEgress; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionIngress; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeBase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeV4; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeV6; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolBase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolIcmp; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolIcmpV6; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolTcp; -import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolUdp; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.security.groups.SecurityGroup; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.SecurityRules; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRule; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Strings; +import com.google.common.base.Optional; import com.google.common.collect.HashMultiset; -import com.google.common.collect.ImmutableBiMap; import com.google.common.collect.ImmutableList; import com.google.common.collect.Multiset; import com.google.common.collect.Sets; -public class NeutronSecurityRuleAware implements MappingProcessor { +public class NeutronSecurityRuleAware implements NeutronAware { private static final Logger LOG = LoggerFactory.getLogger(NeutronSecurityRuleAware.class); + public static final InstanceIdentifier SECURITY_RULE_WILDCARD_IID = + InstanceIdentifier.builder(Neutron.class).child(SecurityRules.class).child(SecurityRule.class).build(); private static final String CONTRACT_PROVIDER = "Contract provider: "; private final DataBroker dataProvider; - private final SecRuleDao secRuleDao; - private final SecGroupDao secGroupDao; private final Multiset> createdClassifierInstances; private final Multiset> createdActionInstances; final static String PROVIDED_BY = "provided_by-"; final static String POSSIBLE_CONSUMER = "possible_consumer-"; - public NeutronSecurityRuleAware(DataBroker dataProvider, SecRuleDao secRuleDao, SecGroupDao secGroupDao) { - this(dataProvider, secRuleDao, secGroupDao, HashMultiset.>create(), + public NeutronSecurityRuleAware(DataBroker dataProvider) { + this(dataProvider, HashMultiset.>create(), HashMultiset.>create()); } @VisibleForTesting - NeutronSecurityRuleAware(DataBroker dataProvider, SecRuleDao secRuleDao, SecGroupDao secGroupDao, + NeutronSecurityRuleAware(DataBroker dataProvider, Multiset> classifierInstanceNames, Multiset> createdActionInstances) { this.dataProvider = checkNotNull(dataProvider); - this.secRuleDao = checkNotNull(secRuleDao); - this.secGroupDao = checkNotNull(secGroupDao); this.createdClassifierInstances = checkNotNull(classifierInstanceNames); this.createdActionInstances = checkNotNull(createdActionInstances); } - // copied from Neutron's NeutronSecurityRuleInterface - private static final ImmutableBiMap,String> DIRECTION_MAP - = new ImmutableBiMap.Builder,String>() - .put(DirectionEgress.class,"egress") - .put(DirectionIngress.class,"ingress") - .build(); - - // copied from Neutron's NeutronSecurityRuleInterface - private static final ImmutableBiMap,String> ETHERTYPE_MAP - = new ImmutableBiMap.Builder,String>() - .put(EthertypeV4.class,"IPv4") - .put(EthertypeV6.class,"IPv6") - .build(); - - // copied from Neutron's NeutronSecurityRuleInterface - private static final ImmutableBiMap,String> PROTOCOL_MAP - = new ImmutableBiMap.Builder,String>() - .put(ProtocolIcmp.class,"icmp") - .put(ProtocolTcp.class,"tcp") - .put(ProtocolUdp.class,"udp") - .put(ProtocolIcmpV6.class,"icmpv6") - .build(); - - @Override - public NeutronSecurityRule convertToNeutron(SecurityRule rule) { - // copied from Neutron's NeutronSecurityRuleInterface - NeutronSecurityRule answer = new NeutronSecurityRule(); - if (rule.getTenantId() != null) { - answer.setTenantID(rule.getTenantId()); - } - if (rule.getDirection() != null) { - answer.setSecurityRuleDirection(DIRECTION_MAP.get(rule.getDirection())); - } - if (rule.getSecurityGroupId() != null) { - answer.setSecurityRuleGroupID(rule.getSecurityGroupId().getValue()); - } - if (rule.getRemoteGroupId() != null) { - answer.setSecurityRemoteGroupID(rule.getRemoteGroupId().getValue()); - } - if (rule.getRemoteIpPrefix() != null) { - answer.setSecurityRuleRemoteIpPrefix(new String(rule.getRemoteIpPrefix().getValue())); - } - if (rule.getProtocol() != null) { - answer.setSecurityRuleProtocol(PROTOCOL_MAP.get(rule.getProtocol())); - } - if (rule.getEthertype() != null) { - answer.setSecurityRuleEthertype(ETHERTYPE_MAP.get(rule.getEthertype())); - } - if (rule.getPortRangeMin() != null) { - answer.setSecurityRulePortMin(rule.getPortRangeMin()); - } - if (rule.getPortRangeMax() != null) { - answer.setSecurityRulePortMax(rule.getPortRangeMax()); - } - if (rule.getId() != null) { - answer.setID(rule.getId().getValue()); - } - return answer; - } - - @Override - public int canCreate(NeutronSecurityRule securityRule) { - LOG.trace("canCreate securityRule - {}", securityRule); - // nothing to consider - return StatusCode.OK; - } - @Override - public void created(NeutronSecurityRule securityRule) { - LOG.trace("created securityRule - {}", securityRule); + public void onCreated(SecurityRule secRule, Neutron neutron) { + LOG.trace("created securityRule - {}", secRule); ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction(); - boolean isNeutronSecurityRuleAdded = addNeutronSecurityRule(securityRule, rwTx); + boolean isNeutronSecurityRuleAdded = addNeutronSecurityRule(secRule, neutron, rwTx); if (isNeutronSecurityRuleAdded) { DataStoreHelper.submitToDs(rwTx); } else { @@ -177,56 +99,31 @@ public class NeutronSecurityRuleAware implements MappingProcessor providerSecGroup = + SecurityGroupUtils.findSecurityGroup(secRule.getSecurityGroupId(), neutron.getSecurityGroups()); + if (!providerSecGroup.isPresent()) { + LOG.error("Neutron Security Group with UUID {} does not exist but it is in {}", secRule.getSecurityGroupId().getValue(), + secRule); + throw new IllegalStateException( + "Neutron Security Group with UUID " + secRule.getSecurityGroupId().getValue() + " does not exist."); + } + return new Description(CONTRACT_PROVIDER + SecurityGroupUtils.getNameOrUuid(providerSecGroup.get())); + } + + return new Description(CONTRACT_PROVIDER + secRule.getSecurityGroupId()); + } + + @VisibleForTesting + static SingleRuleContract createSingleRuleContract(SecurityRule secRule, Description contractDescription, ActionChoice action) { + if (secRule.getRemoteIpPrefix() != null) { return new SingleRuleContract(secRule, 0, contractDescription, action); } return new SingleRuleContract(secRule, 400, contractDescription, action); } @VisibleForTesting - void designContractsBetweenProviderAndConsumer(TenantId tenantId, EndpointGroupId provEpgId, - EndpointGroupId consEpgId, ReadWriteTransaction rwTx) { - Set provSecRules = getProvidedSecRulesBetween(provEpgId, consEpgId); - Set consSecRules = getProvidedSecRulesBetween(consEpgId, provEpgId); - for (NeutronSecurityRule provSecRule : provSecRules) { + void designContractsBetweenProviderAndConsumer(TenantId tenantId, Uuid provSecGroupId, Uuid consSecGroupId, + Neutron neutron, ReadWriteTransaction rwTx) { + Set provSecRules = getProvidedSecRulesBetween(provSecGroupId, consSecGroupId, neutron); + Set consSecRules = getProvidedSecRulesBetween(consSecGroupId, provSecGroupId, neutron); + EndpointGroupId consEpgId = new EndpointGroupId(consSecGroupId.getValue()); + for (SecurityRule provSecRule : provSecRules) { if (isProviderSecRuleSuitableForConsumerSecRules(provSecRule, consSecRules)) { - SelectorName consumerSelector = getSelectorNameWithProvider(provSecRule); + SelectorName consumerSelector = getSelectorNameWithProvider(provSecRule, neutron); ContractId contractId = SecRuleEntityDecoder.getContractId(provSecRule); - writeConsumerNamedSelectorToEpg(consumerSelector, contractId, new EgKey(tenantId, consEpgId), rwTx); + writeConsumerNamedSelectorToEpg(consumerSelector, contractId, new EpgKeyDto(consEpgId, tenantId), rwTx); } // TODO add case when port ranges overlap } } @VisibleForTesting - Set getProvidedSecRulesBetween(EndpointGroupId provEpgId, EndpointGroupId consEpgId) { - return Sets.union(secRuleDao.getSecRulesBySecGrpIdAndRemoteSecGrpId(provEpgId, consEpgId), - secRuleDao.getSecRulesWithoutRemoteSecGrpBySecGrpId(provEpgId)); + Set getProvidedSecRulesBetween(Uuid provSecGroup, Uuid consSecGroup, Neutron neutron) { + return Sets.union(SecurityRuleUtils.findSecurityRulesBySecGroupAndRemoteSecGroup(provSecGroup, consSecGroup, neutron), + SecurityRuleUtils.findSecurityRulesBySecGroupAndRemoteSecGroup(provSecGroup, null, neutron)); } @VisibleForTesting - static boolean isProviderSecRuleSuitableForConsumerSecRules(NeutronSecurityRule provSecRule, - Set consSecRules) { + static boolean isProviderSecRuleSuitableForConsumerSecRules(SecurityRule provSecRule, + Set consSecRules) { Direction directionProvSecRule = SecRuleEntityDecoder.getDirection(provSecRule); - for (NeutronSecurityRule consSecRule : consSecRules) { + for (SecurityRule consSecRule : consSecRules) { Direction directionConsSecRule = SecRuleEntityDecoder.getDirection(consSecRule); if (isDirectionOpposite(directionProvSecRule, directionConsSecRule) && isOneWithinTwo(provSecRule, consSecRule)) { @@ -280,23 +194,46 @@ public class NeutronSecurityRuleAware implements MappingProcessor provSecRules = getProvidedSecRulesBetween(provEpgId, consEpgId); - Set consSecRules = getProvidedSecRulesBetween(consEpgId, provEpgId); - for (NeutronSecurityRule provSecRule : provSecRules) { + void undesignContractsBetweenProviderAndConsumer(TenantId tenantId, Uuid provSecGroupId, + Uuid consSecGroupId, SecurityRule removedSecRule, Neutron neutron, ReadWriteTransaction rwTx) { + Set provSecRules = getProvidedSecRulesBetween(provSecGroupId, consSecGroupId, neutron); + Set consSecRules = getProvidedSecRulesBetween(consSecGroupId, provSecGroupId, neutron); + EndpointGroupId consEpgId = new EndpointGroupId(consSecGroupId.getValue()); + for (SecurityRule provSecRule : provSecRules) { if (isProvidersSecRuleSuitableForConsumersSecRulesAndGoodToRemove(provSecRule, consSecRules, removedSecRule)) { - SelectorName consumerSelector = getSelectorNameWithProvider(provSecRule); - deleteConsumerNamedSelector(consumerSelector, new EgKey(tenantId, consEpgId), rwTx); + SelectorName consumerSelector = getSelectorNameWithProvider(provSecRule, neutron); + deleteConsumerNamedSelector(consumerSelector, new EpgKeyDto(consEpgId, tenantId), rwTx); } // TODO add case when port ranges overlap } } @VisibleForTesting - static boolean isProvidersSecRuleSuitableForConsumersSecRulesAndGoodToRemove(NeutronSecurityRule provSecRule, - Set consSecRules, NeutronSecurityRule removedSecRule) { + static boolean isProvidersSecRuleSuitableForConsumersSecRulesAndGoodToRemove(SecurityRule provSecRule, + Set consSecRules, SecurityRule removedSecRule) { Direction directionProvSecRule = SecRuleEntityDecoder.getDirection(provSecRule); - for (NeutronSecurityRule consSecRule : consSecRules) { + for (SecurityRule consSecRule : consSecRules) { if (isRuleIdEqual(removedSecRule, consSecRule) || isRuleIdEqual(removedSecRule, provSecRule)) { Direction directionConsSecRule = SecRuleEntityDecoder.getDirection(consSecRule); if (isDirectionOpposite(directionProvSecRule, directionConsSecRule) @@ -413,23 +336,23 @@ public class NeutronSecurityRuleAware implements MappingProcessor providerSelectorIid = IidFactory.providerNamedSelectorIid( - providerEpgKey.getTenantId(), providerEpgKey.getEgId(), providerSelector); + providerEpgKey.getTenantId(), providerEpgKey.getEpgId(), providerSelector); DataStoreHelper.removeIfExists(LogicalDatastoreType.CONFIGURATION, providerSelectorIid, rwTx); } - private void deleteConsumerNamedSelector(SelectorName consumerSelector, EgKey consumerEpgKey, + private void deleteConsumerNamedSelector(SelectorName consumerSelector, EpgKeyDto consumerEpgKey, ReadWriteTransaction rwTx) { InstanceIdentifier consumerSelectorIid = IidFactory.consumerNamedSelectorIid( - consumerEpgKey.getTenantId(), consumerEpgKey.getEgId(), consumerSelector); + consumerEpgKey.getTenantId(), consumerEpgKey.getEpgId(), consumerSelector); DataStoreHelper.removeIfExists(LogicalDatastoreType.CONFIGURATION, consumerSelectorIid, rwTx); } @@ -453,25 +376,65 @@ public class NeutronSecurityRuleAware implements MappingProcessor potentialConsumerSecGroup = + SecurityGroupUtils.findSecurityGroup(secRule.getRemoteGroupId(), neutron.getSecurityGroups()); + if (!potentialConsumerSecGroup.isPresent()) { + LOG.error("Neutron Security Group with UUID {} does not exist but it is in {}", + consumerSecGroupId.getValue(), secRule); + throw new IllegalStateException( + "Neutron Security Group with UUID " + consumerSecGroupId.getValue() + " does not exist."); + } + selectorNameBuilder.append(MappingUtils.NAME_DOUBLE_DELIMETER) .append(POSSIBLE_CONSUMER) - .append(secGroupDao.getNameOrIdOfSecGroup(consumerEpgId)); + .append(SecurityGroupUtils.getNameOrUuid(potentialConsumerSecGroup.get())); + return new SelectorName(selectorNameBuilder.toString()); } + + selectorNameBuilder.append(MappingUtils.NAME_DOUBLE_DELIMETER) + .append(POSSIBLE_CONSUMER) + .append(consumerSecGroupId.getValue()); return new SelectorName(selectorNameBuilder.toString()); } - private SelectorName getSelectorNameWithProvider(NeutronSecurityRule secRule) { + private SelectorName getSelectorNameWithProvider(SecurityRule secRule, Neutron neutron) { ClauseName clauseName = SecRuleNameDecoder.getClauseName(secRule); - EndpointGroupId providerEpgId = SecRuleEntityDecoder.getProviderEpgId(secRule); + Uuid providerSecGroupId = secRule.getSecurityGroupId(); + + // we cannot use name of security group in selector, because name can be changed + // therefore name is used only in debug mode + if (NeutronMapperModule.isDebugEnabled()) { + Optional potentialProviderSecGroup = + SecurityGroupUtils.findSecurityGroup(secRule.getSecurityGroupId(), neutron.getSecurityGroups()); + if (!potentialProviderSecGroup.isPresent()) { + LOG.error("Neutron Security Group with UUID {} does not exist but it is in {}", + providerSecGroupId.getValue(), secRule); + throw new IllegalStateException( + "Neutron Security Group with UUID " + providerSecGroupId.getValue() + " does not exist."); + } + String selectorName = new StringBuilder().append(clauseName.getValue()) + .append(MappingUtils.NAME_DOUBLE_DELIMETER) + .append(PROVIDED_BY) + .append(SecurityGroupUtils.getNameOrUuid(potentialProviderSecGroup.get())) + .toString(); + return new SelectorName(selectorName); + } + String selectorName = new StringBuilder().append(clauseName.getValue()) .append(MappingUtils.NAME_DOUBLE_DELIMETER) .append(PROVIDED_BY) - .append(secGroupDao.getNameOrIdOfSecGroup(providerEpgId)) + .append(providerSecGroupId.getValue()) .toString(); return new SelectorName(selectorName); } @@ -482,7 +445,7 @@ public class NeutronSecurityRuleAware implements MappingProcessor secRulesByOwnerSecGrpId = HashMultimap.create(); - private final SetMultimap secRulesByRemoteSecGrpId = - HashMultimap.create(); - private final Map secRuleByUuid = new HashMap<>(); - - public void addSecRule(NeutronSecurityRule secRule) { - Preconditions.checkNotNull(secRule); - EndpointGroupId ownerSecGrp = SecRuleEntityDecoder.getProviderEpgId(secRule); - EndpointGroupId remoteSecGrp = SecRuleEntityDecoder.getConsumerEpgId(secRule); - secRulesByOwnerSecGrpId.put(ownerSecGrp, secRule); - secRulesByRemoteSecGrpId.put(new OwnerAndRemoteOfSecRule(ownerSecGrp, remoteSecGrp), secRule); - secRuleByUuid.put(new Uuid(secRule.getID()), secRule); - } - - public Set getSecRulesByOwnerSecGrpId(EndpointGroupId secGrpId) { - return secRulesByOwnerSecGrpId.get(secGrpId); - } - - public Set getSecRulesBySecGrpIdAndRemoteSecGrpId(EndpointGroupId ownerSecGrpId, - @Nullable EndpointGroupId remoteSecGrpId) { - return secRulesByRemoteSecGrpId.get(new OwnerAndRemoteOfSecRule(ownerSecGrpId, remoteSecGrpId)); - } - - public Set getSecRulesWithoutRemoteSecGrpBySecGrpId(EndpointGroupId ownerSecGrpId) { - return secRulesByRemoteSecGrpId.get(new OwnerAndRemoteOfSecRule(ownerSecGrpId, null)); - } - - public NeutronSecurityRule getSecRuleByUuid(Uuid secRule) { - return secRuleByUuid.get(secRule); - } - - public Set getAllOwnerSecGrps() { - return secRulesByOwnerSecGrpId.keySet(); - } - - public void removeSecRule(NeutronSecurityRule secRule) { - Preconditions.checkNotNull(secRule); - EndpointGroupId ownerSecGrp = SecRuleEntityDecoder.getProviderEpgId(secRule); - EndpointGroupId remoteSecGrp = SecRuleEntityDecoder.getConsumerEpgId(secRule); - secRulesByOwnerSecGrpId.remove(ownerSecGrp, secRule); - secRulesByRemoteSecGrpId.remove(new OwnerAndRemoteOfSecRule(ownerSecGrp, remoteSecGrp), secRule); - secRuleByUuid.remove(new Uuid(secRule.getID())); - } - - static class OwnerAndRemoteOfSecRule { - - private final EndpointGroupId owner; - private final EndpointGroupId remote; - - private OwnerAndRemoteOfSecRule(EndpointGroupId owner, EndpointGroupId remote) { - this.owner = Preconditions.checkNotNull(owner); - this.remote = remote; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((owner == null) ? 0 : owner.hashCode()); - result = prime * result + ((remote == null) ? 0 : remote.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - OwnerAndRemoteOfSecRule other = (OwnerAndRemoteOfSecRule) obj; - if (owner == null) { - if (other.owner != null) - return false; - } else if (!owner.equals(other.owner)) - return false; - if (remote == null) { - if (other.remote != null) - return false; - } else if (!remote.equals(other.remote)) - return false; - return true; - } - - } - -} diff --git a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SecRuleEntityDecoder.java b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SecRuleEntityDecoder.java index c924191fb..579e858f8 100755 --- a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SecRuleEntityDecoder.java +++ b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SecRuleEntityDecoder.java @@ -13,22 +13,15 @@ import static com.google.common.base.Preconditions.checkNotNull; import java.util.ArrayList; import java.util.List; -import javax.annotation.Nullable; - import org.opendaylight.groupbasedpolicy.api.sf.EtherTypeClassifierDefinition; import org.opendaylight.groupbasedpolicy.api.sf.IpProtoClassifierDefinition; import org.opendaylight.groupbasedpolicy.api.sf.L4ClassifierDefinition; import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils; -import org.opendaylight.groupbasedpolicy.neutron.mapper.util.NeutronUtils; -import org.opendaylight.groupbasedpolicy.neutron.mapper.util.Utils; -import org.opendaylight.neutron.spi.NeutronSecurityRule; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ClassifierName; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ContractId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.EndpointGroupId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ParameterName; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.SubjectName; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.change.action.of.security.group.rules.input.action.ActionChoice; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.change.action.of.security.group.rules.input.action.action.choice.AllowActionCase; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.change.action.of.security.group.rules.input.action.action.choice.SfcActionCase; @@ -51,8 +44,19 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.contract.clause.ConsumerMatchersBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.subject.feature.instances.ClassifierInstance; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.subject.feature.instances.ClassifierInstanceBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionBase; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionEgress; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionIngress; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeBase; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeV4; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeV6; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolBase; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolIcmp; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolIcmpV6; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolTcp; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolUdp; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRule; -import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; public class SecRuleEntityDecoder { @@ -61,30 +65,15 @@ public class SecRuleEntityDecoder { throw new UnsupportedOperationException("Cannot create an instace."); } - public static TenantId getTenantId(NeutronSecurityRule secRule) { - return new TenantId(Utils.normalizeUuid(secRule.getSecurityRuleTenantID())); - } - - public static EndpointGroupId getProviderEpgId(NeutronSecurityRule secRule) { - return new EndpointGroupId(Utils.normalizeUuid(secRule.getSecurityRuleGroupID())); + public static ContractId getContractId(SecurityRule secRule) { + return new ContractId(secRule.getId().getValue()); } - public static @Nullable EndpointGroupId getConsumerEpgId(NeutronSecurityRule secRule) { - if (Strings.isNullOrEmpty(secRule.getSecurityRemoteGroupID())) { - return null; - } - return new EndpointGroupId(Utils.normalizeUuid(secRule.getSecurityRemoteGroupID())); - } - - public static ContractId getContractId(NeutronSecurityRule secRule) { - return new ContractId(Utils.normalizeUuid(secRule.getSecurityRuleUUID())); - } - - public static ClassifierInstance getClassifierInstance(NeutronSecurityRule secRule) { + public static ClassifierInstance getClassifierInstance(SecurityRule secRule) { ClassifierInstanceBuilder classifierBuilder = new ClassifierInstanceBuilder(); List params = new ArrayList<>(); - Integer portMin = secRule.getSecurityRulePortMin(); - Integer portMax = secRule.getSecurityRulePortMax(); + Integer portMin = secRule.getPortRangeMin(); + Integer portMax = secRule.getPortRangeMax(); if (portMin != null && portMax != null) { classifierBuilder.setClassifierDefinitionId(L4ClassifierDefinition.DEFINITION.getId()); if (portMin.equals(portMax)) { @@ -129,7 +118,7 @@ public class SecRuleEntityDecoder { return null; } - public static ClassifierRef getClassifierRef(NeutronSecurityRule secRule) { + public static ClassifierRef getClassifierRef(SecurityRule secRule) { checkNotNull(secRule); ClassifierName classifierInstanceName = SecRuleNameDecoder.getClassifierInstanceName(secRule); ClassifierRefBuilder classifierRefBuilder = new ClassifierRefBuilder() @@ -142,42 +131,44 @@ public class SecRuleEntityDecoder { /** * @param secRule - * @return direction resolved from {@link NeutronSecurityRule#getSecurityRuleDirection()} + * @return direction resolved from {@link SecurityRule#getDirection()} * @throws IllegalArgumentException if return value of - * {@link NeutronSecurityRule#getSecurityRuleDirection()} is other than "ingress" or - * "egress" + * {@link SecurityRule#getDirection()} is other than {@link DirectionIngress} or + * {@link DirectionEgress} */ - public static Direction getDirection(NeutronSecurityRule secRule) { - String direction = secRule.getSecurityRuleDirection(); - if (NeutronUtils.INGRESS.equals(direction)) { + public static Direction getDirection(SecurityRule secRule) { + Class direction = secRule.getDirection(); + if (direction == null) { + throw new IllegalArgumentException("Direction cannot be null."); + } + if (direction.isAssignableFrom(DirectionIngress.class)) { return Direction.In; } - if (NeutronUtils.EGRESS.equals(direction)) { + if (direction.isAssignableFrom(DirectionEgress.class)) { return Direction.Out; } throw new IllegalArgumentException("Direction " + direction + " from security group rule " - + secRule.getSecurityRuleUUID() + " is not supported. Direction can be only 'ingress' or 'egress'."); + + secRule + " is not supported. Direction can be only 'ingress' or 'egress'."); } /** - * @param secRule {@link NeutronSecurityRule#getSecurityRuleRemoteIpPrefix()} is used for EIC + * @param secRule {@link SecurityRule#getRemoteIpPrefix()} is used for EIC * and subject selection * @return clause with the subject and with a consumer matcher containing EIC */ - public static Clause getClause(NeutronSecurityRule secRule) { + public static Clause getClause(SecurityRule secRule) { checkNotNull(secRule); SubjectName subjectName = SecRuleNameDecoder.getSubjectName(secRule); ClauseBuilder clauseBuilder = new ClauseBuilder().setSubjectRefs(ImmutableList.of(subjectName)).setName(SecRuleNameDecoder.getClauseName(secRule)); - String remoteIpPrefix = secRule.getSecurityRuleRemoteIpPrefix(); - if (!Strings.isNullOrEmpty(remoteIpPrefix)) { + IpPrefix remoteIpPrefix = secRule.getRemoteIpPrefix(); + if (remoteIpPrefix != null) { clauseBuilder.setConsumerMatchers(createConsumerMatchersWithEic(remoteIpPrefix)); } return clauseBuilder.build(); } - private static ConsumerMatchers createConsumerMatchersWithEic(String remoteIpPrefix) { - IpPrefix ipPrefix = Utils.createIpPrefix(remoteIpPrefix); + private static ConsumerMatchers createConsumerMatchersWithEic(IpPrefix ipPrefix) { PrefixConstraint consumerPrefixConstraint = new PrefixConstraintBuilder().setIpPrefix(ipPrefix).build(); EndpointIdentificationConstraints eic = new EndpointIdentificationConstraintsBuilder() @@ -187,13 +178,13 @@ public class SecRuleEntityDecoder { return new ConsumerMatchersBuilder().setEndpointIdentificationConstraints(eic).build(); } - public static boolean isEtherTypeOfOneWithinTwo(NeutronSecurityRule one, NeutronSecurityRule two) { + public static boolean isEtherTypeOfOneWithinTwo(SecurityRule one, SecurityRule two) { Long oneEtherType = getEtherType(one); Long twoEtherType = getEtherType(two); return twoIsNullOrEqualsOne(oneEtherType, twoEtherType); } - public static boolean isProtocolOfOneWithinTwo(NeutronSecurityRule one, NeutronSecurityRule two) { + public static boolean isProtocolOfOneWithinTwo(SecurityRule one, SecurityRule two) { Long oneProtocol = getProtocol(one); Long twoProtocol = getProtocol(two); return twoIsNullOrEqualsOne(oneProtocol, twoProtocol); @@ -207,11 +198,11 @@ public class SecRuleEntityDecoder { return false; } - public static boolean isPortsOfOneWithinTwo(NeutronSecurityRule one, NeutronSecurityRule two) { - Integer onePortMin = one.getSecurityRulePortMin(); - Integer onePortMax = one.getSecurityRulePortMax(); - Integer twoPortMin = two.getSecurityRulePortMin(); - Integer twoPortMax = two.getSecurityRulePortMax(); + public static boolean isPortsOfOneWithinTwo(SecurityRule one, SecurityRule two) { + Integer onePortMin = one.getPortRangeMin(); + Integer onePortMax = one.getPortRangeMax(); + Integer twoPortMin = two.getPortRangeMin(); + Integer twoPortMax = two.getPortRangeMax(); if (twoPortMin == null && twoPortMax == null) { return true; } @@ -224,22 +215,21 @@ public class SecRuleEntityDecoder { /** * @param secRule - * @return {@code null} if {@link NeutronSecurityRule#getSecurityRuleEthertype()} is null or - * empty; value of {@link EtherTypeClassifierDefinition#IPv4_VALUE} or - * {@link EtherTypeClassifierDefinition#IPv6_VALUE} + * @return {@code null} if {@link SecurityRule#getEthertype()} is null; Otherwise ethertype + * number * @throws IllegalArgumentException if return value of - * {@link NeutronSecurityRule#getSecurityRuleEthertype()} is not empty/null and is other - * than "IPv4" or "IPv6" + * {@link SecurityRule#getEthertype()} is other {@link EthertypeV4} or + * {@link EthertypeV6} */ - public static Long getEtherType(NeutronSecurityRule secRule) { - String ethertype = secRule.getSecurityRuleEthertype(); - if (Strings.isNullOrEmpty(ethertype)) { + public static Long getEtherType(SecurityRule secRule) { + Class ethertype = secRule.getEthertype(); + if (ethertype == null) { return null; } - if (NeutronUtils.IPv4.equals(ethertype)) { + if (ethertype.isAssignableFrom(EthertypeV4.class)) { return EtherTypeClassifierDefinition.IPv4_VALUE; } - if (NeutronUtils.IPv6.equals(ethertype)) { + if (ethertype.isAssignableFrom(EthertypeV6.class)) { return EtherTypeClassifierDefinition.IPv6_VALUE; } throw new IllegalArgumentException("Ethertype " + ethertype + " is not supported."); @@ -247,36 +237,28 @@ public class SecRuleEntityDecoder { /** * @param secRule - * @return {@code null} if {@link NeutronSecurityRule#getSecurityRuleProtocol()} is null or - * empty; Otherwise protocol number + * @return {@code null} if {@link SecurityRule#getProtocol()} is null; Otherwise protocol number * @throws IllegalArgumentException if return value of - * {@link NeutronSecurityRule#getSecurityRuleProtocol()} is not empty/null and is other - * than "tcp", "udp", "icmp", "icmpv6" or string values that can be decoded to {@link Short}. + * {@link SecurityRule#getProtocol()} is other than {@link ProtocolTcp}, + * {@link ProtocolUdp}, {@link ProtocolIcmp}, {@link ProtocolIcmpV6} */ - public static Long getProtocol(NeutronSecurityRule secRule) { - String protocol = secRule.getSecurityRuleProtocol(); - if (Strings.isNullOrEmpty(protocol)) { + public static Long getProtocol(SecurityRule secRule) { + Class protocol = secRule.getProtocol(); + if (protocol == null) { return null; } - if (NeutronUtils.TCP.equals(protocol)) { + if (protocol.isAssignableFrom(ProtocolTcp.class)) { return IpProtoClassifierDefinition.TCP_VALUE; } - if (NeutronUtils.UDP.equals(protocol)) { + if (protocol.isAssignableFrom(ProtocolUdp.class)) { return IpProtoClassifierDefinition.UDP_VALUE; } - if (NeutronUtils.ICMP.equals(protocol)) { + if (protocol.isAssignableFrom(ProtocolIcmp.class)) { return IpProtoClassifierDefinition.ICMP_VALUE; } - if (NeutronUtils.ICMPv6.equals(protocol)) { + if (protocol.isAssignableFrom(ProtocolIcmpV6.class)) { return IpProtoClassifierDefinition.ICMPv6_VALUE; } - Long protocolNum; - try { - protocolNum = Long.valueOf(protocol); - } catch (NumberFormatException e) { - throw new IllegalArgumentException("Neutron Security Rule Protocol value " + protocol - + " is not supported."); - } - return protocolNum; + throw new IllegalArgumentException("Neutron Security Rule Protocol value " + protocol + " is not supported."); } } diff --git a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SecRuleNameDecoder.java b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SecRuleNameDecoder.java index 49f78bc30..cfaa2de99 100644 --- a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SecRuleNameDecoder.java +++ b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SecRuleNameDecoder.java @@ -12,14 +12,16 @@ import org.opendaylight.groupbasedpolicy.api.sf.EtherTypeClassifierDefinition; import org.opendaylight.groupbasedpolicy.api.sf.IpProtoClassifierDefinition; import org.opendaylight.groupbasedpolicy.api.sf.L4ClassifierDefinition; import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils; -import org.opendaylight.neutron.spi.NeutronSecurityRule; +import org.opendaylight.groupbasedpolicy.neutron.mapper.util.Utils; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ClassifierName; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ClauseName; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.RuleName; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.SubjectName; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.HasDirection.Direction; - -import com.google.common.base.Strings; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeBase; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolBase; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRule; public class SecRuleNameDecoder { @@ -30,19 +32,19 @@ public class SecRuleNameDecoder { throw new UnsupportedOperationException("Cannot create an instance."); } - public static SubjectName getSubjectName(NeutronSecurityRule secRule) { + public static SubjectName getSubjectName(SecurityRule secRule) { RuleName ruleName = SecRuleNameDecoder.getRuleName(secRule); return new SubjectName(ruleName); } - public static RuleName getRuleName(NeutronSecurityRule secRule) { + public static RuleName getRuleName(SecurityRule secRule) { ClassifierName classifierRefName = SecRuleNameDecoder.getClassifierRefName(secRule); String ruleName = new StringBuilder(MappingUtils.ACTION_ALLOW.getName().getValue()) .append(MappingUtils.NAME_DOUBLE_DELIMETER).append(classifierRefName.getValue()).toString(); return new RuleName(ruleName); } - public static ClassifierName getClassifierRefName(NeutronSecurityRule secRule) { + public static ClassifierName getClassifierRefName(SecurityRule secRule) { Direction direction = SecRuleEntityDecoder.getDirection(secRule); ClassifierName classifierInstanceName = getClassifierInstanceName(secRule); String crName = new StringBuilder().append(direction.name()) @@ -52,10 +54,10 @@ public class SecRuleNameDecoder { return new ClassifierName(crName); } - public static ClassifierName getClassifierInstanceName(NeutronSecurityRule secRule) { + public static ClassifierName getClassifierInstanceName(SecurityRule secRule) { StringBuilder keyBuilder = new StringBuilder(); - Integer portMin = secRule.getSecurityRulePortMin(); - Integer portMax = secRule.getSecurityRulePortMax(); + Integer portMin = secRule.getPortRangeMin(); + Integer portMax = secRule.getPortRangeMax(); if (portMin != null && portMax != null) { keyBuilder.append(L4ClassifierDefinition.DEFINITION.getName().getValue()); if (portMin.equals(portMax)) { @@ -74,35 +76,35 @@ public class SecRuleNameDecoder { .append(portMax.longValue()); } } - String protocol = secRule.getSecurityRuleProtocol(); - if (!Strings.isNullOrEmpty(protocol)) { + Class protocol = secRule.getProtocol(); + if (protocol != null) { if (keyBuilder.length() > 0) { keyBuilder.append(MappingUtils.NAME_DOUBLE_DELIMETER); } keyBuilder.append(IpProtoClassifierDefinition.DEFINITION.getName().getValue()) .append(MappingUtils.NAME_VALUE_DELIMETER) - .append(protocol); + .append(protocol.getSimpleName()); } - String ethertype = secRule.getSecurityRuleEthertype(); - if (!Strings.isNullOrEmpty(ethertype)) { + Class ethertype = secRule.getEthertype(); + if (ethertype != null) { if (keyBuilder.length() > 0) { keyBuilder.append(MappingUtils.NAME_DOUBLE_DELIMETER); } keyBuilder.append(EtherTypeClassifierDefinition.DEFINITION.getName().getValue()) .append(MappingUtils.NAME_VALUE_DELIMETER) - .append(ethertype); + .append(ethertype.getSimpleName()); } return new ClassifierName(keyBuilder.toString()); } - public static ClauseName getClauseName(NeutronSecurityRule secRule) { - String remoteIpPrefix = secRule.getSecurityRuleRemoteIpPrefix(); + public static ClauseName getClauseName(SecurityRule secRule) { + IpPrefix remoteIpPrefix = secRule.getRemoteIpPrefix(); SubjectName subjectName = getSubjectName(secRule); - if (Strings.isNullOrEmpty(remoteIpPrefix)) { + if (remoteIpPrefix == null) { return new ClauseName(subjectName); } - return new ClauseName( - subjectName.getValue() + MappingUtils.NAME_DOUBLE_DELIMETER + remoteIpPrefix.replace('/', '_')); + return new ClauseName(subjectName.getValue() + MappingUtils.NAME_DOUBLE_DELIMETER + + Utils.getStringIpPrefix(remoteIpPrefix).replace('/', '_')); } } diff --git a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SingleClassifierRule.java b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SingleClassifierRule.java index 703cec440..d17f1c9f5 100644 --- a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SingleClassifierRule.java +++ b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SingleClassifierRule.java @@ -15,7 +15,6 @@ import javax.annotation.concurrent.Immutable; import org.opendaylight.groupbasedpolicy.api.sf.EtherTypeClassifierDefinition; import org.opendaylight.groupbasedpolicy.api.sf.IpProtoClassifierDefinition; import org.opendaylight.groupbasedpolicy.api.sf.L4ClassifierDefinition; -import org.opendaylight.neutron.spi.NeutronSecurityRule; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.change.action.of.security.group.rules.input.action.ActionChoice; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.change.action.of.security.group.rules.input.action.action.choice.SfcActionCase; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.has.classifier.refs.ClassifierRef; @@ -23,6 +22,7 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.contract.subject.Rule; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.contract.subject.RuleBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.subject.feature.instances.ClassifierInstance; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRule; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; @@ -34,7 +34,7 @@ public class SingleClassifierRule { private final ClassifierRef classifierRef; private final Rule rule; - public SingleClassifierRule(NeutronSecurityRule secRule, int ruleBaseOrder, ActionChoice action) { + public SingleClassifierRule(SecurityRule secRule, int ruleBaseOrder, ActionChoice action) { classifierInstance = SecRuleEntityDecoder.getClassifierInstance(secRule); classifierRef = SecRuleEntityDecoder.getClassifierRef(secRule); rule = createRule( @@ -55,7 +55,7 @@ public class SingleClassifierRule { return rule; } - private Rule createRule(int order, NeutronSecurityRule secRule, ActionChoice action) { + private Rule createRule(int order, SecurityRule secRule, ActionChoice action) { return new RuleBuilder().setName(SecRuleNameDecoder.getRuleName(secRule)) .setOrder(order) .setActionRef(ImmutableList.of(SecRuleEntityDecoder.createActionRefFromActionChoice(action))) diff --git a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SingleRuleContract.java b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SingleRuleContract.java index 61082c0cf..54103be75 100644 --- a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SingleRuleContract.java +++ b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SingleRuleContract.java @@ -13,7 +13,6 @@ import static com.google.common.base.Preconditions.checkNotNull; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; -import org.opendaylight.neutron.spi.NeutronSecurityRule; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.Description; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.change.action.of.security.group.rules.input.action.ActionChoice; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.Contract; @@ -22,6 +21,7 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.contract.Subject; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.contract.SubjectBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.contract.subject.Rule; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRule; import com.google.common.collect.ImmutableList; @@ -34,11 +34,11 @@ public class SingleRuleContract { private final Clause clause; private final Contract contract; - public SingleRuleContract(NeutronSecurityRule secRule, int subjectAndRuleOrder, @Nullable Description contractDescription, ActionChoice action) { + public SingleRuleContract(SecurityRule secRule, int subjectAndRuleOrder, @Nullable Description contractDescription, ActionChoice action) { this(secRule, new SingleClassifierRule(secRule, subjectAndRuleOrder, action), contractDescription); } - public SingleRuleContract(NeutronSecurityRule secRule, SingleClassifierRule singleClassifierRule, + public SingleRuleContract(SecurityRule secRule, SingleClassifierRule singleClassifierRule, @Nullable Description contractDescription) { checkNotNull(secRule); this.singleClassifierRule = checkNotNull(singleClassifierRule); diff --git a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/MappingUtils.java b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/MappingUtils.java index fb8df5151..6772d0d54 100644 --- a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/MappingUtils.java +++ b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/MappingUtils.java @@ -8,40 +8,27 @@ package org.opendaylight.groupbasedpolicy.neutron.mapper.util; -import java.util.List; - -import org.opendaylight.controller.md.sal.binding.api.ReadTransaction; -import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; import org.opendaylight.groupbasedpolicy.api.sf.AllowActionDefinition; -import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.NeutronPortAware; -import org.opendaylight.groupbasedpolicy.util.DataStoreHelper; -import org.opendaylight.groupbasedpolicy.util.IidFactory; -import org.opendaylight.neutron.spi.Neutron_IPs; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Prefix; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ActionName; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.EndpointGroupId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2BridgeDomainId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2FloodDomainId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L3ContextId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.change.action.of.security.group.rules.input.action.ActionChoice; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.change.action.of.security.group.rules.input.action.action.choice.AllowActionCaseBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.change.action.of.security.group.rules.input.action.action.choice.SfcActionCaseBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.change.action.of.security.group.rules.input.action.action.choice.allow.action._case.AllowBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.has.action.refs.ActionRef; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.has.action.refs.ActionRefBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2BridgeDomain; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2FloodDomain; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L3Context; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.subject.feature.instances.ActionInstance; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.subject.feature.instances.ActionInstanceBuilder; -import com.google.common.base.Optional; - public final class MappingUtils { public static final String NEUTRON_ROUTER = "neutron_router-"; public static final String NEUTRON_EXTERNAL = "neutron_external_network-"; public static final String NEUTRON_GROUP = "neutron_group-"; + public static final IpPrefix DEFAULT_ROUTE = new IpPrefix(new Ipv4Prefix("0.0.0.0/0")); public static final ActionInstance ACTION_ALLOW = new ActionInstanceBuilder().setName( new ActionName("Allow")) .setActionDefinitionId(AllowActionDefinition.DEFINITION.getId()) @@ -50,7 +37,8 @@ public final class MappingUtils { new AllowBuilder().build()).build(); public static final ActionRef ACTION_REF_ALLOW = new ActionRefBuilder().setName(ACTION_ALLOW.getName()).setOrder(0).build(); - public static final EndpointGroupId EPG_EXTERNAL_ID = new EndpointGroupId("eeeaa3a2-e9ba-44e0-a462-bea923d30e38"); + public static final Uuid EIG_UUID = new Uuid("eeeaa3a2-e9ba-44e0-a462-bea923d30e38"); + public static final EndpointGroupId EPG_EXTERNAL_ID = new EndpointGroupId(EIG_UUID.getValue()); public static final String NAME_VALUE_DELIMETER = "-"; public static final String NAME_DELIMETER = "_"; @@ -68,68 +56,4 @@ public final class MappingUtils { return new SfcActionCaseBuilder().setSfcChainName(chainName).build(); } - public static ForwardingCtx createForwardingContext(TenantId tenantId, L2FloodDomainId l2FdId, ReadTransaction rTx) { - Optional potentialL2Fd = DataStoreHelper.readFromDs(LogicalDatastoreType.CONFIGURATION, - IidFactory.l2FloodDomainIid(tenantId, l2FdId), rTx); - if (!potentialL2Fd.isPresent()) { - return new ForwardingCtx(null, null, null); - } - L2BridgeDomainId l2BdId = potentialL2Fd.get().getParent(); - if (l2BdId == null) { - return new ForwardingCtx(potentialL2Fd.get(), null, null); - } - Optional potentialL2Bd = DataStoreHelper.readFromDs(LogicalDatastoreType.CONFIGURATION, - IidFactory.l2BridgeDomainIid(tenantId, l2BdId), rTx); - if (!potentialL2Bd.isPresent()) { - return new ForwardingCtx(potentialL2Fd.get(), null, null); - } - L3ContextId l3ContextId = potentialL2Bd.get().getParent(); - if (l3ContextId == null) { - return new ForwardingCtx(potentialL2Fd.get(), potentialL2Bd.get(), null); - } - Optional potentialL3Context = DataStoreHelper.readFromDs(LogicalDatastoreType.CONFIGURATION, - IidFactory.l3ContextIid(tenantId, l3ContextId), rTx); - if (!potentialL3Context.isPresent()) { - return new ForwardingCtx(potentialL2Fd.get(), potentialL2Bd.get(), null); - } - return new ForwardingCtx(potentialL2Fd.get(), potentialL2Bd.get(), potentialL3Context.get()); - } - - public static final class ForwardingCtx { - - private final L2FloodDomain l2FloodDomain; - private final L2BridgeDomain l2BridgeDomain; - private final L3Context l3Context; - - private ForwardingCtx(L2FloodDomain l2Fd, L2BridgeDomain l2Bd, L3Context l3Context) { - this.l2FloodDomain = l2Fd; - this.l2BridgeDomain = l2Bd; - this.l3Context = l3Context; - } - - public L2FloodDomain getL2FloodDomain() { - return l2FloodDomain; - } - - public L2BridgeDomain getL2BridgeDomain() { - return l2BridgeDomain; - } - - public L3Context getL3Context() { - return l3Context; - } - - } - - public static Neutron_IPs getFirstIp(List fixedIPs) { - if (fixedIPs == null || fixedIPs.isEmpty()) { - return null; - } - Neutron_IPs neutron_Ip = fixedIPs.get(0); - if (fixedIPs.size() > 1) { - NeutronPortAware.LOG.warn("Neutron mapper does not support multiple IPs on the same port. Only first IP is selected {}", - neutron_Ip); - } - return neutron_Ip; - } } diff --git a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/NetworkUtils.java b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/NetworkUtils.java new file mode 100644 index 000000000..bbf671ac7 --- /dev/null +++ b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/NetworkUtils.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.groupbasedpolicy.neutron.mapper.util; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.ext.rev150712.NetworkL3Extension; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.Networks; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.networks.Network; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.provider.ext.rev150712.NetworkProviderExtension; + +import com.google.common.base.Optional; +import com.google.common.base.Strings; + +public class NetworkUtils { + + public static List findRouterExternalNetworks(@Nullable Networks networks) { + if (networks == null || networks.getNetwork() == null) { + return Collections.emptyList(); + } + List result = new ArrayList<>(); + for (Network network : networks.getNetwork()) { + if (isRouterExternal(network)) { + result.add(network); + } + } + return result; + } + + public static Optional findNetwork(Uuid uuid, @Nullable Networks networks) { + if (networks == null || networks.getNetwork() == null) { + return Optional.absent(); + } + for (Network network : networks.getNetwork()) { + if (network.getUuid().equals(uuid)) { + return Optional.of(network); + } + } + return Optional.absent(); + } + + public static boolean isProviderPhysicalNetwork(Network network) { + return (!isRouterExternal(network) && !getPhysicalNetwork(network).isEmpty()); + } + + public static boolean isRouterExternal(Network network) { + NetworkL3Extension l3Extension = network.getAugmentation(NetworkL3Extension.class); + if (l3Extension == null) { + return false; + } + Boolean external = l3Extension.isExternal(); + if (external == null) { + return false; + } + return true; + } + + public static @Nonnull String getPhysicalNetwork(Network network) { + NetworkProviderExtension providerExtension = network.getAugmentation(NetworkProviderExtension.class); + if (providerExtension == null) { + return ""; + } + return Strings.nullToEmpty(providerExtension.getPhysicalNetwork()); + } + + public static @Nonnull String getSegmentationId(Network network) { + NetworkProviderExtension providerExtension = network.getAugmentation(NetworkProviderExtension.class); + if (providerExtension == null) { + return ""; + } + return Strings.nullToEmpty(providerExtension.getSegmentationId()); + } +} diff --git a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/NeutronMapperIidFactory.java b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/NeutronMapperIidFactory.java deleted file mode 100644 index 332b1bc9f..000000000 --- a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/NeutronMapperIidFactory.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.groupbasedpolicy.neutron.mapper.util; - -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.UniqueId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.mapper.rev150223.Mappings; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.mapper.rev150223.mappings.NetworkMappings; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.mapper.rev150223.mappings.network.mappings.NetworkMapping; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.mapper.rev150223.mappings.network.mappings.NetworkMappingKey; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; - -public class NeutronMapperIidFactory { - - public static InstanceIdentifier networkMappingIid(UniqueId networkId) { - return InstanceIdentifier.builder(Mappings.class) - .child(NetworkMappings.class) - .child(NetworkMapping.class, new NetworkMappingKey(networkId)) - .build(); - } - -} diff --git a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/NeutronUtils.java b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/NeutronUtils.java deleted file mode 100644 index b1c960403..000000000 --- a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/NeutronUtils.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.groupbasedpolicy.neutron.mapper.util; - -public final class NeutronUtils { - - public static final String EGRESS = "egress"; - public static final String INGRESS = "ingress"; - public static final String IPv6 = "IPv6"; - public static final String IPv4 = "IPv4"; - public static final String NULL = "null"; - public static final String UDP = "udp"; - public static final String TCP = "tcp"; - public static final String ICMP = "icmp"; - public static final String ICMPv6 = "icmpv6"; - - private NeutronUtils() { - throw new UnsupportedOperationException("Cannot create an instance."); - } -} diff --git a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/PortUtils.java b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/PortUtils.java new file mode 100644 index 000000000..3ef29b5c1 --- /dev/null +++ b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/PortUtils.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.groupbasedpolicy.neutron.mapper.util; + +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.annotation.Nullable; + +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.FixedIps; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.Ports; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port; + +import com.google.common.base.Optional; + +public class PortUtils { + + private static final String DEVICE_OWNER_DHCP = "network:dhcp"; + private static final String DEVICE_OWNER_ROUTER_IFACE = "network:router_interface"; + private static final String DEVICE_OWNER_ROUTER_GATEWAY = "network:router_gateway"; + private static final String DEVICE_OWNER_FLOATING_IP = "network:floatingip"; + + public static Optional findPort(Uuid uuid, @Nullable Ports ports) { + if (ports == null || ports.getPort() == null) { + return Optional.absent(); + } + for (Port port : ports.getPort()) { + if (port.getUuid().equals(uuid)) { + return Optional.of(port); + } + } + return Optional.absent(); + } + + public static Set findRouterInterfacePorts(@Nullable Ports ports) { + if (ports == null || ports.getPort() == null) { + return Collections.emptySet(); + } + Set routerInterfacePorts = new HashSet<>(); + for (Port port : ports.getPort()) { + if (isRouterInterfacePort(port)) { + routerInterfacePorts.add(port); + } + } + return routerInterfacePorts; + } + + public static Set findPortsBySubnet(Uuid subnetUuid, @Nullable Ports ports) { + if (ports == null || ports.getPort() == null) { + return Collections.emptySet(); + } + Set portsWithSubnet = new HashSet<>(); + for (Port port : ports.getPort()) { + List fixedIps = port.getFixedIps(); + if (fixedIps != null && !fixedIps.isEmpty()) { + for (FixedIps ipWithSubnet : fixedIps) { + if (ipWithSubnet.getSubnetId().equals(subnetUuid)) { + portsWithSubnet.add(port); + } + } + } + } + return portsWithSubnet; + } + + public static Optional resolveFirstFixedIps(Port port) { + List fixedIps = port.getFixedIps(); + if (fixedIps != null && !fixedIps.isEmpty()) { + return Optional.of(fixedIps.get(0)); + } + return Optional.absent(); + } + + public static boolean isNormalPort(Port port) { + if (isDhcpPort(port) || isRouterInterfacePort(port) || isRouterGatewayPort(port) || isFloatingIpPort(port)) { + return false; + } + return true; + } + + public static boolean isDhcpPort(Port port) { + return DEVICE_OWNER_DHCP.equals(port.getDeviceOwner()); + } + + public static boolean isRouterInterfacePort(Port port) { + return DEVICE_OWNER_ROUTER_IFACE.equals(port.getDeviceOwner()); + } + + public static boolean isRouterGatewayPort(Port port) { + return DEVICE_OWNER_ROUTER_GATEWAY.equals(port.getDeviceOwner()); + } + + public static boolean isFloatingIpPort(Port port) { + return DEVICE_OWNER_FLOATING_IP.equals(port.getDeviceOwner()); + } +} diff --git a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/RouterUtils.java b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/RouterUtils.java new file mode 100644 index 000000000..cb6fe7c06 --- /dev/null +++ b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/RouterUtils.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.groupbasedpolicy.neutron.mapper.util; + +import javax.annotation.Nullable; + +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.Routers; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.routers.Router; + +import com.google.common.base.Optional; + +public class RouterUtils { + + public static Optional findRouter(Uuid uuid, @Nullable Routers routers) { + if (routers == null || routers.getRouter() == null) { + return Optional.absent(); + } + for (Router router : routers.getRouter()) { + if (router.getUuid().equals(uuid)) { + return Optional.of(router); + } + } + return Optional.absent(); + } +} diff --git a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/SecurityGroupUtils.java b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/SecurityGroupUtils.java new file mode 100644 index 000000000..0d28041cd --- /dev/null +++ b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/SecurityGroupUtils.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.groupbasedpolicy.neutron.mapper.util; + +import javax.annotation.Nullable; + +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.SecurityGroups; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.security.groups.SecurityGroup; + +import com.google.common.base.Optional; +import com.google.common.base.Preconditions; +import com.google.common.base.Strings; + +public class SecurityGroupUtils { + + public static Optional findSecurityGroup(Uuid secGrpUuid, @Nullable SecurityGroups securityGroups) { + Preconditions.checkNotNull(secGrpUuid); + if (securityGroups == null || securityGroups.getSecurityGroup() == null) { + return Optional.absent(); + } + for (SecurityGroup secGroup : securityGroups.getSecurityGroup()) { + if (secGrpUuid.equals(secGroup.getUuid())) { + return Optional.of(secGroup); + } + } + return Optional.absent(); + } + + public static String getNameOrUuid(SecurityGroup secGroup) { + if (!Strings.isNullOrEmpty(secGroup.getName())) { + return secGroup.getName(); + } + return secGroup.getUuid().getValue(); + } + +} diff --git a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/SecurityRuleUtils.java b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/SecurityRuleUtils.java new file mode 100644 index 000000000..c96de98ee --- /dev/null +++ b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/SecurityRuleUtils.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.groupbasedpolicy.neutron.mapper.util; + +import java.util.Collections; +import java.util.List; +import java.util.Set; + +import javax.annotation.Nullable; + +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.SecurityRules; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRule; + +import com.google.common.base.Function; +import com.google.common.base.Objects; +import com.google.common.base.Optional; +import com.google.common.base.Preconditions; +import com.google.common.base.Predicate; +import com.google.common.collect.FluentIterable; + +public class SecurityRuleUtils { + + public static Optional findSecurityRule(Uuid uuid, @Nullable SecurityRules securityRules) { + if (securityRules == null || securityRules.getSecurityRule() == null) { + return Optional.absent(); + } + for (SecurityRule secRule : securityRules.getSecurityRule()) { + if (secRule.getId().equals(uuid)) { + return Optional.of(secRule); + } + } + return Optional.absent(); + } + + public static Set findSecurityRulesBySecGroupAndRemoteSecGroup(Uuid secGroup, + @Nullable Uuid remoteSecGroup, Neutron neutron) { + Preconditions.checkNotNull(secGroup); + return FluentIterable.from(findAllSecurityRules(neutron)).filter(new Predicate() { + + @Override + public boolean apply(SecurityRule secRule) { + return (secRule.getSecurityGroupId().equals(secGroup) + && Objects.equal(secRule.getRemoteGroupId(), remoteSecGroup)); + } + }).toSet(); + } + + public static Set findSecurityGroupsHavingSecurityRules(Neutron neutron) { + return FluentIterable.from(findAllSecurityRules(neutron)).transform(new Function() { + + @Override + public Uuid apply(SecurityRule secRule) { + return secRule.getSecurityGroupId(); + } + }).toSet(); + } + + public static List findAllSecurityRules(Neutron neutron) { + Preconditions.checkNotNull(neutron); + SecurityRules securityRules = neutron.getSecurityRules(); + if (securityRules == null || securityRules.getSecurityRule() == null) { + return Collections.emptyList(); + } + return securityRules.getSecurityRule(); + } + +} diff --git a/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/SubnetUtils.java b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/SubnetUtils.java new file mode 100644 index 000000000..e368c9d70 --- /dev/null +++ b/neutron-mapper/src/main/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/SubnetUtils.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.groupbasedpolicy.neutron.mapper.util; + +import javax.annotation.Nullable; + +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.Subnets; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet; + +import com.google.common.base.Optional; + +public class SubnetUtils { + + public static Optional findSubnet(Uuid uuid, @Nullable Subnets subnets) { + if (subnets == null || subnets.getSubnet() == null) { + return Optional.absent(); + } + for (Subnet subnet : subnets.getSubnet()) { + if (subnet.getUuid().equals(uuid)) { + return Optional.of(subnet); + } + } + return Optional.absent(); + } +} diff --git a/neutron-mapper/src/main/yang/mapper.yang b/neutron-mapper/src/main/yang/mapper.yang deleted file mode 100644 index ac833261e..000000000 --- a/neutron-mapper/src/main/yang/mapper.yang +++ /dev/null @@ -1,52 +0,0 @@ -module neutron-mapper { - yang-version 1; - - namespace "urn:opendaylight:groupbasedpolicy:neutron-mapper"; - prefix "gbp-neutron-mapper"; - - import gbp-common {prefix gbp-common;} - import endpoint {prefix gbp-endpoint;} - import ietf-inet-types { - prefix inet; - revision-date 2010-09-24; - } - - description - "This module defines the mapping model between Neutron IDs and GBP IDs. - These mappings are used just internaly and are NOT EXPORTED."; - - revision "2015-02-23" { - description - "Initial revision."; - } - - grouping tenant-id-fields { - leaf tenant-id { - description "A unique ID for the tenant"; - mandatory true; - type gbp-common:tenant-id; - } - } - - container mappings { - config false; - container network-mappings { - list network-mapping { - key network-id; - leaf network-id { - description "A unique ID for the neutron network == gbp l2-flood-domain"; - type gbp-common:unique-id; - } - leaf l2-bridge-domain-id { - description "A unique ID of l2-bridge-domain generated for neutron network"; - type gbp-common:l2-bridge-domain-id; - } - leaf l3-context-id { - description "A unique ID of l3-context generated for neutron network"; - type gbp-common:l3-context-id; - } - } - } - } - -} \ No newline at end of file diff --git a/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronSecurityGroupAwareDataStoreTest.java b/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronSecurityGroupAwareDataStoreTest.java new file mode 100644 index 000000000..64f083958 --- /dev/null +++ b/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/NeutronSecurityGroupAwareDataStoreTest.java @@ -0,0 +1,85 @@ +package org.opendaylight.groupbasedpolicy.neutron.mapper.mapping; + +import static org.junit.Assert.fail; + +import org.junit.Test; +import org.opendaylight.controller.md.sal.binding.api.DataBroker; +import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.NeutronSecurityGroupAware; +import org.opendaylight.groupbasedpolicy.neutron.mapper.test.GbpDataBrokerTest; +import org.opendaylight.groupbasedpolicy.neutron.mapper.test.NeutronEntityFactory; +import org.opendaylight.groupbasedpolicy.neutron.mapper.test.PolicyAssert; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.EndpointGroup.IntraGroupPolicy; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.security.groups.SecurityGroup; + +public class NeutronSecurityGroupAwareDataStoreTest extends GbpDataBrokerTest { + + @Test + public void testAddAndDeleteNeutronSecurityGroup_noSecurityRules() throws Exception { + DataBroker dataBroker = getDataBroker(); + NeutronSecurityGroupAware groupAware = new NeutronSecurityGroupAware(dataBroker); + + final String tenantId = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"; + final String secGroupId1 = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"; + final String secGroupId2 = "cccccccc-cccc-cccc-cccc-cccccccccccc"; + + SecurityGroup secGroup1 = NeutronEntityFactory.securityGroup(secGroupId1, tenantId); + SecurityGroup secGroup2 = NeutronEntityFactory.securityGroup(secGroupId2, tenantId); + + groupAware.onCreated(secGroup1, null); + + PolicyAssert.assertTenantExists(dataBroker, tenantId); + PolicyAssert.assertContractCount(dataBroker, tenantId, 0); + PolicyAssert.assertEndpointGroupCount(dataBroker, tenantId, 1); + PolicyAssert.assertEndpointGroupExists(dataBroker, tenantId, secGroupId1); + PolicyAssert.assertNoProviderNamedSelectors(dataBroker, tenantId, secGroupId1); + PolicyAssert.assertNoConsumerNamedSelectors(dataBroker, tenantId, secGroupId1); + PolicyAssert.assertIntraGroupPolicy(dataBroker, tenantId, secGroupId1, IntraGroupPolicy.RequireContract); + + groupAware.onDeleted(secGroup1, null, null); + + PolicyAssert.assertTenantExists(dataBroker, tenantId); + PolicyAssert.assertContractCount(dataBroker, tenantId, 0); + PolicyAssert.assertEndpointGroupCount(dataBroker, tenantId, 0); + + groupAware.onCreated(secGroup1, null); + groupAware.onCreated(secGroup2, null); + + PolicyAssert.assertTenantExists(dataBroker, tenantId); + PolicyAssert.assertContractCount(dataBroker, tenantId, 0); + PolicyAssert.assertEndpointGroupCount(dataBroker, tenantId, 2); + PolicyAssert.assertEndpointGroupExists(dataBroker, tenantId, secGroupId1); + PolicyAssert.assertNoProviderNamedSelectors(dataBroker, tenantId, secGroupId1); + PolicyAssert.assertNoConsumerNamedSelectors(dataBroker, tenantId, secGroupId1); + PolicyAssert.assertIntraGroupPolicy(dataBroker, tenantId, secGroupId1, IntraGroupPolicy.RequireContract); + PolicyAssert.assertEndpointGroupExists(dataBroker, tenantId, secGroupId2); + PolicyAssert.assertNoProviderNamedSelectors(dataBroker, tenantId, secGroupId2); + PolicyAssert.assertNoConsumerNamedSelectors(dataBroker, tenantId, secGroupId2); + PolicyAssert.assertIntraGroupPolicy(dataBroker, tenantId, secGroupId2, IntraGroupPolicy.RequireContract); + + groupAware.onDeleted(secGroup2, null, null); + + PolicyAssert.assertTenantExists(dataBroker, tenantId); + PolicyAssert.assertContractCount(dataBroker, tenantId, 0); + PolicyAssert.assertEndpointGroupCount(dataBroker, tenantId, 1); + PolicyAssert.assertEndpointGroupExists(dataBroker, tenantId, secGroupId1); + PolicyAssert.assertNoProviderNamedSelectors(dataBroker, tenantId, secGroupId1); + PolicyAssert.assertNoConsumerNamedSelectors(dataBroker, tenantId, secGroupId1); + + groupAware.onDeleted(secGroup1, null, null); + + PolicyAssert.assertTenantExists(dataBroker, tenantId); + PolicyAssert.assertContractCount(dataBroker, tenantId, 0); + PolicyAssert.assertEndpointGroupCount(dataBroker, tenantId, 0); + } + + @Test + public void testConstructor_invalidArgument() throws Exception { + try { + new NeutronSecurityGroupAware(null); + fail(NullPointerException.class.getName() + " expected"); + } catch (NullPointerException e) { + // do nothing + } + } + +} diff --git a/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/group/NeutronSecurityGroupAwareDataStoreTest.java b/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/group/NeutronSecurityGroupAwareDataStoreTest.java deleted file mode 100644 index 98d231b32..000000000 --- a/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/group/NeutronSecurityGroupAwareDataStoreTest.java +++ /dev/null @@ -1,216 +0,0 @@ -package org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.group; - -import static org.junit.Assert.fail; - -import org.junit.Test; -import org.opendaylight.controller.md.sal.binding.api.DataBroker; -import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.rule.NeutronSecurityRuleAware; -import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.rule.SecRuleDao; -import org.opendaylight.groupbasedpolicy.neutron.mapper.test.ConfigDataStoreReader; -import org.opendaylight.groupbasedpolicy.neutron.mapper.test.GbpDataBrokerTest; -import org.opendaylight.groupbasedpolicy.neutron.mapper.test.NeutronEntityFactory; -import org.opendaylight.groupbasedpolicy.neutron.mapper.test.PolicyAssert; -import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils; -import org.opendaylight.groupbasedpolicy.neutron.mapper.util.NeutronUtils; -import org.opendaylight.neutron.spi.NeutronSecurityGroup; -import org.opendaylight.neutron.spi.NeutronSecurityRule; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ContractId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.Contract; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.EndpointGroup; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.EndpointGroup.IntraGroupPolicy; - -import com.google.common.base.Optional; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; - -public class NeutronSecurityGroupAwareDataStoreTest extends GbpDataBrokerTest { - - @Test - public void testAddAndDeleteNeutronSecurityGroup_noSecurityRules() throws Exception { - DataBroker dataBroker = getDataBroker(); - SecRuleDao secRuleDao = new SecRuleDao(); - SecGroupDao secGroupDao = new SecGroupDao(); - NeutronSecurityRuleAware ruleAware = new NeutronSecurityRuleAware(dataBroker, secRuleDao, secGroupDao); - NeutronSecurityGroupAware groupAware = new NeutronSecurityGroupAware(dataBroker, ruleAware, secGroupDao); - - final String tenantId = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"; - final String secGroupId1 = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"; - final String secGroupId2 = "cccccccc-cccc-cccc-cccc-cccccccccccc"; - - NeutronSecurityGroup secGroup1 = NeutronEntityFactory.securityGroup(secGroupId1, tenantId); - NeutronSecurityGroup secGroup2 = NeutronEntityFactory.securityGroup(secGroupId2, tenantId); - - groupAware.created(secGroup1); - - PolicyAssert.assertTenantExists(dataBroker, tenantId); - PolicyAssert.assertContractCount(dataBroker, tenantId, 0); - PolicyAssert.assertEndpointGroupCount(dataBroker, tenantId, 1); - PolicyAssert.assertEndpointGroupExists(dataBroker, tenantId, secGroupId1); - PolicyAssert.assertNoProviderNamedSelectors(dataBroker, tenantId, secGroupId1); - PolicyAssert.assertNoConsumerNamedSelectors(dataBroker, tenantId, secGroupId1); - PolicyAssert.assertIntraGroupPolicy(dataBroker, tenantId, secGroupId1, IntraGroupPolicy.RequireContract); - - groupAware.deleted(secGroup1); - - PolicyAssert.assertTenantExists(dataBroker, tenantId); - PolicyAssert.assertContractCount(dataBroker, tenantId, 0); - PolicyAssert.assertEndpointGroupCount(dataBroker, tenantId, 0); - - groupAware.created(secGroup1); - groupAware.created(secGroup2); - - PolicyAssert.assertTenantExists(dataBroker, tenantId); - PolicyAssert.assertContractCount(dataBroker, tenantId, 0); - PolicyAssert.assertEndpointGroupCount(dataBroker, tenantId, 2); - PolicyAssert.assertEndpointGroupExists(dataBroker, tenantId, secGroupId1); - PolicyAssert.assertNoProviderNamedSelectors(dataBroker, tenantId, secGroupId1); - PolicyAssert.assertNoConsumerNamedSelectors(dataBroker, tenantId, secGroupId1); - PolicyAssert.assertIntraGroupPolicy(dataBroker, tenantId, secGroupId1, IntraGroupPolicy.RequireContract); - PolicyAssert.assertEndpointGroupExists(dataBroker, tenantId, secGroupId2); - PolicyAssert.assertNoProviderNamedSelectors(dataBroker, tenantId, secGroupId2); - PolicyAssert.assertNoConsumerNamedSelectors(dataBroker, tenantId, secGroupId2); - PolicyAssert.assertIntraGroupPolicy(dataBroker, tenantId, secGroupId2, IntraGroupPolicy.RequireContract); - - groupAware.deleted(secGroup2); - - PolicyAssert.assertTenantExists(dataBroker, tenantId); - PolicyAssert.assertContractCount(dataBroker, tenantId, 0); - PolicyAssert.assertEndpointGroupCount(dataBroker, tenantId, 1); - PolicyAssert.assertEndpointGroupExists(dataBroker, tenantId, secGroupId1); - PolicyAssert.assertNoProviderNamedSelectors(dataBroker, tenantId, secGroupId1); - PolicyAssert.assertNoConsumerNamedSelectors(dataBroker, tenantId, secGroupId1); - - groupAware.deleted(secGroup1); - - PolicyAssert.assertTenantExists(dataBroker, tenantId); - PolicyAssert.assertContractCount(dataBroker, tenantId, 0); - PolicyAssert.assertEndpointGroupCount(dataBroker, tenantId, 0); - } - - @Test - public void testAddAndDeleteNeutronSecurityGroup_withSecurityRules() throws Exception { - DataBroker dataBroker = getDataBroker(); - SecRuleDao secRuleDao = new SecRuleDao(); - SecGroupDao secGroupDao = new SecGroupDao(); - NeutronSecurityRuleAware ruleAware = new NeutronSecurityRuleAware(dataBroker, secRuleDao, secGroupDao); - NeutronSecurityGroupAware groupAware = new NeutronSecurityGroupAware(dataBroker, ruleAware, secGroupDao); - - final String tenantId = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"; - final String secGroupId1 = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"; - final String secGroupId2 = "cccccccc-cccc-cccc-cccc-cccccccccccc"; - final String secRuleId1 = "dddddddd-dddd-dddd-dddd-dddddddddddd"; - final String secRuleId2 = "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee"; - - NeutronSecurityRule secRule1 = NeutronEntityFactory.securityRuleWithEtherType(secRuleId1, tenantId, - NeutronUtils.IPv4, NeutronUtils.EGRESS, secGroupId1, null); - - NeutronSecurityRule secRule2 = NeutronEntityFactory.securityRuleWithEtherType(secRuleId2, tenantId, - NeutronUtils.IPv4, NeutronUtils.INGRESS, secGroupId2, secGroupId1); - - NeutronSecurityGroup secGroup1 = NeutronEntityFactory.securityGroup(secGroupId1, tenantId, - ImmutableList.of(secRule1)); - - NeutronSecurityGroup secGroup2 = NeutronEntityFactory.securityGroup(secGroupId2, tenantId, - ImmutableList.of(secRule2)); - - groupAware.created(secGroup1); - - PolicyAssert.assertTenantExists(dataBroker, tenantId); - PolicyAssert.assertContractExists(dataBroker, tenantId, secRuleId1); - Optional contract = ConfigDataStoreReader.readContract(dataBroker, tenantId, secRuleId1); - PolicyAssert.assertContract(contract.get(), secRule1); - PolicyAssert.assertContractCount(dataBroker, tenantId, 1); - PolicyAssert.assertEndpointGroupExists(dataBroker, tenantId, secGroupId1); - Optional epGroup1 = ConfigDataStoreReader.readEndpointGroup(dataBroker, tenantId, secGroupId1); - PolicyAssert.assertProviderNamedSelectors(epGroup1.get(), ImmutableSet.of(new ContractId(secRuleId1))); - PolicyAssert.assertNoConsumerNamedSelectors(dataBroker, tenantId, secGroupId1); - PolicyAssert.assertIntraGroupPolicy(dataBroker, tenantId, secGroupId1, IntraGroupPolicy.RequireContract); - PolicyAssert.assertEndpointGroupCount(dataBroker, tenantId, 1); - - PolicyAssert.assertClassifierInstanceExists(dataBroker, secRule1); - PolicyAssert.assertActionInstanceExists(dataBroker, tenantId, MappingUtils.ACTION_ALLOW.getName()); - - groupAware.deleted(secGroup1); - - PolicyAssert.assertTenantExists(dataBroker, tenantId); - PolicyAssert.assertContractCount(dataBroker, tenantId, 0); - PolicyAssert.assertEndpointGroupCount(dataBroker, tenantId, 0); - - PolicyAssert.assertClassifierInstanceNotExists(dataBroker, secRule1); - // TODO: Uncomment this when the life cycle of the Allow ActionInstance will be clarified. - // PolicyAssert.assertActionInstanceNotExists(dataBroker, tenantId, MappingUtils.ACTION_ALLOW.getName()); - - groupAware.created(secGroup1); - groupAware.created(secGroup2); - - PolicyAssert.assertTenantExists(dataBroker, tenantId); - PolicyAssert.assertContractExists(dataBroker, tenantId, secRuleId1); - contract = ConfigDataStoreReader.readContract(dataBroker, tenantId, secRuleId1); - PolicyAssert.assertContract(contract.get(), secRule1); - contract = ConfigDataStoreReader.readContract(dataBroker, tenantId, secRuleId2); - PolicyAssert.assertContract(contract.get(), secRule2); - PolicyAssert.assertContractCount(dataBroker, tenantId, 2); - PolicyAssert.assertEndpointGroupExists(dataBroker, tenantId, secGroupId1); - epGroup1 = ConfigDataStoreReader.readEndpointGroup(dataBroker, tenantId, secGroupId1); - PolicyAssert.assertProviderNamedSelectors(epGroup1.get(), ImmutableSet.of(new ContractId(secRuleId1))); - PolicyAssert.assertConsumerNamedSelectors(epGroup1.get(), ImmutableSet.of(new ContractId(secRuleId2))); - PolicyAssert.assertIntraGroupPolicy(dataBroker, tenantId, secGroupId1, IntraGroupPolicy.RequireContract); - PolicyAssert.assertEndpointGroupExists(dataBroker, tenantId, secGroupId2); - Optional epGroup2 = ConfigDataStoreReader.readEndpointGroup(dataBroker, tenantId, secGroupId2); - PolicyAssert.assertProviderNamedSelectors(epGroup2.get(), ImmutableSet.of(new ContractId(secRuleId2))); - PolicyAssert.assertConsumerNamedSelectors(epGroup2.get(), ImmutableSet.of(new ContractId(secRuleId1))); - PolicyAssert.assertIntraGroupPolicy(dataBroker, tenantId, secGroupId2, IntraGroupPolicy.RequireContract); - PolicyAssert.assertEndpointGroupCount(dataBroker, tenantId, 2); - PolicyAssert.assertClassifierInstanceExists(dataBroker, secRule1); - PolicyAssert.assertActionInstanceExists(dataBroker, tenantId, MappingUtils.ACTION_ALLOW.getName()); - - groupAware.deleted(secGroup2); - - PolicyAssert.assertTenantExists(dataBroker, tenantId); - PolicyAssert.assertContractExists(dataBroker, tenantId, secRuleId1); - contract = ConfigDataStoreReader.readContract(dataBroker, tenantId, secRuleId1); - PolicyAssert.assertContract(contract.get(), secRule1); - PolicyAssert.assertContractCount(dataBroker, tenantId, 1); - PolicyAssert.assertEndpointGroupExists(dataBroker, tenantId, secGroupId1); - epGroup1 = ConfigDataStoreReader.readEndpointGroup(dataBroker, tenantId, secGroupId1); - PolicyAssert.assertProviderNamedSelectors(epGroup1.get(), ImmutableSet.of(new ContractId(secRuleId1))); - PolicyAssert.assertNoConsumerNamedSelectors(dataBroker, tenantId, secGroupId1); - PolicyAssert.assertIntraGroupPolicy(dataBroker, tenantId, secGroupId1, IntraGroupPolicy.RequireContract); - PolicyAssert.assertEndpointGroupCount(dataBroker, tenantId, 1); - - PolicyAssert.assertClassifierInstanceExists(dataBroker, secRule1); - PolicyAssert.assertActionInstanceExists(dataBroker, tenantId, MappingUtils.ACTION_ALLOW.getName()); - - groupAware.deleted(secGroup1); - - PolicyAssert.assertTenantExists(dataBroker, tenantId); - PolicyAssert.assertContractCount(dataBroker, tenantId, 0); - PolicyAssert.assertEndpointGroupCount(dataBroker, tenantId, 0); - - PolicyAssert.assertClassifierInstanceNotExists(dataBroker, secRule1); - // TODO: Uncomment this when the life cycle of the Allow ActionInstance will be clarified. - // PolicyAssert.assertActionInstanceNotExists(dataBroker, tenantId, MappingUtils.ACTION_ALLOW.getName()); - } - - @Test - public void testConstructor_invalidArgument() throws Exception { - DataBroker dataBroker = getDataBroker(); - SecRuleDao secRuleDao = new SecRuleDao(); - SecGroupDao secGroupDao = new SecGroupDao(); - NeutronSecurityRuleAware ruleAware = new NeutronSecurityRuleAware(dataBroker, secRuleDao, secGroupDao); - assertExceptionInConstructor(null, ruleAware, secGroupDao); - assertExceptionInConstructor(dataBroker, null, secGroupDao); - assertExceptionInConstructor(dataBroker, ruleAware, null); - assertExceptionInConstructor(null, null, null); - } - - private void assertExceptionInConstructor(DataBroker dataBroker, NeutronSecurityRuleAware secRuleAware, - SecGroupDao secGroupDao) { - try { - new NeutronSecurityGroupAware(dataBroker, secRuleAware, secGroupDao); - fail(NullPointerException.class.getName() + " expected"); - } catch (NullPointerException ex) { - // do nothing - } - } -} diff --git a/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/group/SecGroupDaoTest.java b/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/group/SecGroupDaoTest.java deleted file mode 100644 index e83f81447..000000000 --- a/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/group/SecGroupDaoTest.java +++ /dev/null @@ -1,135 +0,0 @@ -package org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.group; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.opendaylight.groupbasedpolicy.neutron.mapper.test.NeutronEntityFactory; -import org.opendaylight.neutron.spi.NeutronSecurityGroup; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.EndpointGroupId; - -public class SecGroupDaoTest { - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - private SecGroupDao secGroupDao; - - @Before - public void setUp() throws Exception { - secGroupDao = new SecGroupDao(); - } - - @Test - public void testAddAndRemoveSecGroup() { - NeutronSecurityGroup secGroup1 = NeutronEntityFactory.securityGroup("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", - "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"); - NeutronSecurityGroup secGroup2 = NeutronEntityFactory.securityGroup("cccccccc-cccc-cccc-cccc-cccccccccccc", - "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"); - - // one security group - secGroupDao.addSecGroup(secGroup1); - EndpointGroupId epGroupId1 = new EndpointGroupId(secGroup1.getSecurityGroupUUID()); - NeutronSecurityGroup daoSecGroup = secGroupDao.getSecGroupById(epGroupId1); - assertNotNull(daoSecGroup); - assertEquals(secGroup1, daoSecGroup); - - secGroupDao.removeSecGroup(epGroupId1); - assertNull(secGroupDao.getSecGroupById(epGroupId1)); - - // two security groups - secGroupDao.addSecGroup(secGroup1); - secGroupDao.addSecGroup(secGroup2); - daoSecGroup = secGroupDao.getSecGroupById(epGroupId1); - assertNotNull(daoSecGroup); - assertEquals(secGroup1, daoSecGroup); - EndpointGroupId epGroupId2 = new EndpointGroupId(secGroup2.getSecurityGroupUUID()); - daoSecGroup = secGroupDao.getSecGroupById(epGroupId2); - assertNotNull(daoSecGroup); - assertEquals(secGroup2, daoSecGroup); - - secGroupDao.removeSecGroup(epGroupId2); - daoSecGroup = secGroupDao.getSecGroupById(epGroupId1); - assertNotNull(daoSecGroup); - assertEquals(secGroup1, daoSecGroup); - assertNull(secGroupDao.getSecGroupById(epGroupId2)); - - secGroupDao.removeSecGroup(epGroupId1); - assertNull(secGroupDao.getSecGroupById(epGroupId1)); - assertNull(secGroupDao.getSecGroupById(epGroupId2)); - } - - @Test - public void testAddSecGroup_replacementOfSecGroup() { - NeutronSecurityGroup secGroup = NeutronEntityFactory.securityGroup("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", - "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"); - secGroupDao.addSecGroup(secGroup); - EndpointGroupId epGroupId = new EndpointGroupId(secGroup.getSecurityGroupUUID()); - NeutronSecurityGroup daoSecGroup = secGroupDao.getSecGroupById(epGroupId); - assertNotNull(daoSecGroup); - assertEquals(secGroup, daoSecGroup); - - // the same security group id but different tenant id - secGroup = NeutronEntityFactory.securityGroup("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", - "cccccccc-cccc-cccc-cccc-cccccccccccc"); - secGroupDao.addSecGroup(secGroup); - daoSecGroup = secGroupDao.getSecGroupById(epGroupId); - assertNotNull(daoSecGroup); - assertEquals(secGroup, daoSecGroup); - } - - @Test - public void testAddSecGroup_nullArgument() { - thrown.expect(NullPointerException.class); - secGroupDao.addSecGroup(null); - } - - @Test - public void testGetNameOrIdOfSecGroup_nullArgument() { - thrown.expect(NullPointerException.class); - secGroupDao.getNameOrIdOfSecGroup(null); - } - - @Test - public void testGetNameOrIdOfSecGroup_unknownEpGroupId() { - EndpointGroupId unknownEpGroupId = new EndpointGroupId("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"); - assertEquals("", secGroupDao.getNameOrIdOfSecGroup(unknownEpGroupId)); - } - - @Test - public void testGetNameOrIdOfSecGroup_secGroupNameIsNull() { - NeutronSecurityGroup secGroup = NeutronEntityFactory.securityGroupWithName( - "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", null); - secGroupDao.addSecGroup(secGroup); - EndpointGroupId epGroupId = new EndpointGroupId(secGroup.getSecurityGroupUUID()); - String secGroupNameOrId = secGroupDao.getNameOrIdOfSecGroup(epGroupId); - assertNotNull(secGroupNameOrId); - assertEquals(epGroupId.getValue(), secGroupNameOrId); - } - - @Test - public void testGetNameOrIdOfSecGroup_secGroupNameIsEmpty() { - NeutronSecurityGroup secGroup = NeutronEntityFactory.securityGroupWithName( - "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", ""); - secGroupDao.addSecGroup(secGroup); - EndpointGroupId epGroupId = new EndpointGroupId(secGroup.getSecurityGroupUUID()); - String secGroupNameOrId = secGroupDao.getNameOrIdOfSecGroup(epGroupId); - assertNotNull(secGroupNameOrId); - assertEquals(epGroupId.getValue(), secGroupNameOrId); - } - - @Test - public void testGetNameOrIdOfSecGroup_secGroupNameIsNotEmpty() { - NeutronSecurityGroup secGroup = NeutronEntityFactory.securityGroupWithName( - "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "secGroupName"); - secGroupDao.addSecGroup(secGroup); - EndpointGroupId epGroupId = new EndpointGroupId(secGroup.getSecurityGroupUUID()); - String secGroupNameOrId = secGroupDao.getNameOrIdOfSecGroup(epGroupId); - assertNotNull(secGroupNameOrId); - assertEquals("secGroupName", secGroupNameOrId); - } -} diff --git a/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/NeutronSecurityRuleAwareDataStoreTest.java b/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/NeutronSecurityRuleAwareDataStoreTest.java index 0d1545b2d..d3a4ad13e 100644 --- a/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/NeutronSecurityRuleAwareDataStoreTest.java +++ b/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/NeutronSecurityRuleAwareDataStoreTest.java @@ -3,27 +3,42 @@ package org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.rule; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import java.util.ArrayList; +import java.util.List; + import org.junit.Test; import org.opendaylight.controller.md.sal.binding.api.DataBroker; import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction; import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; -import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.group.SecGroupDao; import org.opendaylight.groupbasedpolicy.neutron.mapper.test.ConfigDataStoreReader; import org.opendaylight.groupbasedpolicy.neutron.mapper.test.GbpDataBrokerTest; import org.opendaylight.groupbasedpolicy.neutron.mapper.test.NeutronEntityFactory; import org.opendaylight.groupbasedpolicy.neutron.mapper.test.PolicyAssert; import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils; -import org.opendaylight.groupbasedpolicy.neutron.mapper.util.NeutronUtils; import org.opendaylight.groupbasedpolicy.util.IidFactory; -import org.opendaylight.neutron.spi.NeutronSecurityRule; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Prefix; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ContractId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.EndpointGroupId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.Tenant; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.Contract; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.EndpointGroup; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionEgress; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionIngress; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeV4; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolTcp; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.NeutronBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.SecurityGroupsBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.security.groups.SecurityGroup; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.SecurityRulesBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRule; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRuleBuilder; import com.google.common.base.Optional; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; /** @@ -37,65 +52,76 @@ public class NeutronSecurityRuleAwareDataStoreTest extends GbpDataBrokerTest { public final void testAddNeutronSecurityRule_rulesWithRemoteIpPrefix() throws Exception { String tenant = "ad4c6c25-2424-4ad3-97ee-f9691ce03645"; String goldSecGrp = "fe40e28f-ad6a-4a2d-b12a-47510876344a"; - NeutronSecurityRule goldInIpv4 = NeutronEntityFactory.securityRuleWithEtherType( - "166aedab-fdf5-4788-9e36-2b00b5f8722f", tenant, NeutronUtils.IPv4, NeutronUtils.INGRESS, goldSecGrp, + SecurityRule goldInIpv4 = NeutronEntityFactory.securityRuleWithEtherType( + "166aedab-fdf5-4788-9e36-2b00b5f8722f", tenant, EthertypeV4.class, DirectionIngress.class, goldSecGrp, null); - NeutronSecurityRule goldOutIpv4 = NeutronEntityFactory.securityRuleWithEtherType( - "dabfd4da-af89-45dd-85f8-181768c1b4c9", tenant, NeutronUtils.IPv4, NeutronUtils.EGRESS, goldSecGrp, + SecurityRule goldOutIpv4 = NeutronEntityFactory.securityRuleWithEtherType( + "dabfd4da-af89-45dd-85f8-181768c1b4c9", tenant, EthertypeV4.class, DirectionEgress.class, goldSecGrp, null); String serverSecGrp = "71cf4fe5-b146-409e-8151-cd921298ce32"; - NeutronSecurityRule serverIn80Tcp10_1_1_0 = NeutronEntityFactory.securityRuleWithEtherType( - "9dbb533d-d9b2-4dc9-bae7-ee60c8df184d", tenant, NeutronUtils.IPv4, NeutronUtils.INGRESS, serverSecGrp, - null); - serverIn80Tcp10_1_1_0.setSecurityRuleProtocol(NeutronUtils.TCP); - serverIn80Tcp10_1_1_0.setSecurityRulePortMin(80); - serverIn80Tcp10_1_1_0.setSecurityRulePortMax(80); - serverIn80Tcp10_1_1_0.setSecurityRuleRemoteIpPrefix("10.1.1.0/24"); - NeutronSecurityRule serverInIp20_1_1_0 = NeutronEntityFactory.securityRuleWithEtherType( - "adf7e558-de47-4f9e-a9b8-96e19db5d1ac", tenant, NeutronUtils.IPv4, NeutronUtils.INGRESS, serverSecGrp, - null); - serverInIp20_1_1_0.setSecurityRuleRemoteIpPrefix("20.1.1.0/24"); - NeutronSecurityRule serverOutIpv4 = NeutronEntityFactory.securityRuleWithEtherType( - "8b9c48d3-44a8-46be-be35-6f3237d98071", tenant, NeutronUtils.IPv4, NeutronUtils.EGRESS, serverSecGrp, + SecurityRule serverIn80Tcp10_1_1_0 = new SecurityRuleBuilder().setId(new Uuid("9dbb533d-d9b2-4dc9-bae7-ee60c8df184d")) + .setTenantId(new Uuid(tenant)) + .setEthertype(EthertypeV4.class) + .setProtocol(ProtocolTcp.class) + .setPortRangeMin(80) + .setPortRangeMax(80) + .setDirection(DirectionIngress.class) + .setSecurityGroupId(new Uuid(serverSecGrp)) + .setRemoteIpPrefix(new IpPrefix(new Ipv4Prefix("10.1.1.0/24"))) + .build(); + SecurityRule serverInIp20_1_1_0 = new SecurityRuleBuilder().setId(new Uuid("adf7e558-de47-4f9e-a9b8-96e19db5d1ac")) + .setTenantId(new Uuid(tenant)) + .setEthertype(EthertypeV4.class) + .setDirection(DirectionIngress.class) + .setSecurityGroupId(new Uuid(serverSecGrp)) + .setRemoteIpPrefix(new IpPrefix(new Ipv4Prefix("20.1.1.0/24"))) + .build(); + SecurityRule serverOutIpv4 = NeutronEntityFactory.securityRuleWithEtherType( + "8b9c48d3-44a8-46be-be35-6f3237d98071", tenant, EthertypeV4.class, DirectionEgress.class, serverSecGrp, null); DataBroker dataBroker = getDataBroker(); - SecRuleDao secRuleDao = new SecRuleDao(); - SecGroupDao secGroupDao = new SecGroupDao(); - secGroupDao.addSecGroup(NeutronEntityFactory.securityGroup(goldSecGrp, tenant)); - secGroupDao.addSecGroup(NeutronEntityFactory.securityGroup(serverSecGrp, tenant)); - NeutronSecurityRuleAware ruleAware = new NeutronSecurityRuleAware(dataBroker, secRuleDao, secGroupDao); + List secGroups = new ArrayList<>(); + secGroups.add(NeutronEntityFactory.securityGroup(goldSecGrp, tenant)); + secGroups.add(NeutronEntityFactory.securityGroup(serverSecGrp, tenant)); + Neutron neutron = new NeutronBuilder() + .setSecurityGroups(new SecurityGroupsBuilder().setSecurityGroup(secGroups).build()) + .setSecurityRules(new SecurityRulesBuilder().setSecurityRule( + ImmutableList.of(goldInIpv4, goldOutIpv4, serverIn80Tcp10_1_1_0, serverInIp20_1_1_0, serverOutIpv4)) + .build()) + .build(); + NeutronSecurityRuleAware ruleAware = new NeutronSecurityRuleAware(dataBroker); ReadWriteTransaction rwTx = dataBroker.newReadWriteTransaction(); - ruleAware.addNeutronSecurityRule(goldInIpv4, rwTx); - ruleAware.addNeutronSecurityRule(goldOutIpv4, rwTx); - ruleAware.addNeutronSecurityRule(serverIn80Tcp10_1_1_0, rwTx); - ruleAware.addNeutronSecurityRule(serverInIp20_1_1_0, rwTx); - ruleAware.addNeutronSecurityRule(serverOutIpv4, rwTx); + ruleAware.addNeutronSecurityRule(goldInIpv4, neutron, rwTx); + ruleAware.addNeutronSecurityRule(goldOutIpv4, neutron, rwTx); + ruleAware.addNeutronSecurityRule(serverIn80Tcp10_1_1_0, neutron, rwTx); + ruleAware.addNeutronSecurityRule(serverInIp20_1_1_0, neutron, rwTx); + ruleAware.addNeutronSecurityRule(serverOutIpv4, neutron, rwTx); TenantId tenantId = new TenantId(tenant); Optional potentialTenant = rwTx.read(LogicalDatastoreType.CONFIGURATION, IidFactory.tenantIid(tenantId)) .get(); assertTrue(potentialTenant.isPresent()); Optional potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION, - IidFactory.contractIid(tenantId, new ContractId(goldInIpv4.getSecurityRuleUUID()))).get(); + IidFactory.contractIid(tenantId, new ContractId(goldInIpv4.getId().getValue()))).get(); assertTrue(potentialContract.isPresent()); Contract contract = potentialContract.get(); PolicyAssert.assertContract(contract, goldInIpv4); potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION, - IidFactory.contractIid(tenantId, new ContractId(goldOutIpv4.getSecurityRuleUUID()))).get(); + IidFactory.contractIid(tenantId, new ContractId(goldOutIpv4.getId().getValue()))).get(); assertTrue(potentialContract.isPresent()); contract = potentialContract.get(); PolicyAssert.assertContract(contract, goldOutIpv4); potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION, - IidFactory.contractIid(tenantId, new ContractId(serverOutIpv4.getSecurityRuleUUID()))).get(); + IidFactory.contractIid(tenantId, new ContractId(serverOutIpv4.getId().getValue()))).get(); assertTrue(potentialContract.isPresent()); contract = potentialContract.get(); PolicyAssert.assertContract(contract, serverOutIpv4); potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION, - IidFactory.contractIid(tenantId, new ContractId(serverIn80Tcp10_1_1_0.getSecurityRuleUUID()))).get(); + IidFactory.contractIid(tenantId, new ContractId(serverIn80Tcp10_1_1_0.getId().getValue()))).get(); assertTrue(potentialContract.isPresent()); contract = potentialContract.get(); PolicyAssert.assertContractWithEic(contract, serverIn80Tcp10_1_1_0); potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION, - IidFactory.contractIid(tenantId, new ContractId(serverInIp20_1_1_0.getSecurityRuleUUID()))).get(); + IidFactory.contractIid(tenantId, new ContractId(serverInIp20_1_1_0.getId().getValue()))).get(); assertTrue(potentialContract.isPresent()); contract = potentialContract.get(); PolicyAssert.assertContractWithEic(contract, serverInIp20_1_1_0); @@ -105,27 +131,25 @@ public class NeutronSecurityRuleAwareDataStoreTest extends GbpDataBrokerTest { EndpointGroup epg = potentialEpg.get(); PolicyAssert.assertConsumerNamedSelectors( epg, - ImmutableSet.of(new ContractId(goldInIpv4.getSecurityRuleUUID()), - new ContractId(goldOutIpv4.getSecurityRuleUUID()), - new ContractId(serverIn80Tcp10_1_1_0.getSecurityRuleUUID()), - new ContractId(serverInIp20_1_1_0.getSecurityRuleUUID()), - new ContractId(serverOutIpv4.getSecurityRuleUUID()))); + ImmutableSet.of(new ContractId(goldInIpv4.getId().getValue()), + new ContractId(goldOutIpv4.getId().getValue()), + new ContractId(serverIn80Tcp10_1_1_0.getId().getValue()), + new ContractId(serverInIp20_1_1_0.getId().getValue()), + new ContractId(serverOutIpv4.getId().getValue()))); potentialEpg = rwTx.read(LogicalDatastoreType.CONFIGURATION, IidFactory.endpointGroupIid(tenantId, new EndpointGroupId(serverSecGrp))).get(); assertTrue(potentialEpg.isPresent()); epg = potentialEpg.get(); PolicyAssert.assertConsumerNamedSelectors(epg, ImmutableSet.of( - new ContractId(serverIn80Tcp10_1_1_0.getSecurityRuleUUID()), - new ContractId(serverInIp20_1_1_0.getSecurityRuleUUID()), - new ContractId(goldInIpv4.getSecurityRuleUUID()))); + new ContractId(serverIn80Tcp10_1_1_0.getId().getValue()), + new ContractId(serverInIp20_1_1_0.getId().getValue()), + new ContractId(goldInIpv4.getId().getValue()))); } @Test public final void testAddAndDeleteNeutronSecurityRule() throws Exception { DataBroker dataBroker = getDataBroker(); - SecRuleDao secRuleDao = new SecRuleDao(); - SecGroupDao secGroupDao = new SecGroupDao(); - NeutronSecurityRuleAware ruleAware = new NeutronSecurityRuleAware(dataBroker, secRuleDao, secGroupDao); + NeutronSecurityRuleAware ruleAware = new NeutronSecurityRuleAware(dataBroker); final String tenantId = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"; final String secGroupId1 = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"; @@ -133,12 +157,19 @@ public class NeutronSecurityRuleAwareDataStoreTest extends GbpDataBrokerTest { final String secRuleId1 = "dddddddd-dddd-dddd-dddd-dddddddddddd"; final String secRuleId2 = "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee"; - NeutronSecurityRule secRule1 = NeutronEntityFactory.securityRuleWithEtherType(secRuleId1, tenantId, - NeutronUtils.IPv4, NeutronUtils.EGRESS, secGroupId1, secGroupId2); - NeutronSecurityRule secRule2 = NeutronEntityFactory.securityRuleWithEtherType(secRuleId2, tenantId, - NeutronUtils.IPv4, NeutronUtils.INGRESS, secGroupId2, secGroupId1); + List secGroups = new ArrayList<>(); + secGroups.add(NeutronEntityFactory.securityGroup(secGroupId1, tenantId)); + secGroups.add(NeutronEntityFactory.securityGroup(secGroupId2, tenantId)); + SecurityRule secRule1 = NeutronEntityFactory.securityRuleWithEtherType(secRuleId1, tenantId, + EthertypeV4.class, DirectionEgress.class, secGroupId1, secGroupId2); + SecurityRule secRule2 = NeutronEntityFactory.securityRuleWithEtherType(secRuleId2, tenantId, + EthertypeV4.class, DirectionIngress.class, secGroupId2, secGroupId1); + NeutronBuilder neutronBuilder = new NeutronBuilder() + .setSecurityGroups(new SecurityGroupsBuilder().setSecurityGroup(secGroups).build()) + .setSecurityRules(new SecurityRulesBuilder() + .setSecurityRule(ImmutableList.of(secRule1)).build()); - ruleAware.created(secRule1); + ruleAware.onCreated(secRule1, neutronBuilder.build()); PolicyAssert.assertTenantExists(dataBroker, tenantId); PolicyAssert.assertContractExists(dataBroker, tenantId, secRuleId1); @@ -153,7 +184,10 @@ public class NeutronSecurityRuleAwareDataStoreTest extends GbpDataBrokerTest { PolicyAssert.assertClassifierInstanceExists(dataBroker, secRule1); PolicyAssert.assertActionInstanceExists(dataBroker, tenantId, MappingUtils.ACTION_ALLOW.getName()); - ruleAware.created(secRule2); + neutronBuilder.setSecurityRules(new SecurityRulesBuilder() + .setSecurityRule(ImmutableList.of(secRule1, secRule2)).build()); + + ruleAware.onCreated(secRule2, neutronBuilder.build()); PolicyAssert.assertTenantExists(dataBroker, tenantId); PolicyAssert.assertContractExists(dataBroker, tenantId, secRuleId1); @@ -174,7 +208,7 @@ public class NeutronSecurityRuleAwareDataStoreTest extends GbpDataBrokerTest { PolicyAssert.assertProviderNamedSelectors(epGroup2.get(), ImmutableSet.of(new ContractId(secRuleId2))); PolicyAssert.assertConsumerNamedSelectors(epGroup2.get(), ImmutableSet.of(new ContractId(secRuleId1))); - ruleAware.deleted(secRule2); + ruleAware.onDeleted(secRule2, neutronBuilder.build(), null); PolicyAssert.assertTenantExists(dataBroker, tenantId); PolicyAssert.assertContractExists(dataBroker, tenantId, secRuleId1); @@ -196,7 +230,10 @@ public class NeutronSecurityRuleAwareDataStoreTest extends GbpDataBrokerTest { PolicyAssert.assertClassifierInstanceExists(dataBroker, secRule1); PolicyAssert.assertActionInstanceExists(dataBroker, tenantId, MappingUtils.ACTION_ALLOW.getName()); - ruleAware.deleted(secRule1); + neutronBuilder.setSecurityRules(new SecurityRulesBuilder() + .setSecurityRule(ImmutableList.of(secRule1)).build()); + + ruleAware.onDeleted(secRule1, neutronBuilder.build(), null); PolicyAssert.assertContractCount(dataBroker, tenantId, 0); PolicyAssert.assertEndpointGroupExists(dataBroker, tenantId, secGroupId1); @@ -214,48 +251,52 @@ public class NeutronSecurityRuleAwareDataStoreTest extends GbpDataBrokerTest { public final void testAddNeutronSecurityRule_rulesWithoutRemote() throws Exception { String tenant = "ad4c6c25-2424-4ad3-97ee-f9691ce03645"; String goldSecGrp = "fe40e28f-ad6a-4a2d-b12a-47510876344a"; - NeutronSecurityRule goldInIpv4 = NeutronEntityFactory.securityRuleWithEtherType( - "166aedab-fdf5-4788-9e36-2b00b5f8722f", tenant, NeutronUtils.IPv4, NeutronUtils.INGRESS, goldSecGrp, + SecurityRule goldInIpv4 = NeutronEntityFactory.securityRuleWithEtherType( + "166aedab-fdf5-4788-9e36-2b00b5f8722f", tenant, EthertypeV4.class, DirectionIngress.class, goldSecGrp, null); - NeutronSecurityRule goldOutIpv4 = NeutronEntityFactory.securityRuleWithEtherType( - "dabfd4da-af89-45dd-85f8-181768c1b4c9", tenant, NeutronUtils.IPv4, NeutronUtils.EGRESS, goldSecGrp, + SecurityRule goldOutIpv4 = NeutronEntityFactory.securityRuleWithEtherType( + "dabfd4da-af89-45dd-85f8-181768c1b4c9", tenant, EthertypeV4.class, DirectionEgress.class, goldSecGrp, null); String serverSecGrp = "71cf4fe5-b146-409e-8151-cd921298ce32"; - NeutronSecurityRule serverOutIpv4 = NeutronEntityFactory.securityRuleWithEtherType( - "8b9c48d3-44a8-46be-be35-6f3237d98071", tenant, NeutronUtils.IPv4, NeutronUtils.EGRESS, serverSecGrp, + SecurityRule serverOutIpv4 = NeutronEntityFactory.securityRuleWithEtherType( + "8b9c48d3-44a8-46be-be35-6f3237d98071", tenant, EthertypeV4.class, DirectionEgress.class, serverSecGrp, null); - NeutronSecurityRule serverInIpv4 = NeutronEntityFactory.securityRuleWithEtherType( - "adf7e558-de47-4f9e-a9b8-96e19db5d1ac", tenant, NeutronUtils.IPv4, NeutronUtils.INGRESS, serverSecGrp, + SecurityRule serverInIpv4 = NeutronEntityFactory.securityRuleWithEtherType( + "adf7e558-de47-4f9e-a9b8-96e19db5d1ac", tenant, EthertypeV4.class, DirectionIngress.class, serverSecGrp, null); DataBroker dataBroker = getDataBroker(); - SecRuleDao secRuleDao = new SecRuleDao(); - SecGroupDao secGroupDao = new SecGroupDao(); - secGroupDao.addSecGroup(NeutronEntityFactory.securityGroup(goldSecGrp, tenant)); - secGroupDao.addSecGroup(NeutronEntityFactory.securityGroup(serverSecGrp, tenant)); - NeutronSecurityRuleAware ruleAware = new NeutronSecurityRuleAware(dataBroker, secRuleDao, secGroupDao); + List secGroups = new ArrayList<>(); + secGroups.add(NeutronEntityFactory.securityGroup(goldSecGrp, tenant)); + secGroups.add(NeutronEntityFactory.securityGroup(serverSecGrp, tenant)); + Neutron neutron = new NeutronBuilder() + .setSecurityGroups(new SecurityGroupsBuilder().setSecurityGroup(secGroups).build()) + .setSecurityRules(new SecurityRulesBuilder() + .setSecurityRule(ImmutableList.of(goldInIpv4, goldOutIpv4, serverOutIpv4, serverInIpv4)).build()) + .build(); + NeutronSecurityRuleAware ruleAware = new NeutronSecurityRuleAware(dataBroker); ReadWriteTransaction rwTx = dataBroker.newReadWriteTransaction(); - ruleAware.addNeutronSecurityRule(goldInIpv4, rwTx); - ruleAware.addNeutronSecurityRule(goldOutIpv4, rwTx); - ruleAware.addNeutronSecurityRule(serverOutIpv4, rwTx); - ruleAware.addNeutronSecurityRule(serverInIpv4, rwTx); + ruleAware.addNeutronSecurityRule(goldInIpv4, neutron, rwTx); + ruleAware.addNeutronSecurityRule(goldOutIpv4, neutron, rwTx); + ruleAware.addNeutronSecurityRule(serverOutIpv4, neutron, rwTx); + ruleAware.addNeutronSecurityRule(serverInIpv4, neutron, rwTx); TenantId tenantId = new TenantId(tenant); Optional potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION, - IidFactory.contractIid(tenantId, new ContractId(goldInIpv4.getSecurityRuleUUID()))).get(); + IidFactory.contractIid(tenantId, new ContractId(goldInIpv4.getId().getValue()))).get(); assertTrue(potentialContract.isPresent()); Contract contract = potentialContract.get(); PolicyAssert.assertContract(contract, goldInIpv4); potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION, - IidFactory.contractIid(tenantId, new ContractId(goldOutIpv4.getSecurityRuleUUID()))).get(); + IidFactory.contractIid(tenantId, new ContractId(goldOutIpv4.getId().getValue()))).get(); assertTrue(potentialContract.isPresent()); contract = potentialContract.get(); PolicyAssert.assertContract(contract, goldOutIpv4); potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION, - IidFactory.contractIid(tenantId, new ContractId(serverOutIpv4.getSecurityRuleUUID()))).get(); + IidFactory.contractIid(tenantId, new ContractId(serverOutIpv4.getId().getValue()))).get(); assertTrue(potentialContract.isPresent()); contract = potentialContract.get(); PolicyAssert.assertContract(contract, serverOutIpv4); potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION, - IidFactory.contractIid(tenantId, new ContractId(serverInIpv4.getSecurityRuleUUID()))).get(); + IidFactory.contractIid(tenantId, new ContractId(serverInIpv4.getId().getValue()))).get(); assertTrue(potentialContract.isPresent()); contract = potentialContract.get(); PolicyAssert.assertContract(contract, serverInIpv4); @@ -265,70 +306,77 @@ public class NeutronSecurityRuleAwareDataStoreTest extends GbpDataBrokerTest { EndpointGroup epg = potentialEpg.get(); PolicyAssert.assertConsumerNamedSelectors( epg, - ImmutableSet.of(new ContractId(goldInIpv4.getSecurityRuleUUID()), - new ContractId(goldOutIpv4.getSecurityRuleUUID()), - new ContractId(serverOutIpv4.getSecurityRuleUUID()), - new ContractId(serverInIpv4.getSecurityRuleUUID()))); + ImmutableSet.of(new ContractId(goldInIpv4.getId().getValue()), + new ContractId(goldOutIpv4.getId().getValue()), + new ContractId(serverOutIpv4.getId().getValue()), + new ContractId(serverInIpv4.getId().getValue()))); potentialEpg = rwTx.read(LogicalDatastoreType.CONFIGURATION, IidFactory.endpointGroupIid(tenantId, new EndpointGroupId(serverSecGrp))).get(); assertTrue(potentialEpg.isPresent()); PolicyAssert.assertConsumerNamedSelectors( epg, - ImmutableSet.of(new ContractId(goldInIpv4.getSecurityRuleUUID()), - new ContractId(goldOutIpv4.getSecurityRuleUUID()), - new ContractId(serverOutIpv4.getSecurityRuleUUID()), - new ContractId(serverInIpv4.getSecurityRuleUUID()))); + ImmutableSet.of(new ContractId(goldInIpv4.getId().getValue()), + new ContractId(goldOutIpv4.getId().getValue()), + new ContractId(serverOutIpv4.getId().getValue()), + new ContractId(serverInIpv4.getId().getValue()))); } @Test public final void testAddNeutronSecurityRule_asymmetricRulesWithoutRemote() throws Exception { String tenant = "ad4c6c25-2424-4ad3-97ee-f9691ce03645"; String goldSecGrp = "fe40e28f-ad6a-4a2d-b12a-47510876344a"; - NeutronSecurityRule goldInIpv4 = NeutronEntityFactory.securityRuleWithEtherType( - "166aedab-fdf5-4788-9e36-2b00b5f8722f", tenant, NeutronUtils.IPv4, NeutronUtils.INGRESS, goldSecGrp, + SecurityRule goldInIpv4 = NeutronEntityFactory.securityRuleWithEtherType( + "166aedab-fdf5-4788-9e36-2b00b5f8722f", tenant, EthertypeV4.class, DirectionIngress.class, goldSecGrp, null); - NeutronSecurityRule goldOutIpv4 = NeutronEntityFactory.securityRuleWithEtherType( - "dabfd4da-af89-45dd-85f8-181768c1b4c9", tenant, NeutronUtils.IPv4, NeutronUtils.EGRESS, goldSecGrp, + SecurityRule goldOutIpv4 = NeutronEntityFactory.securityRuleWithEtherType( + "dabfd4da-af89-45dd-85f8-181768c1b4c9", tenant, EthertypeV4.class, DirectionEgress.class, goldSecGrp, null); String serverSecGrp = "71cf4fe5-b146-409e-8151-cd921298ce32"; - NeutronSecurityRule serverOutIpv4 = NeutronEntityFactory.securityRuleWithEtherType( - "8b9c48d3-44a8-46be-be35-6f3237d98071", tenant, NeutronUtils.IPv4, NeutronUtils.EGRESS, serverSecGrp, + SecurityRule serverOutIpv4 = NeutronEntityFactory.securityRuleWithEtherType( + "8b9c48d3-44a8-46be-be35-6f3237d98071", tenant, EthertypeV4.class, DirectionEgress.class, serverSecGrp, null); - NeutronSecurityRule serverIn80TcpIpv4 = NeutronEntityFactory.securityRuleWithEtherType( - "adf7e558-de47-4f9e-a9b8-96e19db5d1ac", tenant, NeutronUtils.IPv4, NeutronUtils.INGRESS, serverSecGrp, - null); - serverIn80TcpIpv4.setSecurityRuleProtocol(NeutronUtils.TCP); - serverIn80TcpIpv4.setSecurityRulePortMin(80); - serverIn80TcpIpv4.setSecurityRulePortMax(80); + SecurityRule serverIn80TcpIpv4 = new SecurityRuleBuilder().setId(new Uuid("adf7e558-de47-4f9e-a9b8-96e19db5d1ac")) + .setTenantId(new Uuid(tenant)) + .setEthertype(EthertypeV4.class) + .setProtocol(ProtocolTcp.class) + .setPortRangeMin(80) + .setPortRangeMax(80) + .setDirection(DirectionIngress.class) + .setSecurityGroupId(new Uuid(serverSecGrp)) + .build(); DataBroker dataBroker = getDataBroker(); - SecRuleDao secRuleDao = new SecRuleDao(); - SecGroupDao secGroupDao = new SecGroupDao(); - secGroupDao.addSecGroup(NeutronEntityFactory.securityGroup(goldSecGrp, tenant)); - secGroupDao.addSecGroup(NeutronEntityFactory.securityGroup(serverSecGrp, tenant)); - NeutronSecurityRuleAware ruleAware = new NeutronSecurityRuleAware(dataBroker, secRuleDao, secGroupDao); + List secGroups = new ArrayList<>(); + secGroups.add(NeutronEntityFactory.securityGroup(goldSecGrp, tenant)); + secGroups.add(NeutronEntityFactory.securityGroup(serverSecGrp, tenant)); + Neutron neutron = new NeutronBuilder() + .setSecurityGroups(new SecurityGroupsBuilder().setSecurityGroup(secGroups).build()) + .setSecurityRules(new SecurityRulesBuilder() + .setSecurityRule(ImmutableList.of(goldInIpv4, goldOutIpv4, serverOutIpv4, serverIn80TcpIpv4)).build()) + .build(); + NeutronSecurityRuleAware ruleAware = new NeutronSecurityRuleAware(dataBroker); ReadWriteTransaction rwTx = dataBroker.newReadWriteTransaction(); - ruleAware.addNeutronSecurityRule(goldInIpv4, rwTx); - ruleAware.addNeutronSecurityRule(goldOutIpv4, rwTx); - ruleAware.addNeutronSecurityRule(serverOutIpv4, rwTx); - ruleAware.addNeutronSecurityRule(serverIn80TcpIpv4, rwTx); + ruleAware.addNeutronSecurityRule(goldInIpv4, neutron, rwTx); + ruleAware.addNeutronSecurityRule(goldOutIpv4, neutron, rwTx); + ruleAware.addNeutronSecurityRule(serverOutIpv4, neutron, rwTx); + ruleAware.addNeutronSecurityRule(serverIn80TcpIpv4, neutron, rwTx); TenantId tenantId = new TenantId(tenant); Optional potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION, - IidFactory.contractIid(tenantId, new ContractId(goldInIpv4.getSecurityRuleUUID()))).get(); + IidFactory.contractIid(tenantId, new ContractId(goldInIpv4.getId().getValue()))).get(); assertTrue(potentialContract.isPresent()); Contract contract = potentialContract.get(); PolicyAssert.assertContract(contract, goldInIpv4); potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION, - IidFactory.contractIid(tenantId, new ContractId(goldOutIpv4.getSecurityRuleUUID()))).get(); + IidFactory.contractIid(tenantId, new ContractId(goldOutIpv4.getId().getValue()))).get(); assertTrue(potentialContract.isPresent()); contract = potentialContract.get(); PolicyAssert.assertContract(contract, goldOutIpv4); potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION, - IidFactory.contractIid(tenantId, new ContractId(serverOutIpv4.getSecurityRuleUUID()))).get(); + IidFactory.contractIid(tenantId, new ContractId(serverOutIpv4.getId().getValue()))).get(); assertTrue(potentialContract.isPresent()); contract = potentialContract.get(); PolicyAssert.assertContract(contract, serverOutIpv4); potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION, - IidFactory.contractIid(tenantId, new ContractId(serverIn80TcpIpv4.getSecurityRuleUUID()))).get(); + IidFactory.contractIid(tenantId, new ContractId(serverIn80TcpIpv4.getId().getValue()))).get(); assertTrue(potentialContract.isPresent()); contract = potentialContract.get(); PolicyAssert.assertContract(contract, serverIn80TcpIpv4); @@ -338,64 +386,65 @@ public class NeutronSecurityRuleAwareDataStoreTest extends GbpDataBrokerTest { EndpointGroup epg = potentialEpg.get(); PolicyAssert.assertConsumerNamedSelectors( epg, - ImmutableSet.of(new ContractId(goldInIpv4.getSecurityRuleUUID()), - new ContractId(goldOutIpv4.getSecurityRuleUUID()), - new ContractId(serverOutIpv4.getSecurityRuleUUID()), - new ContractId(serverIn80TcpIpv4.getSecurityRuleUUID()))); + ImmutableSet.of(new ContractId(goldInIpv4.getId().getValue()), + new ContractId(goldOutIpv4.getId().getValue()), + new ContractId(serverOutIpv4.getId().getValue()), + new ContractId(serverIn80TcpIpv4.getId().getValue()))); potentialEpg = rwTx.read(LogicalDatastoreType.CONFIGURATION, IidFactory.endpointGroupIid(tenantId, new EndpointGroupId(serverSecGrp))).get(); assertTrue(potentialEpg.isPresent()); epg = potentialEpg.get(); PolicyAssert.assertConsumerNamedSelectors( epg, - ImmutableSet.of(new ContractId(goldInIpv4.getSecurityRuleUUID()), - new ContractId(serverIn80TcpIpv4.getSecurityRuleUUID()))); + ImmutableSet.of(new ContractId(goldInIpv4.getId().getValue()), + new ContractId(serverIn80TcpIpv4.getId().getValue()))); } @Test public final void testAddNeutronSecurityRule_defaultSecGrp() throws Exception { String tenant = "111aaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"; String defaultSecGrp = "111fffff-ffff-ffff-ffff-ffffffffffff"; - NeutronSecurityRule defaultInIpv4Default = NeutronEntityFactory.securityRuleWithEtherType( - "111ccccc-111c-cccc-cccc-cccccccccccc", tenant, NeutronUtils.IPv4, NeutronUtils.INGRESS, defaultSecGrp, + SecurityRule defaultInIpv4Default = NeutronEntityFactory.securityRuleWithEtherType( + "111ccccc-111c-cccc-cccc-cccccccccccc", tenant, EthertypeV4.class, DirectionIngress.class, defaultSecGrp, defaultSecGrp); - NeutronSecurityRule defaultInIpv6Default = NeutronEntityFactory.securityRuleWithEtherType( - "222ccccc-111c-cccc-cccc-cccccccccccc", tenant, NeutronUtils.IPv6, NeutronUtils.INGRESS, defaultSecGrp, + SecurityRule defaultInIpv6Default = NeutronEntityFactory.securityRuleWithEtherType( + "222ccccc-111c-cccc-cccc-cccccccccccc", tenant, EthertypeV4.class, DirectionIngress.class, defaultSecGrp, defaultSecGrp); - NeutronSecurityRule defaultOutIpv4 = NeutronEntityFactory.securityRuleWithEtherType( - "333ccccc-111c-cccc-cccc-cccccccccccc", tenant, NeutronUtils.IPv4, NeutronUtils.EGRESS, defaultSecGrp, + SecurityRule defaultOutIpv4 = NeutronEntityFactory.securityRuleWithEtherType( + "333ccccc-111c-cccc-cccc-cccccccccccc", tenant, EthertypeV4.class, DirectionEgress.class, defaultSecGrp, null); - NeutronSecurityRule defaultOutIpv6 = NeutronEntityFactory.securityRuleWithEtherType( - "444ccccc-111c-cccc-cccc-cccccccccccc", tenant, NeutronUtils.IPv6, NeutronUtils.EGRESS, defaultSecGrp, + SecurityRule defaultOutIpv6 = NeutronEntityFactory.securityRuleWithEtherType( + "444ccccc-111c-cccc-cccc-cccccccccccc", tenant, EthertypeV4.class, DirectionEgress.class, defaultSecGrp, null); DataBroker dataBroker = getDataBroker(); - SecRuleDao secRuleDao = new SecRuleDao(); - SecGroupDao secGroupDao = new SecGroupDao(); - secGroupDao.addSecGroup(NeutronEntityFactory.securityGroup(defaultSecGrp, tenant)); - NeutronSecurityRuleAware ruleAware = new NeutronSecurityRuleAware(dataBroker, secRuleDao, secGroupDao); + List secGroups = new ArrayList<>(); + secGroups.add(NeutronEntityFactory.securityGroup(defaultSecGrp, tenant)); + Neutron neutron = new NeutronBuilder() + .setSecurityGroups(new SecurityGroupsBuilder().setSecurityGroup(secGroups).build()).build(); + NeutronSecurityRuleAware ruleAware = new NeutronSecurityRuleAware(dataBroker); ReadWriteTransaction rwTx = dataBroker.newReadWriteTransaction(); - ruleAware.addNeutronSecurityRule(defaultInIpv4Default, rwTx); - ruleAware.addNeutronSecurityRule(defaultInIpv6Default, rwTx); - ruleAware.addNeutronSecurityRule(defaultOutIpv4, rwTx); - ruleAware.addNeutronSecurityRule(defaultOutIpv6, rwTx); + ruleAware.addNeutronSecurityRule(defaultInIpv4Default, neutron, rwTx); + ruleAware.addNeutronSecurityRule(defaultInIpv6Default, neutron, rwTx); + ruleAware.addNeutronSecurityRule(defaultOutIpv4, neutron, rwTx); + ruleAware.addNeutronSecurityRule(defaultOutIpv6, neutron, rwTx); TenantId tenantId = new TenantId(tenant); Optional potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION, - IidFactory.contractIid(tenantId, new ContractId(defaultInIpv4Default.getSecurityRuleUUID()))).get(); + IidFactory.contractIid(tenantId, new ContractId(defaultInIpv4Default.getId().getValue()))).get(); assertTrue(potentialContract.isPresent()); Contract contract = potentialContract.get(); PolicyAssert.assertContract(contract, defaultInIpv4Default); potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION, - IidFactory.contractIid(tenantId, new ContractId(defaultInIpv6Default.getSecurityRuleUUID()))).get(); + IidFactory.contractIid(tenantId, new ContractId(defaultInIpv6Default.getId().getValue()))).get(); assertTrue(potentialContract.isPresent()); contract = potentialContract.get(); PolicyAssert.assertContract(contract, defaultInIpv6Default); potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION, - IidFactory.contractIid(tenantId, new ContractId(defaultOutIpv4.getSecurityRuleUUID()))).get(); + IidFactory.contractIid(tenantId, new ContractId(defaultOutIpv4.getId().getValue()))).get(); assertTrue(potentialContract.isPresent()); contract = potentialContract.get(); PolicyAssert.assertContract(contract, defaultOutIpv4); potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION, - IidFactory.contractIid(tenantId, new ContractId(defaultOutIpv6.getSecurityRuleUUID()))).get(); + IidFactory.contractIid(tenantId, new ContractId(defaultOutIpv6.getId().getValue()))).get(); assertTrue(potentialContract.isPresent()); contract = potentialContract.get(); PolicyAssert.assertContract(contract, defaultOutIpv6); @@ -403,21 +452,12 @@ public class NeutronSecurityRuleAwareDataStoreTest extends GbpDataBrokerTest { @Test public void testConstructor_invalidArgument() throws Exception { - DataBroker dataBroker = getDataBroker(); - SecRuleDao secRuleDao = new SecRuleDao(); - SecGroupDao secGroupDao = new SecGroupDao(); - assertExceptionInConstructor(null, secRuleDao, secGroupDao); - assertExceptionInConstructor(dataBroker, null, secGroupDao); - assertExceptionInConstructor(dataBroker, secRuleDao, null); - assertExceptionInConstructor(null, null, null); - } - - private void assertExceptionInConstructor(DataBroker dataBroker, SecRuleDao secRuleDao, SecGroupDao secGroupDao) { try { - new NeutronSecurityRuleAware(dataBroker, secRuleDao, secGroupDao); + new NeutronSecurityRuleAware(null); fail(NullPointerException.class.getName() + " expected"); } catch (NullPointerException ex) { // do nothing } } + } diff --git a/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/NeutronSecurityRuleAwareTest.java b/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/NeutronSecurityRuleAwareTest.java index 5a82b60fc..e77e2937f 100644 --- a/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/NeutronSecurityRuleAwareTest.java +++ b/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/NeutronSecurityRuleAwareTest.java @@ -5,16 +5,29 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import java.util.ArrayList; +import java.util.List; + import org.junit.Test; import org.opendaylight.controller.md.sal.binding.api.DataBroker; -import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.StatusCode; -import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.group.SecGroupDao; import org.opendaylight.groupbasedpolicy.neutron.mapper.test.ConfigDataStoreReader; import org.opendaylight.groupbasedpolicy.neutron.mapper.test.GbpDataBrokerTest; +import org.opendaylight.groupbasedpolicy.neutron.mapper.test.NeutronEntityFactory; import org.opendaylight.groupbasedpolicy.neutron.mapper.test.PolicyAssert; -import org.opendaylight.neutron.spi.NeutronSecurityRule; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Prefix; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.HasDirection.Direction; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.Contract; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionIngress; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeV4; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolTcp; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.NeutronBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.SecurityGroupsBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.security.groups.SecurityGroup; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRule; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRuleBuilder; public class NeutronSecurityRuleAwareTest extends GbpDataBrokerTest { @@ -45,16 +58,16 @@ public class NeutronSecurityRuleAwareTest extends GbpDataBrokerTest { @Test public void testNeutronSecurityRuleCreatedAndDeleted() throws Exception { DataBroker dataProvider = getDataBroker(); - SecGroupDao secGroupDao = new SecGroupDao(); - SecRuleDao secRuleDao = new SecRuleDao(); - NeutronSecurityRuleAware neutronSecurityRuleAware = - new NeutronSecurityRuleAware(dataProvider, secRuleDao, secGroupDao); + NeutronSecurityRuleAware neutronSecurityRuleAware = new NeutronSecurityRuleAware(dataProvider); //create security rule and put to DS - NeutronSecurityRule neutronRule = buildNeutronSecurityRule(); - assertEquals(neutronSecurityRuleAware.canCreate(neutronRule), - StatusCode.OK); - neutronSecurityRuleAware.created(neutronRule); + SecurityRule neutronRule = buildNeutronSecurityRule(); + List secGroups = new ArrayList<>(); + secGroups.add(NeutronEntityFactory.securityGroup(neutronRule.getSecurityGroupId().getValue(), + neutronRule.getTenantId().getValue())); + Neutron neutron = new NeutronBuilder() + .setSecurityGroups(new SecurityGroupsBuilder().setSecurityGroup(secGroups).build()).build(); + neutronSecurityRuleAware.onCreated(neutronRule, neutron); //read security rule PolicyAssert.assertContractExists(dataProvider, RULE_TENANT_ID, RULE_ID); @@ -64,30 +77,23 @@ public class NeutronSecurityRuleAwareTest extends GbpDataBrokerTest { assertNotNull(readContract); assertEquals(readContract.getId().getValue(), RULE_ID); - assertEquals(neutronSecurityRuleAware.canUpdate(neutronRule, neutronRule), - StatusCode.BAD_REQUEST); - //delete rule - assertEquals(neutronSecurityRuleAware.canDelete(neutronRule), - StatusCode.OK); - neutronSecurityRuleAware.deleted(neutronRule); + neutronSecurityRuleAware.onDeleted(neutronRule, neutron, null); PolicyAssert.assertContractNotExists(dataProvider, RULE_TENANT_ID, RULE_ID); } - //create neutron security rule - private NeutronSecurityRule buildNeutronSecurityRule() { - NeutronSecurityRule neutronSecurityRule = new NeutronSecurityRule(); - neutronSecurityRule.setSecurityRuleUUID(RULE_ID); - neutronSecurityRule.setSecurityRuleTenantID(RULE_TENANT_ID); - neutronSecurityRule.setSecurityRuleGroupID(RULE_GROUP_ID); - neutronSecurityRule.setSecurityRuleRemoteIpPrefix("192.0.0.1/24"); - neutronSecurityRule.setSecurityRulePortMin(1000); - neutronSecurityRule.setSecurityRulePortMax(5000); - neutronSecurityRule.setSecurityRuleProtocol("tcp"); - neutronSecurityRule.setSecurityRuleEthertype("IPv4"); - neutronSecurityRule.setSecurityRuleDirection("ingress"); - - return neutronSecurityRule; + // create neutron security rule + private SecurityRule buildNeutronSecurityRule() { + return new SecurityRuleBuilder().setId(new Uuid(RULE_ID)) + .setTenantId(new Uuid(RULE_TENANT_ID)) + .setSecurityGroupId(new Uuid(RULE_GROUP_ID)) + .setRemoteIpPrefix(new IpPrefix(new Ipv4Prefix("192.0.0.1/24"))) + .setPortRangeMin(1000) + .setPortRangeMax(5000) + .setProtocol(ProtocolTcp.class) + .setEthertype(EthertypeV4.class) + .setDirection(DirectionIngress.class) + .build(); } } diff --git a/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SecRuleDaoTest.java b/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SecRuleDaoTest.java deleted file mode 100644 index 663e8d6c8..000000000 --- a/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SecRuleDaoTest.java +++ /dev/null @@ -1,211 +0,0 @@ -package org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.rule; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.util.Set; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.opendaylight.groupbasedpolicy.neutron.mapper.test.NeutronEntityFactory; -import org.opendaylight.neutron.spi.NeutronSecurityRule; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.EndpointGroupId; - -public class SecRuleDaoTest { - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - private SecRuleDao secRuleDao; - - @Before - public void setUp() throws Exception { - secRuleDao = new SecRuleDao(); - } - - @Test - public void testAddAndRemoveSecRule() { - final String xSecGrpId = "cccccccc-cccc-cccc-cccc-cccccccccccc"; - final String ySecGrpId = "dddddddd-dddd-dddd-dddd-dddddddddddd"; - final String nullSecGrpId = null; - - EndpointGroupId xEpGrpId = new EndpointGroupId(xSecGrpId); - EndpointGroupId yEpGrpId = new EndpointGroupId(ySecGrpId); - EndpointGroupId nullEpGrpId = null; - - NeutronSecurityRule secRule1 = NeutronEntityFactory.securityRuleWithGroupIds( - "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaa1", "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", xSecGrpId, nullSecGrpId); - - NeutronSecurityRule secRule2 = NeutronEntityFactory.securityRuleWithGroupIds( - "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaa2", "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", xSecGrpId, xSecGrpId); - - NeutronSecurityRule secRule3 = NeutronEntityFactory.securityRuleWithGroupIds( - "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaa3", "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", xSecGrpId, ySecGrpId); - - NeutronSecurityRule secRule4 = NeutronEntityFactory.securityRuleWithGroupIds( - "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaa4", "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", ySecGrpId, nullSecGrpId); - - NeutronSecurityRule secRule5 = NeutronEntityFactory.securityRuleWithGroupIds( - "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaa5", "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", ySecGrpId, ySecGrpId); - - NeutronSecurityRule secRule6 = NeutronEntityFactory.securityRuleWithGroupIds( - "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaa6", "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", ySecGrpId, xSecGrpId); - - secRuleDao.addSecRule(secRule1); - assertSecRulesByOwnerSecGrpId(xEpGrpId, secRule1); - assertSecRulesWithoutRemoteSecGrpBySecGrpId(xEpGrpId, secRule1); - assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, nullEpGrpId, secRule1); - assertAllOwnerSecGrps(xEpGrpId); - - secRuleDao.addSecRule(secRule2); - assertSecRulesByOwnerSecGrpId(xEpGrpId, secRule1, secRule2); - assertSecRulesWithoutRemoteSecGrpBySecGrpId(xEpGrpId, secRule1); - assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, nullEpGrpId, secRule1); - assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, xEpGrpId, secRule2); - assertAllOwnerSecGrps(xEpGrpId); - - secRuleDao.addSecRule(secRule3); - assertSecRulesByOwnerSecGrpId(xEpGrpId, secRule1, secRule2, secRule3); - assertSecRulesWithoutRemoteSecGrpBySecGrpId(xEpGrpId, secRule1); - assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, nullEpGrpId, secRule1); - assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, xEpGrpId, secRule2); - assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, yEpGrpId, secRule3); - assertAllOwnerSecGrps(xEpGrpId); - - secRuleDao.addSecRule(secRule4); - assertSecRulesByOwnerSecGrpId(yEpGrpId, secRule4); - assertSecRulesWithoutRemoteSecGrpBySecGrpId(yEpGrpId, secRule4); - assertSecRulesBySecGrpIdAndRemoteSecGrpId(yEpGrpId, nullEpGrpId, secRule4); - assertAllOwnerSecGrps(xEpGrpId, yEpGrpId); - - secRuleDao.addSecRule(secRule5); - assertSecRulesByOwnerSecGrpId(yEpGrpId, secRule4, secRule5); - assertSecRulesWithoutRemoteSecGrpBySecGrpId(yEpGrpId, secRule4); - assertSecRulesBySecGrpIdAndRemoteSecGrpId(yEpGrpId, nullEpGrpId, secRule4); - assertSecRulesBySecGrpIdAndRemoteSecGrpId(yEpGrpId, yEpGrpId, secRule5); - assertAllOwnerSecGrps(xEpGrpId, yEpGrpId); - - secRuleDao.addSecRule(secRule6); - assertSecRulesByOwnerSecGrpId(yEpGrpId, secRule4, secRule5, secRule6); - assertSecRulesWithoutRemoteSecGrpBySecGrpId(yEpGrpId, secRule4); - assertSecRulesBySecGrpIdAndRemoteSecGrpId(yEpGrpId, nullEpGrpId, secRule4); - assertSecRulesBySecGrpIdAndRemoteSecGrpId(yEpGrpId, yEpGrpId, secRule5); - assertSecRulesBySecGrpIdAndRemoteSecGrpId(yEpGrpId, xEpGrpId, secRule6); - assertAllOwnerSecGrps(xEpGrpId, yEpGrpId); - - // check once more security rules with owner group id = xSecGrpId - assertSecRulesByOwnerSecGrpId(xEpGrpId, secRule1, secRule2, secRule3); - assertSecRulesWithoutRemoteSecGrpBySecGrpId(xEpGrpId, secRule1); - assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, nullEpGrpId, secRule1); - assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, xEpGrpId, secRule2); - assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, yEpGrpId, secRule3); - - secRuleDao.removeSecRule(secRule6); - assertSecRulesByOwnerSecGrpId(yEpGrpId, secRule4, secRule5); - assertSecRulesWithoutRemoteSecGrpBySecGrpId(yEpGrpId, secRule4); - assertSecRulesBySecGrpIdAndRemoteSecGrpId(yEpGrpId, nullEpGrpId, secRule4); - assertSecRulesBySecGrpIdAndRemoteSecGrpId(yEpGrpId, yEpGrpId, secRule5); - assertAllOwnerSecGrps(xEpGrpId, yEpGrpId); - - secRuleDao.removeSecRule(secRule5); - assertSecRulesByOwnerSecGrpId(yEpGrpId, secRule4); - assertSecRulesWithoutRemoteSecGrpBySecGrpId(yEpGrpId, secRule4); - assertSecRulesBySecGrpIdAndRemoteSecGrpId(yEpGrpId, nullEpGrpId, secRule4); - assertAllOwnerSecGrps(xEpGrpId, yEpGrpId); - - secRuleDao.removeSecRule(secRule4); - - // check once more security rules with owner group id = xSecGrpId - assertSecRulesByOwnerSecGrpId(xEpGrpId, secRule1, secRule2, secRule3); - assertSecRulesWithoutRemoteSecGrpBySecGrpId(xEpGrpId, secRule1); - assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, nullEpGrpId, secRule1); - assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, xEpGrpId, secRule2); - assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, yEpGrpId, secRule3); - - secRuleDao.removeSecRule(secRule3); - assertSecRulesByOwnerSecGrpId(xEpGrpId, secRule1, secRule2); - assertSecRulesWithoutRemoteSecGrpBySecGrpId(xEpGrpId, secRule1); - assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, nullEpGrpId, secRule1); - assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, xEpGrpId, secRule2); - assertAllOwnerSecGrps(xEpGrpId); - - secRuleDao.removeSecRule(secRule2); - assertSecRulesByOwnerSecGrpId(xEpGrpId, secRule1); - assertSecRulesWithoutRemoteSecGrpBySecGrpId(xEpGrpId, secRule1); - assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, nullEpGrpId, secRule1); - assertAllOwnerSecGrps(xEpGrpId); - - secRuleDao.removeSecRule(secRule1); - assertSecRulesByOwnerSecGrpId(xEpGrpId); - assertSecRulesWithoutRemoteSecGrpBySecGrpId(xEpGrpId); - assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, nullEpGrpId); - assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, xEpGrpId); - assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, yEpGrpId); - assertSecRulesByOwnerSecGrpId(yEpGrpId); - assertSecRulesWithoutRemoteSecGrpBySecGrpId(yEpGrpId); - assertSecRulesBySecGrpIdAndRemoteSecGrpId(yEpGrpId, nullEpGrpId); - assertSecRulesBySecGrpIdAndRemoteSecGrpId(yEpGrpId, yEpGrpId); - assertSecRulesBySecGrpIdAndRemoteSecGrpId(yEpGrpId, xEpGrpId); - assertAllOwnerSecGrps(); - } - - @Test - public void testAddSecGroup_nullArgument() { - thrown.expect(NullPointerException.class); - secRuleDao.addSecRule(null); - } - - @Test - public void testRemoveNonExistingSecRule() { - NeutronSecurityRule secRule = NeutronEntityFactory.securityRuleWithGroupIds( - "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", - "cccccccc-cccc-cccc-cccc-cccccccccccc", "dddddddd-dddd-dddd-dddd-dddddddddddd"); - secRuleDao.removeSecRule(secRule); - } - - @Test - public void testRemoveNonExistingSecRule_remoteSecGroupIdIsNull() { - NeutronSecurityRule secRule = NeutronEntityFactory.securityRuleWithGroupIds( - "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", - "cccccccc-cccc-cccc-cccc-cccccccccccc", null); - secRuleDao.removeSecRule(secRule); - } - - private static void assertSecRules(Set secRules, NeutronSecurityRule... expectedSecRules) { - assertNotNull(secRules); - assertEquals(expectedSecRules.length, secRules.size()); - for (int i = 0; i < expectedSecRules.length; ++i) { - assertTrue(secRules.contains(expectedSecRules[i])); - } - } - - private void assertSecRulesByOwnerSecGrpId(EndpointGroupId ownerEpGrpId, NeutronSecurityRule... expectedSecRules) { - Set secRules = secRuleDao.getSecRulesByOwnerSecGrpId(ownerEpGrpId); - assertSecRules(secRules, expectedSecRules); - } - - private void assertSecRulesBySecGrpIdAndRemoteSecGrpId(EndpointGroupId ownerEpGrpId, EndpointGroupId remoteEpGrpId, - NeutronSecurityRule... expectedSecRules) { - Set secRules = secRuleDao.getSecRulesBySecGrpIdAndRemoteSecGrpId(ownerEpGrpId, - remoteEpGrpId); - assertSecRules(secRules, expectedSecRules); - } - - private void assertSecRulesWithoutRemoteSecGrpBySecGrpId(EndpointGroupId ownerEpGrpId, - NeutronSecurityRule... expectedSecRules) { - Set secRules = secRuleDao.getSecRulesWithoutRemoteSecGrpBySecGrpId(ownerEpGrpId); - assertSecRules(secRules, expectedSecRules); - } - - private void assertAllOwnerSecGrps(EndpointGroupId... expectedEndpointGropuIds) { - Set allOwnerSecGrps = secRuleDao.getAllOwnerSecGrps(); - assertNotNull(allOwnerSecGrps); - assertEquals(expectedEndpointGropuIds.length, allOwnerSecGrps.size()); - for (int i = 0; i < expectedEndpointGropuIds.length; ++i) { - assertTrue(allOwnerSecGrps.contains(expectedEndpointGropuIds[i])); - } - } -} diff --git a/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SecRuleEntityDecoderTest.java b/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SecRuleEntityDecoderTest.java index ccda7b17d..6d5e50d51 100644 --- a/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SecRuleEntityDecoderTest.java +++ b/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SecRuleEntityDecoderTest.java @@ -15,9 +15,9 @@ import org.opendaylight.groupbasedpolicy.api.sf.EtherTypeClassifierDefinition; import org.opendaylight.groupbasedpolicy.api.sf.IpProtoClassifierDefinition; import org.opendaylight.groupbasedpolicy.api.sf.L4ClassifierDefinition; import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils; -import org.opendaylight.groupbasedpolicy.neutron.mapper.util.NeutronUtils; -import org.opendaylight.neutron.spi.NeutronSecurityRule; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Prefix; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ClassifierName; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ClauseName; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ParameterName; @@ -32,215 +32,46 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.contract.Clause; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.contract.clause.ConsumerMatchers; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.subject.feature.instances.ClassifierInstance; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionBase; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionEgress; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionIngress; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeBase; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeV4; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeV6; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolBase; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolIcmp; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolTcp; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolUdp; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRule; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRuleBuilder; public class SecRuleEntityDecoderTest { @Rule public ExpectedException thrown = ExpectedException.none(); - private NeutronSecurityRule secRule; + private SecurityRuleBuilder secRuleBuilder; @Before public void setUp() throws Exception { - secRule = new NeutronSecurityRule(); + secRuleBuilder = new SecurityRuleBuilder().setId(new Uuid("01234567-abcd-ef01-0123-0123456789ab")); } @Test - public final void testGetTenantId_lowercaseUuidTenantID() { - secRule.setSecurityRuleTenantID("01234567-abcd-ef01-0123-0123456789ab"); + public final void testGetContractId() { Assert.assertEquals("01234567-abcd-ef01-0123-0123456789ab", - SecRuleEntityDecoder.getTenantId(secRule).getValue()); - } - - @Test - public final void testGetTenantId_uppercaseUuidTenantID() { - secRule.setSecurityRuleTenantID("01234567-ABCD-EF01-0123-0123456789AB"); - Assert.assertEquals("01234567-ABCD-EF01-0123-0123456789AB", - SecRuleEntityDecoder.getTenantId(secRule).getValue()); - } - - @Test - public final void testGetTenantId_mixUuidTenantID() { - secRule.setSecurityRuleTenantID("01234567-ABCD-ef01-0123-0123456789Ab"); - Assert.assertEquals("01234567-ABCD-ef01-0123-0123456789Ab", - SecRuleEntityDecoder.getTenantId(secRule).getValue()); - } - - @Test - public final void testGetTenantId_noSlashLowercaseUuidTenantID() { - secRule.setSecurityRuleTenantID("01234567abcdef0101230123456789ab"); - Assert.assertEquals("01234567-abcd-ef01-0123-0123456789ab", - SecRuleEntityDecoder.getTenantId(secRule).getValue()); - } - - @Test - public final void testGetTenantId_noSlashUppercaseUuidTenantID() { - secRule.setSecurityRuleTenantID("01234567ABCDEF0101230123456789AB"); - Assert.assertEquals("01234567-ABCD-EF01-0123-0123456789AB", - SecRuleEntityDecoder.getTenantId(secRule).getValue()); - } - - @Test - public final void testGetTenantId_noSlashMixUuidTenantID() { - secRule.setSecurityRuleTenantID("01234567ABCDef0101230123456789Ab"); - Assert.assertEquals("01234567-ABCD-ef01-0123-0123456789Ab", - SecRuleEntityDecoder.getTenantId(secRule).getValue()); - } - - @Test - public final void testGetTenantId_emptyUuidTenantID() { - secRule.setSecurityRuleTenantID(""); - thrown.expect(NullPointerException.class); - SecRuleEntityDecoder.getTenantId(secRule); - } - - @Test - public final void testGetTenantId_nullUuidTenantID() { - secRule.setSecurityRuleTenantID(null); - thrown.expect(NullPointerException.class); - SecRuleEntityDecoder.getTenantId(secRule); - } - - @Test - public final void testGetProviderEpgId_lowercaseUuidGroupID() { - secRule.setSecurityRuleGroupID("01234567-abcd-ef01-0123-0123456789ab"); - Assert.assertEquals("01234567-abcd-ef01-0123-0123456789ab", - SecRuleEntityDecoder.getProviderEpgId(secRule).getValue()); - } - - @Test - public final void testGetProviderEpgId_uppercaseUuidGroupID() { - secRule.setSecurityRuleGroupID("01234567-ABCD-EF01-0123-0123456789AB"); - Assert.assertEquals("01234567-ABCD-EF01-0123-0123456789AB", - SecRuleEntityDecoder.getProviderEpgId(secRule).getValue()); - } - - @Test - public final void testGetProviderEpgId_mixUuidGroupID() { - secRule.setSecurityRuleGroupID("01234567-ABCD-ef01-0123-0123456789Ab"); - Assert.assertEquals("01234567-ABCD-ef01-0123-0123456789Ab", - SecRuleEntityDecoder.getProviderEpgId(secRule).getValue()); - } - - @Test - public final void testGetProviderEpgId_noSlashLowercaseUuidGroupID() { - secRule.setSecurityRuleGroupID("01234567abcdef0101230123456789ab"); - Assert.assertEquals("01234567-abcd-ef01-0123-0123456789ab", - SecRuleEntityDecoder.getProviderEpgId(secRule).getValue()); - } - - @Test - public final void testGetProviderEpgId_noSlashUppercaseUuidGroupID() { - secRule.setSecurityRuleGroupID("01234567ABCDEF0101230123456789AB"); - Assert.assertEquals("01234567-ABCD-EF01-0123-0123456789AB", - SecRuleEntityDecoder.getProviderEpgId(secRule).getValue()); - } - - @Test - public final void testGetProviderEpgId_noSlashMixUuidGroupID() { - secRule.setSecurityRuleGroupID("01234567ABCDef0101230123456789Ab"); - Assert.assertEquals("01234567-ABCD-ef01-0123-0123456789Ab", - SecRuleEntityDecoder.getProviderEpgId(secRule).getValue()); - } - - @Test - public final void testGetProviderEpgId_emptyUuidGroupID() { - secRule.setSecurityRuleGroupID(""); - thrown.expect(IllegalArgumentException.class); - SecRuleEntityDecoder.getProviderEpgId(secRule); - } - - @Test - public final void testGetProviderEpgId_nullUuidGroupID() { - secRule.setSecurityRuleGroupID(null); - thrown.expect(NullPointerException.class); - SecRuleEntityDecoder.getProviderEpgId(secRule); - } - - @Test - public final void testGetConsumerEpgId_lowercaseUuidRemoteGroupID() { - secRule.setSecurityRemoteGroupID("01234567-abcd-ef01-0123-0123456789ab"); - Assert.assertEquals("01234567-abcd-ef01-0123-0123456789ab", - SecRuleEntityDecoder.getConsumerEpgId(secRule).getValue()); - } - - @Test - public final void testGetConsumerEpgId_uppercaseUuidRemoteGroupID() { - secRule.setSecurityRemoteGroupID("01234567-ABCD-EF01-0123-0123456789AB"); - Assert.assertEquals("01234567-ABCD-EF01-0123-0123456789AB", - SecRuleEntityDecoder.getConsumerEpgId(secRule).getValue()); - } - - @Test - public final void testGetConsumerEpgId_mixUuidRemoteGroupID() { - secRule.setSecurityRemoteGroupID("01234567-ABCD-ef01-0123-0123456789Ab"); - Assert.assertEquals("01234567-ABCD-ef01-0123-0123456789Ab", - SecRuleEntityDecoder.getConsumerEpgId(secRule).getValue()); - } - - @Test - public final void testGetConsumerEpgId_noSlashLowercaseUuidRemoteGroupID() { - secRule.setSecurityRemoteGroupID("01234567abcdef0101230123456789ab"); - Assert.assertEquals("01234567-abcd-ef01-0123-0123456789ab", - SecRuleEntityDecoder.getConsumerEpgId(secRule).getValue()); - } - - @Test - public final void testGetConsumerEpgId_noSlashUppercaseUuidRemoteGroupID() { - secRule.setSecurityRemoteGroupID("01234567ABCDEF0101230123456789AB"); - Assert.assertEquals("01234567-ABCD-EF01-0123-0123456789AB", - SecRuleEntityDecoder.getConsumerEpgId(secRule).getValue()); - } - - @Test - public final void testGetConsumerEpgId_noSlashMixUuidRemoteGroupID() { - secRule.setSecurityRemoteGroupID("01234567ABCDef0101230123456789Ab"); - Assert.assertEquals("01234567-ABCD-ef01-0123-0123456789Ab", - SecRuleEntityDecoder.getConsumerEpgId(secRule).getValue()); - } - - @Test - public final void testGetConsumerEpgId_emptyUuidRemoteGroupID() { - secRule.setSecurityRemoteGroupID(""); - Assert.assertSame(null, SecRuleEntityDecoder.getConsumerEpgId(secRule)); - } - - @Test - public final void testGetConsumerEpgId_nullUuidRemoteGroupID() { - secRule.setSecurityRemoteGroupID(null); - Assert.assertSame(null, SecRuleEntityDecoder.getConsumerEpgId(secRule)); - } - - @Test - public final void testGetContractId_lowercaseUuidID() { - secRule.setSecurityRuleUUID("01234567-abcd-ef01-0123-0123456789ab"); - Assert.assertEquals("01234567-abcd-ef01-0123-0123456789ab", - SecRuleEntityDecoder.getContractId(secRule).getValue()); - } - - @Test - public final void testGetContractId_uppercaseUuidID() { - secRule.setSecurityRuleUUID("01234567-ABCD-EF01-0123-0123456789AB"); - Assert.assertEquals("01234567-ABCD-EF01-0123-0123456789AB", - SecRuleEntityDecoder.getContractId(secRule).getValue()); - } - - @Test - public final void testGetContractId_mixUuidID() { - secRule.setSecurityRuleUUID("01234567-ABCD-ef01-0123-0123456789Ab"); - Assert.assertEquals("01234567-ABCD-ef01-0123-0123456789Ab", - SecRuleEntityDecoder.getContractId(secRule).getValue()); + SecRuleEntityDecoder.getContractId(secRuleBuilder.build()).getValue()); } @Test public final void testGetClassifierInstance_onlyEthertype() { - secRule.setSecurityRuleEthertype(NeutronUtils.IPv4); - ClassifierInstance ci = SecRuleEntityDecoder.getClassifierInstance(secRule); + secRuleBuilder.setEthertype(EthertypeV4.class); + ClassifierInstance ci = SecRuleEntityDecoder.getClassifierInstance(secRuleBuilder.build()); Assert.assertEquals(EtherTypeClassifierDefinition.DEFINITION.getId(), ci.getClassifierDefinitionId()); // name is ether_type_IPv4 String expectedName = new StringBuilder().append(EtherTypeClassifierDefinition.DEFINITION.getName().getValue()) .append(MappingUtils.NAME_VALUE_DELIMETER) - .append(NeutronUtils.IPv4) + .append(EthertypeV4.class.getSimpleName()) .toString(); Assert.assertEquals(expectedName, ci.getName().getValue()); Assert.assertEquals(expectedName, ci.getName().getValue()); @@ -254,18 +85,18 @@ public class SecRuleEntityDecoderTest { @Test public final void testGetClassifierInstance_EthertypeAndProtocol() { - secRule.setSecurityRuleEthertype(NeutronUtils.IPv4); - secRule.setSecurityRuleProtocol(NeutronUtils.TCP); - ClassifierInstance ci = SecRuleEntityDecoder.getClassifierInstance(secRule); + secRuleBuilder.setEthertype(EthertypeV4.class); + secRuleBuilder.setProtocol(ProtocolTcp.class); + ClassifierInstance ci = SecRuleEntityDecoder.getClassifierInstance(secRuleBuilder.build()); Assert.assertEquals(IpProtoClassifierDefinition.DEFINITION.getId(), ci.getClassifierDefinitionId()); // name is ip_proto_tcp__ether_type_IPv4 String expectedName = new StringBuilder().append(IpProtoClassifierDefinition.DEFINITION.getName().getValue()) .append(MappingUtils.NAME_VALUE_DELIMETER) - .append(NeutronUtils.TCP) + .append(ProtocolTcp.class.getSimpleName()) .append(MappingUtils.NAME_DOUBLE_DELIMETER) .append(EtherTypeClassifierDefinition.DEFINITION.getName().getValue()) .append(MappingUtils.NAME_VALUE_DELIMETER) - .append(NeutronUtils.IPv4) + .append(EthertypeV4.class.getSimpleName()) .toString(); Assert.assertEquals(expectedName, ci.getName().getValue()); List parameterValues = ci.getParameterValue(); @@ -292,27 +123,29 @@ public class SecRuleEntityDecoderTest { @Test public final void testGetClassifierInstance_EthertypeAndProtocolAndPort() { - secRule.setSecurityRuleEthertype(NeutronUtils.IPv4); - secRule.setSecurityRuleProtocol(NeutronUtils.TCP); - secRule.setSecurityRulePortMin(5); - secRule.setSecurityRulePortMax(5); - ClassifierInstance ci = SecRuleEntityDecoder.getClassifierInstance(secRule); + secRuleBuilder.setEthertype(EthertypeV4.class); + secRuleBuilder.setProtocol(ProtocolTcp.class); + secRuleBuilder.setPortRangeMin(5); + secRuleBuilder.setPortRangeMax(5); + ClassifierInstance ci = SecRuleEntityDecoder.getClassifierInstance(secRuleBuilder.build()); Assert.assertEquals(L4ClassifierDefinition.DEFINITION.getId(), ci.getClassifierDefinitionId()); // name is l4_destport-5__ip_proto-tcp__ether_type-IPv4 String expectedName = new StringBuilder().append(L4ClassifierDefinition.DEFINITION.getName().getValue()) .append(MappingUtils.NAME_DELIMETER) .append(L4ClassifierDefinition.DST_PORT_PARAM) .append(MappingUtils.NAME_VALUE_DELIMETER) - .append(secRule.getSecurityRulePortMin()) + .append(secRuleBuilder.getPortRangeMin()) .append(MappingUtils.NAME_DOUBLE_DELIMETER) .append(IpProtoClassifierDefinition.DEFINITION.getName().getValue()) .append(MappingUtils.NAME_VALUE_DELIMETER) - .append(NeutronUtils.TCP) + .append(ProtocolTcp.class.getSimpleName()) .append(MappingUtils.NAME_DOUBLE_DELIMETER) .append(EtherTypeClassifierDefinition.DEFINITION.getName().getValue()) .append(MappingUtils.NAME_VALUE_DELIMETER) - .append(NeutronUtils.IPv4) + .append(EthertypeV4.class.getSimpleName()) .toString(); + System.out.println(expectedName); + System.out.println(ci.getName().getValue()); Assert.assertEquals(expectedName, ci.getName().getValue()); List parameterValues = ci.getParameterValue(); Assert.assertNotNull(parameterValues); @@ -350,11 +183,11 @@ public class SecRuleEntityDecoderTest { @Test public final void testGetClassifierInstance_EthertypeAndProtocolAndPorts() { - secRule.setSecurityRuleEthertype(NeutronUtils.IPv4); - secRule.setSecurityRuleProtocol(NeutronUtils.TCP); - secRule.setSecurityRulePortMin(5); - secRule.setSecurityRulePortMax(10); - ClassifierInstance ci = SecRuleEntityDecoder.getClassifierInstance(secRule); + secRuleBuilder.setEthertype(EthertypeV4.class); + secRuleBuilder.setProtocol(ProtocolTcp.class); + secRuleBuilder.setPortRangeMin(5); + secRuleBuilder.setPortRangeMax(10); + ClassifierInstance ci = SecRuleEntityDecoder.getClassifierInstance(secRuleBuilder.build()); Assert.assertEquals(L4ClassifierDefinition.DEFINITION.getId(), ci.getClassifierDefinitionId()); // name is l4_destport_range_min-5_max-10__ip_proto-tcp__ether_type-IPv4 String expectedName = new StringBuilder().append(L4ClassifierDefinition.DEFINITION.getName().getValue()) @@ -362,69 +195,72 @@ public class SecRuleEntityDecoderTest { .append(L4ClassifierDefinition.DST_PORT_RANGE_PARAM) .append(SecRuleNameDecoder.MIN_PORT) .append(MappingUtils.NAME_VALUE_DELIMETER) - .append(secRule.getSecurityRulePortMin()) + .append(secRuleBuilder.getPortRangeMin()) .append(SecRuleNameDecoder.MAX_PORT) .append(MappingUtils.NAME_VALUE_DELIMETER) - .append(secRule.getSecurityRulePortMax()) + .append(secRuleBuilder.getPortRangeMax()) .append(MappingUtils.NAME_DOUBLE_DELIMETER) .append(IpProtoClassifierDefinition.DEFINITION.getName().getValue()) .append(MappingUtils.NAME_VALUE_DELIMETER) - .append(NeutronUtils.TCP) + .append(ProtocolTcp.class.getSimpleName()) .append(MappingUtils.NAME_DOUBLE_DELIMETER) .append(EtherTypeClassifierDefinition.DEFINITION.getName().getValue()) .append(MappingUtils.NAME_VALUE_DELIMETER) - .append(NeutronUtils.IPv4) + .append(EthertypeV4.class.getSimpleName()) .toString(); Assert.assertEquals(expectedName, ci.getName().getValue()); } @Test public final void testGetClassifierRef() { - secRule.setSecurityRuleDirection(NeutronUtils.INGRESS); - secRule.setSecurityRuleEthertype(NeutronUtils.IPv4); - ClassifierName expectedName = SecRuleNameDecoder.getClassifierRefName(secRule); - ClassifierRef cr = SecRuleEntityDecoder.getClassifierRef(secRule); + secRuleBuilder.setDirection(DirectionIngress.class); + secRuleBuilder.setEthertype(EthertypeV4.class); + ClassifierName expectedName = SecRuleNameDecoder.getClassifierRefName(secRuleBuilder.build()); + ClassifierRef cr = SecRuleEntityDecoder.getClassifierRef(secRuleBuilder.build()); Assert.assertEquals(expectedName, cr.getName()); } @Test public final void testGetDirection_directionIngress() { - secRule.setSecurityRuleDirection(NeutronUtils.INGRESS); - Assert.assertEquals(Direction.In, SecRuleEntityDecoder.getDirection(secRule)); + secRuleBuilder.setDirection(DirectionIngress.class); + Assert.assertEquals(Direction.In, SecRuleEntityDecoder.getDirection(secRuleBuilder.build())); } @Test public final void testGetDirection_directionEgress() { - secRule.setSecurityRuleDirection(NeutronUtils.EGRESS); - Assert.assertEquals(Direction.Out, SecRuleEntityDecoder.getDirection(secRule)); + secRuleBuilder.setDirection(DirectionEgress.class); + Assert.assertEquals(Direction.Out, SecRuleEntityDecoder.getDirection(secRuleBuilder.build())); } @Test public final void testGetDirection_directionNull() { - secRule.setSecurityRuleDirection(null); + secRuleBuilder.setDirection(null); thrown.expect(IllegalArgumentException.class); - SecRuleEntityDecoder.getDirection(secRule); + SecRuleEntityDecoder.getDirection(secRuleBuilder.build()); } @Test public final void testGetDirection_directionUnknown() { - secRule.setSecurityRuleDirection("foo"); + secRuleBuilder.setDirection(UnknownDirection.class); thrown.expect(IllegalArgumentException.class); - SecRuleEntityDecoder.getDirection(secRule); + SecRuleEntityDecoder.getDirection(secRuleBuilder.build()); + } + + private static class UnknownDirection extends DirectionBase { } @Test public final void testGetClause_noRemoteIpPrefix() { - secRule.setSecurityRuleDirection(NeutronUtils.INGRESS); - secRule.setSecurityRuleEthertype(NeutronUtils.IPv4); - ClauseName expectedClauseName = SecRuleNameDecoder.getClauseName(secRule); - Clause clause = SecRuleEntityDecoder.getClause(secRule); + secRuleBuilder.setDirection(DirectionIngress.class); + secRuleBuilder.setEthertype(EthertypeV4.class); + ClauseName expectedClauseName = SecRuleNameDecoder.getClauseName(secRuleBuilder.build()); + Clause clause = SecRuleEntityDecoder.getClause(secRuleBuilder.build()); Assert.assertEquals(expectedClauseName, clause.getName()); List subjectRefs = clause.getSubjectRefs(); Assert.assertNotNull(subjectRefs); Assert.assertEquals(1, subjectRefs.size()); SubjectName subjectNameFromClause = subjectRefs.get(0); - SubjectName expectedSubjectName = SecRuleNameDecoder.getSubjectName(secRule); + SubjectName expectedSubjectName = SecRuleNameDecoder.getSubjectName(secRuleBuilder.build()); Assert.assertEquals(expectedSubjectName, subjectNameFromClause); Assert.assertNull(clause.getConsumerMatchers()); Assert.assertNull(clause.getProviderMatchers()); @@ -432,17 +268,17 @@ public class SecRuleEntityDecoderTest { @Test public final void testGetClause_remoteIpPrefix() { - secRule.setSecurityRuleDirection(NeutronUtils.INGRESS); - secRule.setSecurityRuleEthertype(NeutronUtils.IPv4); - secRule.setSecurityRuleRemoteIpPrefix("10.0.0.0/8"); - Clause clause = SecRuleEntityDecoder.getClause(secRule); - ClauseName expectedClauseName = SecRuleNameDecoder.getClauseName(secRule); + secRuleBuilder.setDirection(DirectionIngress.class); + secRuleBuilder.setEthertype(EthertypeV4.class); + secRuleBuilder.setRemoteIpPrefix(new IpPrefix(new Ipv4Prefix("10.0.0.0/8"))); + Clause clause = SecRuleEntityDecoder.getClause(secRuleBuilder.build()); + ClauseName expectedClauseName = SecRuleNameDecoder.getClauseName(secRuleBuilder.build()); Assert.assertEquals(expectedClauseName, clause.getName()); List subjectRefs = clause.getSubjectRefs(); Assert.assertNotNull(subjectRefs); Assert.assertEquals(1, subjectRefs.size()); SubjectName subjectNameFromClause = subjectRefs.get(0); - SubjectName expectedSubjectName = SecRuleNameDecoder.getSubjectName(secRule); + SubjectName expectedSubjectName = SecRuleNameDecoder.getSubjectName(secRuleBuilder.build()); Assert.assertEquals(expectedSubjectName, subjectNameFromClause); Assert.assertNull(clause.getProviderMatchers()); ConsumerMatchers consumerMatchers = clause.getConsumerMatchers(); @@ -464,220 +300,193 @@ public class SecRuleEntityDecoderTest { @Test public final void testIsEtherTypeOfOneWithinTwo_oneEthTypeIPv4TwoEthTypeIPv4() { - NeutronSecurityRule one = createSecRuleWithEtherType(NeutronUtils.IPv4); - NeutronSecurityRule two = createSecRuleWithEtherType(NeutronUtils.IPv4); + SecurityRule one = secRuleBuilder.setEthertype(EthertypeV4.class).build(); + SecurityRule two = secRuleBuilder.setEthertype(EthertypeV4.class).build(); assertTrue(SecRuleEntityDecoder.isEtherTypeOfOneWithinTwo(one, two)); } @Test public final void testIsEtherTypeOfOneWithinTwo_oneEthTypeIPv4TwoEthTypeNull() { - NeutronSecurityRule one = createSecRuleWithEtherType(NeutronUtils.IPv4); - NeutronSecurityRule two = createSecRuleWithEtherType(null); + SecurityRule one = secRuleBuilder.setEthertype(EthertypeV4.class).build(); + SecurityRule two = secRuleBuilder.setEthertype(null).build(); assertTrue(SecRuleEntityDecoder.isEtherTypeOfOneWithinTwo(one, two)); } @Test public final void testIsEtherTypeOfOneWithinTwo_oneEthTypeNullTwoEthTypeNull() { - NeutronSecurityRule one = createSecRuleWithEtherType(null); - NeutronSecurityRule two = createSecRuleWithEtherType(null); + SecurityRule one = secRuleBuilder.setEthertype(null).build(); + SecurityRule two = secRuleBuilder.setEthertype(null).build(); assertTrue(SecRuleEntityDecoder.isEtherTypeOfOneWithinTwo(one, two)); } @Test public final void testIsEtherTypeOfOneWithinTwo_oneEthTypeIPv4TwoEthTypeIPv6() { - NeutronSecurityRule one = createSecRuleWithEtherType(NeutronUtils.IPv4); - NeutronSecurityRule two = createSecRuleWithEtherType(NeutronUtils.IPv6); + SecurityRule one = secRuleBuilder.setEthertype(EthertypeV4.class).build(); + SecurityRule two = secRuleBuilder.setEthertype(EthertypeV6.class).build(); assertFalse(SecRuleEntityDecoder.isEtherTypeOfOneWithinTwo(one, two)); } @Test public final void testIsEtherTypeOfOneWithinTwo_oneEthTypeNullTwoEthTypeIPv4() { - NeutronSecurityRule one = createSecRuleWithEtherType(null); - NeutronSecurityRule two = createSecRuleWithEtherType(NeutronUtils.IPv4); + SecurityRule one = secRuleBuilder.setEthertype(null).build(); + SecurityRule two = secRuleBuilder.setEthertype(EthertypeV4.class).build(); assertFalse(SecRuleEntityDecoder.isEtherTypeOfOneWithinTwo(one, two)); } - private final NeutronSecurityRule createSecRuleWithEtherType(String etherType) { - NeutronSecurityRule secRule = new NeutronSecurityRule(); - secRule.setSecurityRuleEthertype(etherType); - return secRule; - } - @Test public void testIsProtocolOfOneWithinTwo_oneProtocolTcpTwoProtocolTcp() { - NeutronSecurityRule one = createSecRuleWithProtocol(NeutronUtils.TCP); - NeutronSecurityRule two = createSecRuleWithProtocol(NeutronUtils.TCP); + SecurityRule one = secRuleBuilder.setProtocol(ProtocolTcp.class).build(); + SecurityRule two = secRuleBuilder.setProtocol(ProtocolTcp.class).build(); assertTrue(SecRuleEntityDecoder.isProtocolOfOneWithinTwo(one, two)); } @Test public void testIsProtocolOfOneWithinTwo_oneProtocolTcpTwoProtocolNull() { - NeutronSecurityRule one = createSecRuleWithProtocol(NeutronUtils.TCP); - NeutronSecurityRule two = createSecRuleWithProtocol(null); + SecurityRule one = secRuleBuilder.setProtocol(ProtocolTcp.class).build(); + SecurityRule two = secRuleBuilder.setProtocol(null).build(); assertTrue(SecRuleEntityDecoder.isProtocolOfOneWithinTwo(one, two)); } @Test public void testIsProtocolOfOneWithinTwo_oneProtocolNullTwoProtocolNull() { - NeutronSecurityRule one = createSecRuleWithProtocol(null); - NeutronSecurityRule two = createSecRuleWithProtocol(null); + SecurityRule one = secRuleBuilder.setProtocol(null).build(); + SecurityRule two = secRuleBuilder.setProtocol(null).build(); assertTrue(SecRuleEntityDecoder.isProtocolOfOneWithinTwo(one, two)); } @Test public void testIsProtocolOfOneWithinTwo_oneProtocolTcpTwoProtocolUdp() { - NeutronSecurityRule one = createSecRuleWithProtocol(NeutronUtils.TCP); - NeutronSecurityRule two = createSecRuleWithProtocol(NeutronUtils.UDP); + SecurityRule one = secRuleBuilder.setProtocol(ProtocolTcp.class).build(); + SecurityRule two = secRuleBuilder.setProtocol(ProtocolUdp.class).build(); assertFalse(SecRuleEntityDecoder.isProtocolOfOneWithinTwo(one, two)); } @Test public void testIsProtocolOfOneWithinTwo_oneProtocolNullTwoProtocolTcp() { - NeutronSecurityRule one = createSecRuleWithProtocol(null); - NeutronSecurityRule two = createSecRuleWithProtocol(NeutronUtils.TCP); + SecurityRule one = secRuleBuilder.setProtocol(null).build(); + SecurityRule two = secRuleBuilder.setProtocol(ProtocolTcp.class).build(); assertFalse(SecRuleEntityDecoder.isProtocolOfOneWithinTwo(one, two)); } - private NeutronSecurityRule createSecRuleWithProtocol(String protocol) { - NeutronSecurityRule secRule = new NeutronSecurityRule(); - secRule.setSecurityRuleProtocol(protocol); - return secRule; - } - @Test public final void testIsPortsOfOneWithinTwo_onePortMinGtTwoPortMinOnePortMaxLtTwoPortMax() { - NeutronSecurityRule one = createSecRuleWithMinMaxPort(6, 9); - NeutronSecurityRule two = createSecRuleWithMinMaxPort(5, 10); + SecurityRule one = createSecRuleWithMinMaxPort(6, 9); + SecurityRule two = createSecRuleWithMinMaxPort(5, 10); assertTrue(SecRuleEntityDecoder.isPortsOfOneWithinTwo(one, two)); } @Test public final void testIsPortsOfOneWithinTwo_onePortMinEqTwoPortMinOnePortMaxEqTwoPortMax() { - NeutronSecurityRule one = createSecRuleWithMinMaxPort(5, 10); - NeutronSecurityRule two = createSecRuleWithMinMaxPort(5, 10); + SecurityRule one = createSecRuleWithMinMaxPort(5, 10); + SecurityRule two = createSecRuleWithMinMaxPort(5, 10); assertTrue(SecRuleEntityDecoder.isPortsOfOneWithinTwo(one, two)); } @Test public final void testIsPortsOfOneWithinTwo_onePortMinTwoPortMinNullOnePortMaxTwoPortMaxNull() { - NeutronSecurityRule one = createSecRuleWithMinMaxPort(4, 9); - NeutronSecurityRule two = createSecRuleWithMinMaxPort(null, null); + SecurityRule one = createSecRuleWithMinMaxPort(4, 9); + SecurityRule two = createSecRuleWithMinMaxPort(null, null); assertTrue(SecRuleEntityDecoder.isPortsOfOneWithinTwo(one, two)); } @Test public final void testIsPortsOfOneWithinTwo_onePortMinNullTwoPortMinNullOnePortMaxNullTwoPortMaxNull() { - NeutronSecurityRule one = createSecRuleWithMinMaxPort(null, null); - NeutronSecurityRule two = createSecRuleWithMinMaxPort(null, null); + SecurityRule one = createSecRuleWithMinMaxPort(null, null); + SecurityRule two = createSecRuleWithMinMaxPort(null, null); assertTrue(SecRuleEntityDecoder.isPortsOfOneWithinTwo(one, two)); } @Test public final void testIsPortsOfOneWithinTwo_onePortMinNullTwoPortMinOnePortMaxNullTwoPortMax() { - NeutronSecurityRule one = createSecRuleWithMinMaxPort(null, null); - NeutronSecurityRule two = createSecRuleWithMinMaxPort(5, 10); + SecurityRule one = createSecRuleWithMinMaxPort(null, null); + SecurityRule two = createSecRuleWithMinMaxPort(5, 10); assertFalse(SecRuleEntityDecoder.isPortsOfOneWithinTwo(one, two)); } @Test public final void testIsPortsOfOneWithinTwo_onePortMinLtTwoPortMinOnePortMaxLtTwoPortMax() { - NeutronSecurityRule one = createSecRuleWithMinMaxPort(4, 9); - NeutronSecurityRule two = createSecRuleWithMinMaxPort(5, 10); + SecurityRule one = createSecRuleWithMinMaxPort(4, 9); + SecurityRule two = createSecRuleWithMinMaxPort(5, 10); assertFalse(SecRuleEntityDecoder.isPortsOfOneWithinTwo(one, two)); } @Test public final void testIsPortsOfOneWithinTwo_onePortMinGtTwoPortMinOnePortMaxGtTwoPortMax() { - NeutronSecurityRule one = createSecRuleWithMinMaxPort(6, 11); - NeutronSecurityRule two = createSecRuleWithMinMaxPort(5, 10); + SecurityRule one = createSecRuleWithMinMaxPort(6, 11); + SecurityRule two = createSecRuleWithMinMaxPort(5, 10); assertFalse(SecRuleEntityDecoder.isPortsOfOneWithinTwo(one, two)); } @Test public final void testIsPortsOfOneWithinTwo_onePortMinLtTwoPortMinOnePortMaxGtTwoPortMax() { - NeutronSecurityRule one = createSecRuleWithMinMaxPort(4, 11); - NeutronSecurityRule two = createSecRuleWithMinMaxPort(5, 10); + SecurityRule one = createSecRuleWithMinMaxPort(4, 11); + SecurityRule two = createSecRuleWithMinMaxPort(5, 10); assertFalse(SecRuleEntityDecoder.isPortsOfOneWithinTwo(one, two)); } - private NeutronSecurityRule createSecRuleWithMinMaxPort(Integer portMin, Integer portMax) { - NeutronSecurityRule secRule = new NeutronSecurityRule(); - secRule.setSecurityRulePortMin(portMin); - secRule.setSecurityRulePortMax(portMax); - return secRule; + private SecurityRule createSecRuleWithMinMaxPort(Integer portMin, Integer portMax) { + return secRuleBuilder.setPortRangeMin(portMin).setPortRangeMax(portMax).build(); } @Test public final void testGetEtherType_ethertypeIPv4() { - secRule.setSecurityRuleEthertype("IPv4"); - Assert.assertEquals(EtherTypeClassifierDefinition.IPv4_VALUE, SecRuleEntityDecoder.getEtherType(secRule)); + secRuleBuilder.setEthertype(EthertypeV4.class); + Assert.assertEquals(EtherTypeClassifierDefinition.IPv4_VALUE, SecRuleEntityDecoder.getEtherType(secRuleBuilder.build())); } @Test public final void testGetEtherType_ethertypeIPv6() { - secRule.setSecurityRuleEthertype("IPv6"); - Assert.assertEquals(EtherTypeClassifierDefinition.IPv6_VALUE, SecRuleEntityDecoder.getEtherType(secRule)); + secRuleBuilder.setEthertype(EthertypeV6.class); + Assert.assertEquals(EtherTypeClassifierDefinition.IPv6_VALUE, SecRuleEntityDecoder.getEtherType(secRuleBuilder.build())); } @Test public final void testGetEtherType_ethertypeNull() { - secRule.setSecurityRuleEthertype(null); - Assert.assertNull(SecRuleEntityDecoder.getEtherType(secRule)); - } - - @Test - public final void testGetEtherType_ethertypeEmptyString() { - secRule.setSecurityRuleEthertype(""); - Assert.assertNull(SecRuleEntityDecoder.getEtherType(secRule)); + secRuleBuilder.setEthertype(null); + Assert.assertNull(SecRuleEntityDecoder.getEtherType(secRuleBuilder.build())); } @Test public final void testGetEtherType_ethertypeUnknown() { - secRule.setSecurityRuleEthertype("foo"); + secRuleBuilder.setEthertype(UnknownEthertype.class); thrown.expect(IllegalArgumentException.class); - SecRuleEntityDecoder.getEtherType(secRule); + SecRuleEntityDecoder.getEtherType(secRuleBuilder.build()); + } + + private static class UnknownEthertype extends EthertypeBase { } @Test public final void testGetProtocol_protoTcp() { - secRule.setSecurityRuleProtocol("tcp"); - Assert.assertEquals(IpProtoClassifierDefinition.TCP_VALUE, SecRuleEntityDecoder.getProtocol(secRule)); + secRuleBuilder.setProtocol(ProtocolTcp.class); + Assert.assertEquals(IpProtoClassifierDefinition.TCP_VALUE, SecRuleEntityDecoder.getProtocol(secRuleBuilder.build())); } @Test public final void testGetProtocol_protoUdp() { - secRule.setSecurityRuleProtocol("udp"); - Assert.assertEquals(IpProtoClassifierDefinition.UDP_VALUE, SecRuleEntityDecoder.getProtocol(secRule)); + secRuleBuilder.setProtocol(ProtocolUdp.class); + Assert.assertEquals(IpProtoClassifierDefinition.UDP_VALUE, SecRuleEntityDecoder.getProtocol(secRuleBuilder.build())); } @Test public final void testGetProtocol_protoIcmp() { - secRule.setSecurityRuleProtocol("icmp"); - Assert.assertEquals(IpProtoClassifierDefinition.ICMP_VALUE, SecRuleEntityDecoder.getProtocol(secRule)); - } - - @Test - public final void testGetProtocol_numValue() { - secRule.setSecurityRuleProtocol("199"); - Assert.assertEquals(Long.valueOf(199) , SecRuleEntityDecoder.getProtocol(secRule)); + secRuleBuilder.setProtocol(ProtocolIcmp.class); + Assert.assertEquals(IpProtoClassifierDefinition.ICMP_VALUE, SecRuleEntityDecoder.getProtocol(secRuleBuilder.build())); } @Test public final void testGetProtocol_protoNull() { - secRule.setSecurityRuleProtocol(null); - Assert.assertNull(SecRuleEntityDecoder.getProtocol(secRule)); - } - - @Test - public final void testGetProtocol_protoEmptyString() { - secRule.setSecurityRuleProtocol(""); - Assert.assertNull(SecRuleEntityDecoder.getProtocol(secRule)); + secRuleBuilder.setProtocol(null); + Assert.assertNull(SecRuleEntityDecoder.getProtocol(secRuleBuilder.build())); } @Test public final void testGetProtocol_protoUnknown() { - secRule.setSecurityRuleProtocol("foo"); + secRuleBuilder.setProtocol(UnknownProtocol.class); thrown.expect(IllegalArgumentException.class); - SecRuleEntityDecoder.getProtocol(secRule); + SecRuleEntityDecoder.getProtocol(secRuleBuilder.build()); + } + + private static class UnknownProtocol extends ProtocolBase { } } diff --git a/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SecRuleNameDecoderTest.java b/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SecRuleNameDecoderTest.java index 0d9fe5b0a..482d283af 100644 --- a/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SecRuleNameDecoderTest.java +++ b/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SecRuleNameDecoderTest.java @@ -8,41 +8,46 @@ import org.opendaylight.groupbasedpolicy.api.sf.EtherTypeClassifierDefinition; import org.opendaylight.groupbasedpolicy.api.sf.IpProtoClassifierDefinition; import org.opendaylight.groupbasedpolicy.api.sf.L4ClassifierDefinition; import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils; -import org.opendaylight.groupbasedpolicy.neutron.mapper.util.NeutronUtils; -import org.opendaylight.neutron.spi.NeutronSecurityRule; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Prefix; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ClassifierName; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ClauseName; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.HasDirection.Direction; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionIngress; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeV4; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolTcp; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRuleBuilder; public class SecRuleNameDecoderTest { - private NeutronSecurityRule secRule; + private SecurityRuleBuilder secRule; @Before public void setUp() throws Exception { - secRule = new NeutronSecurityRule(); + secRule = new SecurityRuleBuilder().setId(new Uuid("01234567-abcd-ef01-0123-0123456789ab")); } @Test public final void testGetClassifierRefName() { - secRule.setSecurityRuleDirection(NeutronUtils.INGRESS); - secRule.setSecurityRuleEthertype(NeutronUtils.IPv4); - ClassifierName clsfInstanceName = SecRuleNameDecoder.getClassifierInstanceName(secRule); + secRule.setDirection(DirectionIngress.class); + secRule.setEthertype(EthertypeV4.class); + ClassifierName clsfInstanceName = SecRuleNameDecoder.getClassifierInstanceName(secRule.build()); String crName = new StringBuilder().append(Direction.In.name()) .append(MappingUtils.NAME_DOUBLE_DELIMETER) .append(clsfInstanceName.getValue()) .toString(); ClassifierName expectedClsfRefName = new ClassifierName(crName); - assertEquals(expectedClsfRefName, SecRuleNameDecoder.getClassifierRefName(secRule)); + assertEquals(expectedClsfRefName, SecRuleNameDecoder.getClassifierRefName(secRule.build())); } @Test public final void testGetClassifierInstanceName() { - secRule.setSecurityRuleDirection(NeutronUtils.INGRESS); - secRule.setSecurityRuleEthertype(NeutronUtils.IPv4); - secRule.setSecurityRuleProtocol(NeutronUtils.TCP); - secRule.setSecurityRulePortMin(8010); - secRule.setSecurityRulePortMax(8020); + secRule.setDirection(DirectionIngress.class); + secRule.setEthertype(EthertypeV4.class); + secRule.setProtocol(ProtocolTcp.class); + secRule.setPortRangeMin(8010); + secRule.setPortRangeMax(8020); StringBuilder frmtBuilder = new StringBuilder(); frmtBuilder.append(L4ClassifierDefinition.DEFINITION.getName().getValue()) .append(MappingUtils.NAME_DELIMETER) @@ -61,27 +66,27 @@ public class SecRuleNameDecoderTest { .append(EtherTypeClassifierDefinition.DEFINITION.getName().getValue()) .append(MappingUtils.NAME_VALUE_DELIMETER) .append("%s"); - String frmtClsfName = String.format(frmtBuilder.toString(), 8010, 8020, secRule.getSecurityRuleProtocol(), - secRule.getSecurityRuleEthertype()); + String frmtClsfName = String.format(frmtBuilder.toString(), 8010, 8020, secRule.getProtocol().getSimpleName(), + secRule.getEthertype().getSimpleName()); ClassifierName expectedClsfInstanceName = new ClassifierName(frmtClsfName); - assertEquals(expectedClsfInstanceName, SecRuleNameDecoder.getClassifierInstanceName(secRule)); + assertEquals(expectedClsfInstanceName, SecRuleNameDecoder.getClassifierInstanceName(secRule.build())); } @Test public final void testGetClauseName_noRemoteIpPrefix() { - secRule.setSecurityRuleDirection(NeutronUtils.INGRESS); - secRule.setSecurityRuleEthertype(NeutronUtils.IPv4); - ClauseName expectedClauseName = new ClauseName(SecRuleNameDecoder.getSubjectName(secRule)); - assertEquals(expectedClauseName, SecRuleNameDecoder.getClauseName(secRule)); + secRule.setDirection(DirectionIngress.class); + secRule.setEthertype(EthertypeV4.class); + ClauseName expectedClauseName = new ClauseName(SecRuleNameDecoder.getSubjectName(secRule.build())); + assertEquals(expectedClauseName, SecRuleNameDecoder.getClauseName(secRule.build())); } @Test public final void testGetClauseName_remoteIpPrefix() { - secRule.setSecurityRuleDirection(NeutronUtils.INGRESS); - secRule.setSecurityRuleEthertype(NeutronUtils.IPv4); - secRule.setSecurityRuleRemoteIpPrefix("10.0.0.0/8"); - ClauseName expectedClauseName = new ClauseName(SecRuleNameDecoder.getSubjectName(secRule).getValue() + secRule.setDirection(DirectionIngress.class); + secRule.setEthertype(EthertypeV4.class); + secRule.setRemoteIpPrefix(new IpPrefix(new Ipv4Prefix("10.0.0.0/8"))); + ClauseName expectedClauseName = new ClauseName(SecRuleNameDecoder.getSubjectName(secRule.build()).getValue() + MappingUtils.NAME_DOUBLE_DELIMETER + "10.0.0.0_8"); - assertEquals(expectedClauseName, SecRuleNameDecoder.getClauseName(secRule)); + assertEquals(expectedClauseName, SecRuleNameDecoder.getClauseName(secRule.build())); } } diff --git a/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SingleClassifierRuleTest.java b/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SingleClassifierRuleTest.java index b5f016a25..17e0f96ca 100644 --- a/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SingleClassifierRuleTest.java +++ b/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SingleClassifierRuleTest.java @@ -3,7 +3,6 @@ package org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.rule; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import java.lang.reflect.Method; import java.util.Arrays; import org.junit.Test; @@ -13,8 +12,6 @@ import org.opendaylight.groupbasedpolicy.api.sf.L4ClassifierDefinition; import org.opendaylight.groupbasedpolicy.neutron.mapper.test.NeutronEntityFactory; import org.opendaylight.groupbasedpolicy.neutron.mapper.test.PolicyAssert; import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils; -import org.opendaylight.groupbasedpolicy.neutron.mapper.util.NeutronUtils; -import org.opendaylight.neutron.spi.NeutronSecurityRule; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ClassifierDefinitionId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ParameterName; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.change.action.of.security.group.rules.input.action.ActionChoice; @@ -28,6 +25,10 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.contract.subject.Rule; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.subject.feature.instances.ClassifierInstance; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.subject.feature.instances.ClassifierInstanceBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionIngress; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeV4; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolTcp; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRule; public class SingleClassifierRuleTest { @@ -37,9 +38,9 @@ public class SingleClassifierRuleTest { @Test public void testConstructorAndGetters() { - NeutronSecurityRule secRule = NeutronEntityFactory.securityRuleWithoutGroupIds( - "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", NeutronUtils.IPv4, - NeutronUtils.INGRESS, NeutronUtils.TCP, 8010, 8020); + SecurityRule secRule = NeutronEntityFactory.securityRuleWithoutGroupIds( + "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", EthertypeV4.class, + DirectionIngress.class, ProtocolTcp.class, 8010, 8020); final int ruleOrder = 1; singleClsfRule = new SingleClassifierRule(secRule, ruleOrder, MappingUtils.ALLOW_ACTION_CHOICE); diff --git a/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SingleRuleContractTest.java b/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SingleRuleContractTest.java index c3c513da6..fca2c195a 100644 --- a/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SingleRuleContractTest.java +++ b/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/mapping/rule/SingleRuleContractTest.java @@ -7,8 +7,6 @@ import org.junit.Test; import org.opendaylight.groupbasedpolicy.neutron.mapper.test.NeutronEntityFactory; import org.opendaylight.groupbasedpolicy.neutron.mapper.test.PolicyAssert; import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils; -import org.opendaylight.groupbasedpolicy.neutron.mapper.util.NeutronUtils; -import org.opendaylight.neutron.spi.NeutronSecurityRule; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.Description; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.has.classifier.refs.ClassifierRef; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.Contract; @@ -16,14 +14,18 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.contract.Subject; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.contract.subject.Rule; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.subject.feature.instances.ClassifierInstance; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionIngress; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeV4; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolTcp; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRule; public class SingleRuleContractTest { @Test public void testConstructorAndGetters() { - NeutronSecurityRule secRule = NeutronEntityFactory.securityRuleWithoutGroupIds( - "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", NeutronUtils.IPv4, - NeutronUtils.INGRESS, NeutronUtils.TCP, 8010, 8020); + SecurityRule secRule = NeutronEntityFactory.securityRuleWithoutGroupIds( + "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", EthertypeV4.class, + DirectionIngress.class, ProtocolTcp.class, 8010, 8020); int subjectAndRuleOrder = 1; SingleRuleContract singleRuleContract = new SingleRuleContract(secRule, subjectAndRuleOrder, new Description( "contractDescription"), MappingUtils.ALLOW_ACTION_CHOICE); diff --git a/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/test/NeutronEntityFactory.java b/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/test/NeutronEntityFactory.java index fc0f7356f..b4f3392b6 100644 --- a/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/test/NeutronEntityFactory.java +++ b/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/test/NeutronEntityFactory.java @@ -1,10 +1,15 @@ package org.opendaylight.groupbasedpolicy.neutron.mapper.test; -import java.util.ArrayList; -import java.util.List; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionBase; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeBase; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolBase; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.security.groups.SecurityGroup; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.security.groups.SecurityGroupBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRule; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRuleBuilder; -import org.opendaylight.neutron.spi.NeutronSecurityGroup; -import org.opendaylight.neutron.spi.NeutronSecurityRule; +import com.google.common.base.Strings; public final class NeutronEntityFactory { @@ -12,62 +17,38 @@ public final class NeutronEntityFactory { throw new UnsupportedOperationException("Cannot create an instance"); } - public static NeutronSecurityGroup securityGroup(String id, String tenantId) { - NeutronSecurityGroup secGrp = new NeutronSecurityGroup(); - secGrp.setSecurityGroupUUID(id); - secGrp.setSecurityGroupTenantID(tenantId); - secGrp.setSecurityRules(new ArrayList()); - return secGrp; + public static SecurityGroup securityGroup(String id, String tenantId) { + return new SecurityGroupBuilder().setUuid(new Uuid(id)).setTenantId(new Uuid(tenantId)).build(); } - public static NeutronSecurityGroup securityGroupWithName(String id, String tenantId, String name) { - NeutronSecurityGroup secGrp = new NeutronSecurityGroup(); - secGrp.setSecurityGroupUUID(id); - secGrp.setSecurityGroupTenantID(tenantId); - secGrp.setSecurityGroupName(name); - return secGrp; + public static SecurityGroup securityGroupWithName(String id, String tenantId, String name) { + return new SecurityGroupBuilder().setUuid(new Uuid(id)).setTenantId(new Uuid(tenantId)).setName(name).build(); } - public static NeutronSecurityGroup securityGroup(String id, String tenantId, List secRules) { - NeutronSecurityGroup secGrp = new NeutronSecurityGroup(); - secGrp.setSecurityGroupUUID(id); - secGrp.setSecurityGroupTenantID(tenantId); - secGrp.setSecurityRules(secRules); - return secGrp; + public static SecurityRule securityRuleWithoutGroupIds(String id, String tenant, Class etherType, + Class direction, Class protocol, int portMin, int portMax) { + SecurityRuleBuilder secRule = new SecurityRuleBuilder(); + secRule.setId(new Uuid(id)); + secRule.setTenantId(new Uuid(tenant)); + secRule.setEthertype(etherType); + secRule.setDirection(direction); + secRule.setProtocol(protocol); + secRule.setPortRangeMin(portMin); + secRule.setPortRangeMax(portMax); + return secRule.build(); } - public static NeutronSecurityRule securityRuleWithGroupIds(String id, String tenant, String ownerGroupId, + public static SecurityRule securityRuleWithEtherType(String id, String tenant, + Class etherType, Class direction, String ownerGroupId, String remoteGroupId) { - NeutronSecurityRule secRule = new NeutronSecurityRule(); - secRule.setSecurityRuleUUID(id); - secRule.setSecurityRuleTenantID(tenant); - secRule.setSecurityRuleGroupID(ownerGroupId); - secRule.setSecurityRemoteGroupID(remoteGroupId); - return secRule; - } - - public static NeutronSecurityRule securityRuleWithoutGroupIds(String id, String tenant, String etherType, - String direction, String protocol, int portMin, int portMax) { - NeutronSecurityRule secRule = new NeutronSecurityRule(); - secRule.setSecurityRuleUUID(id); - secRule.setSecurityRuleTenantID(tenant); - secRule.setSecurityRuleEthertype(etherType); - secRule.setSecurityRuleDirection(direction); - secRule.setSecurityRuleProtocol(protocol); - secRule.setSecurityRulePortMin(portMin); - secRule.setSecurityRulePortMax(portMax); - return secRule; - } - - public static NeutronSecurityRule securityRuleWithEtherType(String id, String tenant, String etherType, - String direction, String ownerGroupId, String remoteGroupId) { - NeutronSecurityRule secRule = new NeutronSecurityRule(); - secRule.setSecurityRuleUUID(id); - secRule.setSecurityRuleTenantID(tenant); - secRule.setSecurityRuleEthertype(etherType); - secRule.setSecurityRuleDirection(direction); - secRule.setSecurityRuleGroupID(ownerGroupId); - secRule.setSecurityRemoteGroupID(remoteGroupId); - return secRule; + SecurityRuleBuilder securityRuleBuilder = new SecurityRuleBuilder().setId(new Uuid(id)) + .setTenantId(new Uuid(tenant)) + .setEthertype(etherType) + .setDirection(direction) + .setSecurityGroupId(new Uuid(ownerGroupId)); + if (!Strings.isNullOrEmpty(remoteGroupId)) { + securityRuleBuilder.setRemoteGroupId(new Uuid(remoteGroupId)); + } + return securityRuleBuilder.build(); } } diff --git a/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/test/PolicyAssert.java b/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/test/PolicyAssert.java index 6b8752eb9..8cece9619 100644 --- a/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/test/PolicyAssert.java +++ b/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/test/PolicyAssert.java @@ -14,13 +14,10 @@ import org.opendaylight.controller.md.sal.binding.api.DataBroker; import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.rule.SecRuleEntityDecoder; import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.rule.SecRuleNameDecoder; import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils; -import org.opendaylight.groupbasedpolicy.neutron.mapper.util.Utils; -import org.opendaylight.neutron.spi.NeutronSecurityRule; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ActionName; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ClassifierName; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ContractId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.Description; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.SubjectName; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.has.action.refs.ActionRef; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.has.classifier.refs.ClassifierRef; @@ -36,10 +33,10 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.endpoint.group.ProviderNamedSelector; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.subject.feature.instances.ActionInstance; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.subject.feature.instances.ClassifierInstance; +import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRule; import com.google.common.base.Optional; import com.google.common.base.Preconditions; -import com.google.common.base.Strings; public final class PolicyAssert { @@ -88,19 +85,18 @@ public final class PolicyAssert { } } - public static void assertContractWithEic(Contract contract, NeutronSecurityRule secRule) { - assertEquals(new ContractId(secRule.getSecurityRuleUUID()), contract.getId()); + public static void assertContractWithEic(Contract contract, SecurityRule secRule) { + assertEquals(new ContractId(secRule.getId().getValue()), contract.getId()); assertNull(contract.getQuality()); assertNull(contract.getTarget()); assertOneClauseWithEicWithOneSubject(contract, secRule); PolicyAssert.assertOneSubjectWithOneRule(contract, secRule); } - private static void assertOneClauseWithEicWithOneSubject(Contract contract, NeutronSecurityRule secRule) { + private static void assertOneClauseWithEicWithOneSubject(Contract contract, SecurityRule secRule) { Clause clause = assertOneItem(contract.getClause()); assertNull(clause.getAnyMatchers()); - Preconditions.checkArgument(!Strings.isNullOrEmpty(secRule.getSecurityRuleRemoteIpPrefix())); - IpPrefix expectedIpPrefix = Utils.createIpPrefix(secRule.getSecurityRuleRemoteIpPrefix()); + IpPrefix expectedIpPrefix = secRule.getRemoteIpPrefix(); assertNotNull(clause.getConsumerMatchers()); IpPrefix ipPrefix = clause.getConsumerMatchers() .getEndpointIdentificationConstraints() @@ -113,31 +109,24 @@ public final class PolicyAssert { assertEquals(SecRuleNameDecoder.getSubjectName(secRule), subjectRef); } - public static void assertContract(Contract contract, NeutronSecurityRule secRule) { - assertEquals(new ContractId(secRule.getSecurityRuleUUID()), contract.getId()); + public static void assertContract(Contract contract, SecurityRule secRule) { + assertEquals(new ContractId(secRule.getId().getValue()), contract.getId()); assertNull(contract.getQuality()); assertNull(contract.getTarget()); assertOneClauseWithOneSubject(contract, secRule); assertOneSubjectWithOneRule(contract, secRule); } - private static void assertOneClauseWithOneSubject(Contract contract, NeutronSecurityRule secRule) { + private static void assertOneClauseWithOneSubject(Contract contract, SecurityRule secRule) { Clause clause = assertOneItem(contract.getClause()); assertClauseWithOneSubject(clause, secRule); } - private static void assertOneSubjectWithOneRule(Contract contract, NeutronSecurityRule secRule) { + private static void assertOneSubjectWithOneRule(Contract contract, SecurityRule secRule) { Subject subject = assertOneItem(contract.getSubject()); assertSubjectWithOneRule(subject, secRule); } - public static void assertContract(Contract contract, NeutronSecurityRule secRule, Description contractDescription) { - assertContract(contract, secRule); - assertEquals(contractDescription, contract.getDescription()); - } - - // asserts for endpoint group - public static void assertEndpointGroupExists(DataBroker dataBroker, String tenantId, String endpointGroupId) throws Exception { Optional epg = ConfigDataStoreReader.readEndpointGroup(dataBroker, tenantId, endpointGroupId); @@ -222,11 +211,11 @@ public final class PolicyAssert { // asserts for classifier - public static void assertClassifierInstanceExists(DataBroker dataBroker, NeutronSecurityRule secRule) + public static void assertClassifierInstanceExists(DataBroker dataBroker, SecurityRule secRule) throws Exception { ClassifierInstance clsfInstance = SecRuleEntityDecoder.getClassifierInstance(secRule); Optional readClsfInstance = ConfigDataStoreReader.readClassifierInstance(dataBroker, - secRule.getSecurityRuleTenantID(), clsfInstance.getName()); + secRule.getTenantId().getValue(), clsfInstance.getName()); assertTrue(readClsfInstance.isPresent()); } @@ -237,11 +226,11 @@ public final class PolicyAssert { assertTrue(classifierInstance.isPresent()); } - public static void assertClassifierInstanceNotExists(DataBroker dataBroker, NeutronSecurityRule secRule) + public static void assertClassifierInstanceNotExists(DataBroker dataBroker, SecurityRule secRule) throws Exception { ClassifierInstance clsfInstance = SecRuleEntityDecoder.getClassifierInstance(secRule); Optional readClsfInstance = ConfigDataStoreReader.readClassifierInstance(dataBroker, - secRule.getSecurityRuleTenantID(), clsfInstance.getName()); + secRule.getTenantId().getValue(), clsfInstance.getName()); assertFalse(readClsfInstance.isPresent()); } @@ -263,7 +252,7 @@ public final class PolicyAssert { // asserts for clause - public static void assertClauseWithOneSubject(Clause clause, NeutronSecurityRule secRule) { + public static void assertClauseWithOneSubject(Clause clause, SecurityRule secRule) { assertNull(clause.getAnyMatchers()); assertNull(clause.getConsumerMatchers()); assertNull(clause.getProviderMatchers()); @@ -278,7 +267,7 @@ public final class PolicyAssert { // asserts for subject - public static void assertSubjectWithOneRule(Subject subject, NeutronSecurityRule secRule) { + public static void assertSubjectWithOneRule(Subject subject, SecurityRule secRule) { assertEquals(SecRuleNameDecoder.getSubjectName(secRule), subject.getName()); Rule rule = assertOneItem(subject.getRule()); assertRule(rule, secRule); @@ -286,7 +275,7 @@ public final class PolicyAssert { // asserts for rule - public static void assertRule(Rule rule, NeutronSecurityRule secRule) { + public static void assertRule(Rule rule, SecurityRule secRule) { assertEquals(SecRuleNameDecoder.getRuleName(secRule), rule.getName()); ActionRef actionRef = assertOneItem(rule.getActionRef()); assertEquals(MappingUtils.ACTION_ALLOW.getName(), actionRef.getName()); @@ -296,7 +285,7 @@ public final class PolicyAssert { assertEquals(SecRuleEntityDecoder.getDirection(secRule), classifierRef.getDirection()); } - public static void assertRule(Rule rule, NeutronSecurityRule secRule, int order) { + public static void assertRule(Rule rule, SecurityRule secRule, int order) { assertRule(rule, secRule); assertEquals(order, rule.getOrder().intValue()); } diff --git a/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/MappingUtilsTest.java b/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/MappingUtilsTest.java deleted file mode 100644 index 25633f1c3..000000000 --- a/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/MappingUtilsTest.java +++ /dev/null @@ -1,221 +0,0 @@ -package org.opendaylight.groupbasedpolicy.neutron.mapper.util; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.opendaylight.controller.md.sal.binding.api.DataBroker; -import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction; -import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; -import org.opendaylight.groupbasedpolicy.neutron.mapper.test.GbpDataBrokerTest; -import org.opendaylight.groupbasedpolicy.util.IidFactory; -import org.opendaylight.neutron.spi.Neutron_IPs; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2BridgeDomainId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2FloodDomainId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L3ContextId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.Name; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2BridgeDomain; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2BridgeDomainBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2BridgeDomainKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2FloodDomain; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2FloodDomainBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2FloodDomainKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L3Context; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L3ContextBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L3ContextKey; - -public class MappingUtilsTest extends GbpDataBrokerTest { - - private final TenantId tenantId = new TenantId("00000000-0000-0000-0000-000000000001"); - private final L2FloodDomainId l2FloodDomainId = new L2FloodDomainId("00000000-0000-0000-0000-000000000002"); - private final L2BridgeDomainId l2BridgeDomainId = new L2BridgeDomainId("00000000-0000-0000-0000-000000000003"); - private final L3ContextId l3ContextId = new L3ContextId("00000000-0000-0000-0000-000000000004"); - private final String[] ips = {"170.0.0.1", "170.0.0.2", "170.0.0.3"}; - private L2FloodDomainBuilder l2FloodDomainBuilder; - private List emptyList, singleIp, multiIp; - private L2BridgeDomainBuilder l2BridgeDomainBuilder; - private L3ContextBuilder l3ContextBuilder; - - @Before - public void init() { - l2FloodDomainBuilder = new L2FloodDomainBuilder(); - l2FloodDomainBuilder.setName(new Name("l2fdn")) - .setKey(new L2FloodDomainKey(l2FloodDomainId)); - l2BridgeDomainBuilder = new L2BridgeDomainBuilder(); - l2BridgeDomainBuilder.setName(new Name("l2bdn")) - .setKey(new L2BridgeDomainKey(l2BridgeDomainId)); - l3ContextBuilder = new L3ContextBuilder(); - l3ContextBuilder.setName(new Name("l3cn")) - .setKey(new L3ContextKey(l3ContextId)); - Neutron_IPs neutronIp1 = new Neutron_IPs(); - Neutron_IPs neutronIp2 = new Neutron_IPs(); - Neutron_IPs neutronIp3 = new Neutron_IPs(); - neutronIp1.setIpAddress(ips[0]); - neutronIp2.setIpAddress(ips[1]); - neutronIp3.setIpAddress(ips[2]); - emptyList = new ArrayList<>(); - singleIp = new ArrayList<>(); - singleIp.add(neutronIp1); - multiIp = new ArrayList<>(); - multiIp.add(neutronIp1); - multiIp.add(neutronIp2); - multiIp.add(neutronIp3); - } - - @Test - public void testCreateForwardingContext1() { - //case #1 - L2FloodDomain is not present in DS - DataBroker dataBroker = getDataBroker(); - ReadWriteTransaction rwTx = dataBroker.newReadWriteTransaction(); - MappingUtils.ForwardingCtx - forwardingCtx = - MappingUtils.createForwardingContext(tenantId, l2FloodDomainBuilder.build().getId(), rwTx); - assertNotNull(forwardingCtx); - assertNull(forwardingCtx.getL2FloodDomain()); - assertNull(forwardingCtx.getL2BridgeDomain()); - assertNull(forwardingCtx.getL3Context()); - } - - @Test - public void testCreateForwardingContext2() { - //case #2 - L2FloodDomain is present in DS, but its parent is null - DataBroker dataBroker = getDataBroker(); - ReadWriteTransaction rwTx = dataBroker.newReadWriteTransaction(); - l2FloodDomainBuilder.setParent(null); - L2FloodDomain l2FloodDomain = l2FloodDomainBuilder.build(); - writeL2FloodDomain(tenantId, l2FloodDomain, rwTx); - MappingUtils.ForwardingCtx - forwardingCtx = - MappingUtils.createForwardingContext(tenantId, l2FloodDomainBuilder.build().getId(), rwTx); - assertNotNull(forwardingCtx); - assertTrue(forwardingCtx.getL2FloodDomain().equals(l2FloodDomain)); - assertNull(forwardingCtx.getL2BridgeDomain()); - assertNull(forwardingCtx.getL3Context()); - } - - @Test - public void testCreateForwardingContext3() { - //case #3 - L2FloodDomain is present in DS with not-null parent, but L2BridgeDomain is not present in DS - DataBroker dataBroker = getDataBroker(); - ReadWriteTransaction rwTx = dataBroker.newReadWriteTransaction(); - l2FloodDomainBuilder.setParent(l2BridgeDomainBuilder.build().getId()); - L2FloodDomain l2FloodDomain = l2FloodDomainBuilder.build(); - writeL2FloodDomain(tenantId, l2FloodDomain, rwTx); - MappingUtils.ForwardingCtx - forwardingCtx = - MappingUtils.createForwardingContext(tenantId, l2FloodDomainBuilder.build().getId(), rwTx); - assertNotNull(forwardingCtx); - assertTrue(forwardingCtx.getL2FloodDomain().equals(l2FloodDomain)); - assertNull(forwardingCtx.getL2BridgeDomain()); - assertNull(forwardingCtx.getL3Context()); - } - - @Test - public void testCreateForwardingContext4() { - //case #4 - L2BridgeDomain is also present in DS but with null parent - DataBroker dataBroker = getDataBroker(); - ReadWriteTransaction rwTx = dataBroker.newReadWriteTransaction(); - l2BridgeDomainBuilder.setParent(null); - l2FloodDomainBuilder.setParent(l2BridgeDomainBuilder.build().getId()); - L2FloodDomain l2FloodDomain = l2FloodDomainBuilder.build(); - L2BridgeDomain l2BridgeDomain = l2BridgeDomainBuilder.build(); - writeL2FloodDomain(tenantId, l2FloodDomain, rwTx); - writeL2BridgeDomain(tenantId, l2BridgeDomain, rwTx); - MappingUtils.ForwardingCtx - forwardingCtx = - MappingUtils.createForwardingContext(tenantId, l2FloodDomainBuilder.build().getId(), rwTx); - assertNotNull(forwardingCtx); - assertTrue(forwardingCtx.getL2FloodDomain().equals(l2FloodDomain)); - assertTrue(forwardingCtx.getL2BridgeDomain().equals(l2BridgeDomain)); - assertNull(forwardingCtx.getL3Context()); - } - - @Test - public void testCreateForwardingContext5() { - //case #5 - L2BridgeDomain is also present in DS with not-null parent, but L3Context is not present in DS - DataBroker dataBroker = getDataBroker(); - ReadWriteTransaction rwTx = dataBroker.newReadWriteTransaction(); - l2BridgeDomainBuilder.setParent(l3ContextBuilder.build().getId()); - l2FloodDomainBuilder.setParent(l2BridgeDomainBuilder.build().getId()); - L2FloodDomain l2FloodDomain = l2FloodDomainBuilder.build(); - L2BridgeDomain l2BridgeDomain = l2BridgeDomainBuilder.build(); - writeL2FloodDomain(tenantId, l2FloodDomain, rwTx); - writeL2BridgeDomain(tenantId, l2BridgeDomain, rwTx); - MappingUtils.ForwardingCtx - forwardingCtx = - MappingUtils.createForwardingContext(tenantId, l2FloodDomainBuilder.build().getId(), rwTx); - assertNotNull(forwardingCtx); - assertTrue(forwardingCtx.getL2FloodDomain().equals(l2FloodDomain)); - assertTrue(forwardingCtx.getL2BridgeDomain().equals(l2BridgeDomain)); - assertNull(forwardingCtx.getL3Context()); - } - - @Test - public void testCreateForwardingContext6() { - //case #6 - L3Context present in DS - DataBroker dataBroker = getDataBroker(); - ReadWriteTransaction rwTx = dataBroker.newReadWriteTransaction(); - l2BridgeDomainBuilder.setParent(l3ContextBuilder.build().getId()); - l2FloodDomainBuilder.setParent(l2BridgeDomainBuilder.build().getId()); - L2FloodDomain l2FloodDomain = l2FloodDomainBuilder.build(); - L2BridgeDomain l2BridgeDomain = l2BridgeDomainBuilder.build(); - L3Context l3Context = l3ContextBuilder.build(); - writeL2FloodDomain(tenantId, l2FloodDomain, rwTx); - writeL2BridgeDomain(tenantId, l2BridgeDomain, rwTx); - writeL3Context(tenantId, l3Context, rwTx); - MappingUtils.ForwardingCtx - forwardingCtx = - MappingUtils.createForwardingContext(tenantId, l2FloodDomainBuilder.build().getId(), rwTx); - assertNotNull(forwardingCtx); - assertTrue(forwardingCtx.getL2FloodDomain().equals(l2FloodDomain)); - assertTrue(forwardingCtx.getL2BridgeDomain().equals(l2BridgeDomain)); - assertTrue(forwardingCtx.getL3Context().equals(l3Context)); - } - - @Test - public void testGetFirstIpNullIp() { - Neutron_IPs result = MappingUtils.getFirstIp(emptyList); - assertNull(result); - } - - @Test - public void testGetFirstIpOneIp() { - Neutron_IPs result = MappingUtils.getFirstIp(singleIp); - assertNotNull(result); - assertEquals(result.getIpAddress(), ips[0]); - } - - @Test - public void testGetFirstIpMoreIps() { - Neutron_IPs result = MappingUtils.getFirstIp(multiIp); - assertNotNull(result); - assertEquals(result.getIpAddress(), ips[0]); - } - - private void writeL2FloodDomain(TenantId tenantId, L2FloodDomain l2Fd, ReadWriteTransaction rwTx) { - checkNotNull(l2Fd); - L2FloodDomainId l2FdId = l2Fd.getId(); - rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.l2FloodDomainIid(tenantId, l2FdId), l2Fd); - } - - private void writeL2BridgeDomain(TenantId tenantId, L2BridgeDomain l2Bd, ReadWriteTransaction rwTx) { - checkNotNull(l2Bd); - L2BridgeDomainId l2BdId = l2Bd.getId(); - rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.l2BridgeDomainIid(tenantId, l2BdId), l2Bd); - } - - private void writeL3Context(TenantId tenantId, L3Context l3Ct, ReadWriteTransaction rwTx) { - checkNotNull(l3Ct); - L3ContextId l3CtId = l3Ct.getId(); - rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.l3ContextIid(tenantId, l3CtId), l3Ct); - } - -} diff --git a/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/NeutronMapperIidFactoryTest.java b/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/NeutronMapperIidFactoryTest.java deleted file mode 100644 index 24b9b1efc..000000000 --- a/neutron-mapper/src/test/java/org/opendaylight/groupbasedpolicy/neutron/mapper/util/NeutronMapperIidFactoryTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.opendaylight.groupbasedpolicy.neutron.mapper.util; - -import static junit.framework.Assert.assertEquals; -import static junit.framework.Assert.assertTrue; -import static org.junit.Assert.assertNotNull; - -import java.util.Iterator; - -import org.junit.Test; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.UniqueId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.mapper.rev150223.Mappings; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.mapper.rev150223.mappings.NetworkMappings; -import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.mapper.rev150223.mappings.network.mappings.NetworkMapping; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; - -public class NeutronMapperIidFactoryTest { - - @Test - public void instantiate() { - NeutronMapperIidFactory iidFactory = new NeutronMapperIidFactory(); - assertNotNull(iidFactory); - } - - @Test - public void testEndpointByPortIid() { - String dummyId = "00000000-0000-0000-0000-000000000001"; - InstanceIdentifier iid = NeutronMapperIidFactory.networkMappingIid(new UniqueId(dummyId)); - assertNotNull(iid); - assertEquals(iid.getTargetType(), NetworkMapping.class); - assertTrue(iid.toString().contains(dummyId)); - - Iterator pathArguments = iid.getPathArguments().iterator(); - - assertEquals(pathArguments.next().toString(), Mappings.class.getName()); - assertEquals(pathArguments.next().toString(), NetworkMappings.class.getName()); - assertEquals(pathArguments.next().getType().toString(), NetworkMapping.class.toString()); - } -} diff --git a/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/flow/GroupTable.java b/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/flow/GroupTable.java index fdb53bf24..a26e14ee8 100644 --- a/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/flow/GroupTable.java +++ b/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/flow/GroupTable.java @@ -10,6 +10,7 @@ package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Optional; + import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction; import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; import org.opendaylight.groupbasedpolicy.dto.EgKey; @@ -24,10 +25,13 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.Fl import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.BucketId; import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupId; import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.buckets.BucketBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2FloodDomainId; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.SubnetId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.Endpoint; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.ofoverlay.rev140528.OfOverlayContext; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.ofoverlay.rev140528.Segmentation; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2FloodDomain; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.Subnet; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.overlay.rev150105.TunnelTypeVxlan; @@ -137,8 +141,9 @@ public class GroupTable extends OfTable { for (Endpoint extEp : ctx.getEndpointManager().getExtEpsNoLocForGroup(endpointGroupKey)) { if (extEp.getNetworkContainment() != null && extEp.getNetworkContainment().equals(endpoint.getNetworkContainment())) { + Subnet subnet = ctx.getTenant(extEp.getTenant()).resolveSubnet(new SubnetId(extEp.getNetworkContainment())); L2FloodDomain l2Fd = ctx.getTenant(extEp.getTenant()) - .resolveL2FloodDomain(extEp.getNetworkContainment()); + .resolveL2FloodDomain(new L2FloodDomainId(subnet.getParent().getValue())); if (l2Fd != null) { Segmentation segmentation = l2Fd.getAugmentation(Segmentation.class); // external endpoints do not have location augmentation diff --git a/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/flow/OrdinalFactory.java b/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/flow/OrdinalFactory.java index 2658b6850..f7101e893 100755 --- a/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/flow/OrdinalFactory.java +++ b/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/flow/OrdinalFactory.java @@ -15,6 +15,7 @@ import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import com.google.common.annotations.VisibleForTesting; + import org.opendaylight.groupbasedpolicy.dto.ConditionGroup; import org.opendaylight.groupbasedpolicy.dto.EgKey; import org.opendaylight.groupbasedpolicy.dto.EpKey; @@ -22,13 +23,16 @@ import org.opendaylight.groupbasedpolicy.dto.IndexedTenant; import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.OfContext; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ConditionName; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.EndpointGroupId; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2FloodDomainId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.NetworkDomainId; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.SubnetId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.UniqueId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.Endpoint; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2BridgeDomain; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2FloodDomain; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L3Context; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.Subnet; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.EndpointGroup; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId; import org.slf4j.Logger; @@ -214,9 +218,12 @@ public class OrdinalFactory { // Based on network containment, determine components of // forwarding context - L3Context l3c = tenant.resolveL3Context(networkContainment); - L2BridgeDomain bd = tenant.resolveL2BridgeDomain(networkContainment); - L2FloodDomain fd = tenant.resolveL2FloodDomain(networkContainment); + Subnet s = ctx.getTenant(ep.getTenant()).resolveSubnet(new SubnetId(networkContainment)); + L2FloodDomainId l2fdId = new L2FloodDomainId(s.getParent().getValue()); + L2BridgeDomain bd = tenant.resolveL2BridgeDomain(l2fdId); + L2FloodDomain fd = tenant.resolveL2FloodDomain(l2fdId); + L3Context l3c = tenant.resolveL3Context(l2fdId); + // Set ordinal id's for use in flows for each forwarding context // component diff --git a/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/destination/DestinationMapperUtils.java b/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/destination/DestinationMapperUtils.java index 48487603b..482907852 100644 --- a/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/destination/DestinationMapperUtils.java +++ b/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/destination/DestinationMapperUtils.java @@ -10,6 +10,7 @@ package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.mapper.destination; import com.google.common.base.Preconditions; + import org.opendaylight.groupbasedpolicy.dto.EpKey; import org.opendaylight.groupbasedpolicy.dto.IndexedTenant; import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.OfContext; @@ -17,7 +18,9 @@ import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.OrdinalFactory; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.EndpointGroupId; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2FloodDomainId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.NetworkDomainId; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.SubnetId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoint.l3.prefix.fields.EndpointL3Gateways; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.Endpoint; @@ -59,10 +62,10 @@ class DestinationMapperUtils { } L3Context getL3ContextForSubnet(IndexedTenant indexedTenant, Subnet subnet) { - if (indexedTenant == null) { + if (indexedTenant == null || subnet.getParent() == null) { return null; } - return indexedTenant.resolveL3Context(subnet.getId()); + return indexedTenant.resolveL3Context(new L2FloodDomainId(subnet.getParent().getValue())); } NetworkDomainId getEPNetworkContainment(Endpoint endpoint, IndexedTenant tenant) { diff --git a/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/external/ExternalMapper.java b/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/external/ExternalMapper.java index d75afa2e2..a2a91d867 100755 --- a/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/external/ExternalMapper.java +++ b/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/external/ExternalMapper.java @@ -38,6 +38,8 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.Fl import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.Match; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2FloodDomainId; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.SubnetId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.Endpoint; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointL3; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.l3endpoint.rev151217.NatAddress; @@ -141,7 +143,7 @@ public class ExternalMapper extends FlowTable { natL3Ep.getKey())); if (natIpSubnet != null && natIpSubnet.getParent() != null) { L2FloodDomain natEpl2Fd = - ctx.getTenant(natL3Ep.getTenant()).resolveL2FloodDomain(natIpSubnet.getParent()); + ctx.getTenant(natL3Ep.getTenant()).resolveL2FloodDomain(new L2FloodDomainId(natIpSubnet.getParent().getValue())); if (natEpl2Fd != null && natEpl2Fd.getAugmentation(Segmentation.class) != null) { Integer vlanId = natEpl2Fd.getAugmentation(Segmentation.class).getSegmentationId(); ofWriter.writeFlow(nodeId, TABLE_ID, @@ -158,7 +160,8 @@ public class ExternalMapper extends FlowTable { * for applying VLAN tag is generated. The flow matches against REG5 holding * the L2FloodDomain and REG7 holding value of an external interface. */ - L2FloodDomain l2Fd = ctx.getTenant(endpoint.getTenant()).resolveL2FloodDomain(endpoint.getNetworkContainment()); + Subnet sub = ctx.getTenant(endpoint.getTenant()).resolveSubnet(new SubnetId(endpoint.getNetworkContainment())); + L2FloodDomain l2Fd = ctx.getTenant(endpoint.getTenant()).resolveL2FloodDomain(new L2FloodDomainId(sub.getParent().getValue())); if (l2Fd == null) { return; } diff --git a/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/ingressnat/IngressNatMapperFlows.java b/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/ingressnat/IngressNatMapperFlows.java index 1bbc8cd98..1d159cc04 100644 --- a/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/ingressnat/IngressNatMapperFlows.java +++ b/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/ingressnat/IngressNatMapperFlows.java @@ -9,6 +9,7 @@ package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.mapper.ingressnat; import com.google.common.base.Preconditions; + import org.apache.commons.lang3.ArrayUtils; import org.opendaylight.groupbasedpolicy.dto.IndexedTenant; import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.OfWriter; @@ -26,6 +27,7 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.ta import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.go.to.table._case.GoToTable; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2FloodDomainId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoint.fields.L3Address; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.Endpoint; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointL3; @@ -230,7 +232,7 @@ class IngressNatMapperFlows { Subnet extSubnet = ExternalMapper.resolveSubnetForIpv4Address(tenant, outsideDestAddress.getIpv4Address()); L2FloodDomain l2Fd = null; if (extSubnet != null && extSubnet.getParent() != null) { - l2Fd = tenant.resolveL2FloodDomain(extSubnet.getParent()); + l2Fd = tenant.resolveL2FloodDomain(new L2FloodDomainId(extSubnet.getParent().getValue())); } FlowBuilder flowBuilder = base(tableId).setPriority(priority); if (l2Fd != null && l2Fd.getAugmentation(Segmentation.class) != null) { diff --git a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/flow/ChainActionFlowsTest.java b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/flow/ChainActionFlowsTest.java index 04bda8cc6..8c06d150a 100755 --- a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/flow/ChainActionFlowsTest.java +++ b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/flow/ChainActionFlowsTest.java @@ -215,9 +215,9 @@ public class ChainActionFlowsTest extends MapperUtilsTest { List flows = new ArrayList<>(); Action segReg = nxLoadRegAction(NxmNxReg0.class, BigInteger.valueOf(1L)); Action scgReg = nxLoadRegAction(NxmNxReg1.class, BigInteger.valueOf(0xffffff)); - Action bdReg = nxLoadRegAction(NxmNxReg4.class, BigInteger.valueOf(0L)); - Action fdReg = nxLoadRegAction(NxmNxReg5.class, BigInteger.valueOf(0L)); - Action vrfReg = nxLoadRegAction(NxmNxReg6.class, BigInteger.valueOf(0L)); + Action bdReg = nxLoadRegAction(NxmNxReg4.class, BigInteger.valueOf(3L)); + Action fdReg = nxLoadRegAction(NxmNxReg5.class, BigInteger.valueOf(4L)); + Action vrfReg = nxLoadRegAction(NxmNxReg6.class, BigInteger.valueOf(5L)); for (L3Address address : networkElements.getDstEp().getL3Address()) { Layer3Match l3Match = new Ipv4MatchBuilder().setIpv4Source(new Ipv4Prefix(address.getIpAddress() .getIpv4Address().getValue() + IP_PREFIX_32)).build(); @@ -251,11 +251,11 @@ public class ChainActionFlowsTest extends MapperUtilsTest { MatchBuilder matchBuilder = new MatchBuilder().setInPort(CONNECTOR_2); addNxNsiMatch(matchBuilder, (short) 250); addNxNspMatch(matchBuilder, 27L); - addNxTunIdMatch(matchBuilder, 0); + addNxTunIdMatch(matchBuilder, 4); Match match = matchBuilder.build(); FlowId flowId = FlowIdUtils.newFlowId((short) 2, "chainbroadcast", match); FlowBuilder flowBuilder = base((short) 2).setId(flowId).setPriority(150).setMatch(match) - .setInstructions(instructions(applyActionIns(nxLoadRegAction(NxmNxReg5.class, BigInteger.valueOf(0))), + .setInstructions(instructions(applyActionIns(nxLoadRegAction(NxmNxReg5.class, BigInteger.valueOf(4))), gotoTableIns(ctx.getPolicyManager().getTABLEID_DESTINATION_MAPPER()))); return flowBuilder.build(); } @@ -271,7 +271,7 @@ public class ChainActionFlowsTest extends MapperUtilsTest { Action outputAction = FlowUtils.createActionResubmit(null, (short) 0); MatchBuilder matchBuilder = new MatchBuilder(); - addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg6.class, 0L)); + addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg6.class, 5L)); addNxTunIdMatch(matchBuilder, matchTunnelId); addNxNspMatch(matchBuilder, 27L); addNxNsiMatch(matchBuilder, (short) 255); diff --git a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/flow/GroupTableTest.java b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/flow/GroupTableTest.java index 5f79a61f1..1f38f4a5d 100755 --- a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/flow/GroupTableTest.java +++ b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/flow/GroupTableTest.java @@ -144,7 +144,7 @@ public class GroupTableTest extends MapperUtilsTest { OfOverlayContextBuilder ofOverlayContextBuilder = new OfOverlayContextBuilder(); ofOverlayContextBuilder.setNodeId(NODE_ID); endpointBuilder.addAugmentation(OfOverlayContext.class, ofOverlayContextBuilder.build()); - endpointBuilder.setNetworkContainment(NET_DOMAIN_ID); + endpointBuilder.setNetworkContainment(SUBNET_0); endpointBuilder.setTenant(buildTenant().getId()); Endpoint endpoint = endpointBuilder.build(); @@ -163,7 +163,7 @@ public class GroupTableTest extends MapperUtilsTest { groupTable.sync(endpoint, ofWriter); verify(optionalFlowCapableNode, times(1)).isPresent(); - verify(ofWriter, times(1)).writeGroup(NODE_ID, new GroupId(0L)); + verify(ofWriter, times(1)).writeGroup(NODE_ID, new GroupId(4L)); } @Test @@ -172,7 +172,8 @@ public class GroupTableTest extends MapperUtilsTest { NodeId nodeWithoutTunnel = new NodeId("nodeIdWithoutTunnel"); NodeId nodeIdIpV6 = new NodeId("nodeIdIpV6"); NodeId nodeIdIpV4 = new NodeId("nodeIdIpV4"); - Endpoint endpoint = buildEndpoint(IPV4_0, MAC_0, new NodeConnectorId(OPENFLOW + CONNECTOR_0.getValue())).build(); + Endpoint endpoint = buildEndpoint(IPV4_0, MAC_0, new NodeConnectorId(OPENFLOW + CONNECTOR_0.getValue())) + .build(); when(ctx.getTenant(any(TenantId.class))).thenReturn(getTestIndexedTenant()); when(ctx.getEndpointManager()).thenReturn(endpointManager); @@ -224,7 +225,7 @@ public class GroupTableTest extends MapperUtilsTest { @Test public void syncGroups_externalEpsWithoutLocation() throws Exception { EndpointBuilder endpointBuilder = buildEndpoint(IPV4_0, MAC_0, new NodeConnectorId(OPENFLOW + CONNECTOR_0.getValue())); - endpointBuilder.setNetworkContainment(L2FD_ID); + endpointBuilder.setNetworkContainment(SUBNET_1); Endpoint endpoint = endpointBuilder.build(); when(ctx.getTenant(any(TenantId.class))).thenReturn(getTestIndexedTenant()); @@ -243,7 +244,6 @@ public class GroupTableTest extends MapperUtilsTest { // Endpoints Collection endpoints = new HashSet<>(); EndpointBuilder noLocEndpointBuilder = buildEndpoint(IPV4_1, MAC_1, CONNECTOR_1); - noLocEndpointBuilder.setNetworkContainment(L2FD_ID); endpoints.add(noLocEndpointBuilder.build()); when(ctx.getSwitchManager()).thenReturn(switchManager); diff --git a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/MapperUtilsTest.java b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/MapperUtilsTest.java index f49ebcc22..fefcecd65 100644 --- a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/MapperUtilsTest.java +++ b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/MapperUtilsTest.java @@ -97,7 +97,7 @@ public abstract class MapperUtilsTest { protected static final EndpointGroupId ENDPOINT_GROUP_0 = new EndpointGroupId("eg0"); protected static final EndpointGroupId ENDPOINT_GROUP_1 = new EndpointGroupId("eg1"); protected static final EndpointGroupId ENDPOINT_GROUP_2 = new EndpointGroupId("eg2"); - protected static final NetworkDomainId NET_DOMAIN_ID = new NetworkDomainId("ndId"); + protected static final SubnetId NET_DOMAIN_ID = new SubnetId("ndId"); protected static final L2BridgeDomainId L2BD_ID = new L2BridgeDomainId("l2bdId"); protected static final L2FloodDomainId L2FD_ID = new L2FloodDomainId("l2fdId"); protected static final L2FloodDomainId L2_FD_ID_EXT = new L2FloodDomainId("externalL2fdId"); @@ -143,6 +143,15 @@ public abstract class MapperUtilsTest { if (l2bd != null) { endpointL3Builder.setL2Context(new L2BridgeDomainId(l2bd)); } + if(ip.equals(IPV4_0)) { + endpointL3Builder.setNetworkContainment(SUBNET_0); + } + else if(ip.equals(IPV4_1)) { + endpointL3Builder.setNetworkContainment(SUBNET_1); + } + else if(ip.equals(IPV4_2)) { + endpointL3Builder.setNetworkContainment(SUBNET_2); + } return endpointL3Builder; } @@ -255,7 +264,15 @@ public abstract class MapperUtilsTest { endpointBuilder.setL2Context(new L2BridgeDomainId(L2BD_ID)); endpointBuilder.setEndpointGroup(ENDPOINT_GROUP_0); endpointBuilder.addAugmentation(OfOverlayContext.class, getOfOverlayContext(connector).build()); - endpointBuilder.setNetworkContainment(NET_DOMAIN_ID); + if(l3IpAddress.equals(IPV4_0)) { + endpointBuilder.setNetworkContainment(SUBNET_0); + } + else if(l3IpAddress.equals(IPV4_1)) { + endpointBuilder.setNetworkContainment(SUBNET_1); + } + else if(l3IpAddress.equals(IPV4_2)) { + endpointBuilder.setNetworkContainment(SUBNET_2); + } return endpointBuilder; } diff --git a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/destination/DestinationMapperFlowsTest.java b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/destination/DestinationMapperFlowsTest.java index 78dba01b4..8605c94db 100644 --- a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/destination/DestinationMapperFlowsTest.java +++ b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/destination/DestinationMapperFlowsTest.java @@ -146,7 +146,7 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { when(ctx.getCurrentPolicy()).thenReturn(policyInfo); flows.createExternalL2Flow(tableId, 100, endpointBuilder.build(), externalConnectors, ofWriter); - verify(ctx, times(2)).getTenant(any(TenantId.class)); + verify(ctx, times(3)).getTenant(any(TenantId.class)); verify(ctx, times(1)).getEndpointManager(); verify(ctx, times(1)).getCurrentPolicy(); verifyZeroInteractions(ofWriter); @@ -160,9 +160,10 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { externalConnectors.add(new NodeConnectorId(OPENFLOW + CONNECTOR_1.getValue())); Endpoint endpoint = endpointBuilder.build(); + MatchBuilder matchBuilder = new MatchBuilder() .setEthernetMatch(ethernetMatch(null, endpoint.getMacAddress(), null)); - addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg4.class, (long) 0)); + addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg4.class, (long) 3)); Match match = matchBuilder.build(); List applyActions = new ArrayList<>(); @@ -192,7 +193,7 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { when(ctx.getCurrentPolicy()).thenReturn(policyInfo); flows.createExternalL2Flow(tableId, 100, endpointBuilder.build(), externalConnectors, ofWriter); - verify(ctx, times(2)).getTenant(any(TenantId.class)); + verify(ctx, times(3)).getTenant(any(TenantId.class)); verify(ctx, times(1)).getEndpointManager(); verify(ctx, times(1)).getCurrentPolicy(); verify(ofWriter, times(1)).writeFlow(eq(NODE_ID), eq(tableId), eq(flow)); @@ -217,7 +218,7 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { flows.createExternalL3RoutedFlow(tableId, 90, endpoint, gateway, l3AddressBuilder.build(), externalConnectors, ofWriter); - verify(ctx, times(2)).getTenant(any(TenantId.class)); + verify(ctx, times(3)).getTenant(any(TenantId.class)); verify(ctx, times(1)).getEndpointManager(); verify(ctx, times(1)).getCurrentPolicy(); verifyZeroInteractions(ofWriter); @@ -230,7 +231,7 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { Endpoint gateway = gatewayBuilder.build(); Endpoint endpoint = endpointBuilder.build(); L3AddressBuilder l3AddressBuilder = new L3AddressBuilder(); - l3AddressBuilder.setIpAddress(new IpAddress(new Ipv4Address(IPV4_0))); + l3AddressBuilder.setIpAddress(new IpAddress(IPV4_0)); Set externalConnectors = new HashSet<>(); externalConnectors.add(new NodeConnectorId(CONNECTOR_0)); externalConnectors.add(new NodeConnectorId(CONNECTOR_1)); @@ -242,7 +243,7 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { flows.createExternalL3RoutedFlow(tableId, 90, endpoint, gateway, l3AddressBuilder.build(), externalConnectors, ofWriter); - verify(ctx, times(2)).getTenant(any(TenantId.class)); + verify(ctx, times(3)).getTenant(any(TenantId.class)); verify(ctx, times(1)).getEndpointManager(); verify(ctx, times(1)).getCurrentPolicy(); verifyZeroInteractions(ofWriter); @@ -255,14 +256,14 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { Endpoint gateway = gatewayBuilder.build(); Endpoint endpoint = endpointBuilder.build(); L3AddressBuilder l3AddressBuilder = new L3AddressBuilder(); - l3AddressBuilder.setIpAddress(new IpAddress(new Ipv4Address(IPV4_0))); + l3AddressBuilder.setIpAddress(new IpAddress(IPV4_0)); Set externalConnectors = new HashSet<>(); externalConnectors.add(new NodeConnectorId(OPENFLOW + CONNECTOR_0.getValue())); externalConnectors.add(new NodeConnectorId(OPENFLOW + CONNECTOR_1.getValue())); List l3ApplyActions = new ArrayList<>(); - l3ApplyActions.add(setDlSrcAction(new MacAddress(MAC_0))); - l3ApplyActions.add(setDlDstAction(new MacAddress(MAC_0))); + l3ApplyActions.add(setDlSrcAction(MAC_0)); + l3ApplyActions.add(setDlDstAction(MAC_0)); List applyActions = new ArrayList<>(); applyActions.add(nxLoadRegAction(NxmNxReg2.class, BigInteger.valueOf(1))); applyActions.add(nxLoadRegAction(NxmNxReg3.class, BigInteger.valueOf(0))); @@ -272,7 +273,7 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { MatchBuilder matchBuilder = new MatchBuilder().setEthernetMatch(ethernetMatch(null, MAC_1, IPv4)) .setLayer3Match(new Ipv4MatchBuilder() .setIpv4Destination(new Ipv4Prefix(IPV4_0.getValue() + IP_PREFIX_32)).build()); - addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg6.class, (long) 0)); + addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg6.class, (long) 5)); Match match = matchBuilder.build(); int order = 0; @@ -298,7 +299,7 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { flows.createExternalL3RoutedFlow(tableId, 90, endpoint, gateway, l3AddressBuilder.build(), externalConnectors, ofWriter); - verify(ctx, times(2)).getTenant(any(TenantId.class)); + verify(ctx, times(3)).getTenant(any(TenantId.class)); verify(ctx, times(1)).getEndpointManager(); verify(ctx, times(1)).getCurrentPolicy(); verify(ofWriter, times(1)).writeFlow(eq(NODE_ID), eq(tableId), eq(flow)); @@ -317,8 +318,8 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { externalConnectors.add(new NodeConnectorId(OPENFLOW + CONNECTOR_1.getValue())); List l3ApplyActions = new ArrayList<>(); - l3ApplyActions.add(setDlSrcAction(new MacAddress(MAC_0))); - l3ApplyActions.add(setDlDstAction(new MacAddress(MAC_0))); + l3ApplyActions.add(setDlSrcAction(MAC_0)); + l3ApplyActions.add(setDlDstAction(MAC_0)); List applyActions = new ArrayList<>(); applyActions.add(nxLoadRegAction(NxmNxReg2.class, BigInteger.valueOf(1))); applyActions.add(nxLoadRegAction(NxmNxReg3.class, BigInteger.valueOf(0))); @@ -354,7 +355,7 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { flows.createExternalL3RoutedFlow(tableId, 90, endpoint, gateway, l3AddressBuilder.build(), externalConnectors, ofWriter); - verify(ctx, times(2)).getTenant(any(TenantId.class)); + verify(ctx, times(3)).getTenant(any(TenantId.class)); verify(ctx, times(1)).getEndpointManager(); verify(ctx, times(1)).getCurrentPolicy(); verify(ofWriter, times(1)).writeFlow(eq(NODE_ID), eq(tableId), eq(flow)); @@ -371,7 +372,7 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { flows.createLocalL2Flow(tableId, 80, endpoint, ofWriter); - verify(ctx, times(2)).getTenant(any(TenantId.class)); + verify(ctx, times(3)).getTenant(any(TenantId.class)); verify(ctx, times(1)).getEndpointManager(); verify(ctx, times(1)).getCurrentPolicy(); verifyZeroInteractions(ofWriter); @@ -381,6 +382,7 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { public void createLocalL2Flow() { NodeConnectorId connectorId = new NodeConnectorId(OPENFLOW + CONNECTOR_0.getValue()); EndpointBuilder endpointBuilder = buildEndpoint(IPV6_1, MAC_0, connectorId); + endpointBuilder.setNetworkContainment(SUBNET_0); Endpoint endpoint = endpointBuilder.build(); List applyActions = new ArrayList<>(); @@ -404,7 +406,7 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { MatchBuilder matchBuilder = new MatchBuilder().setEthernetMatch(ethernetMatch(null, endpoint.getMacAddress(), null)); - addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg4.class, (long) 0)); + addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg4.class, (long) 3)); Match match = matchBuilder.build(); Flow flow = buildFlow(FlowIdUtils.newFlowId(tableId, "localL2", match), tableId, 80, match, @@ -416,7 +418,7 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { flows.createLocalL2Flow(tableId, 80, endpoint, ofWriter); - verify(ctx, times(2)).getTenant(any(TenantId.class)); + verify(ctx, times(3)).getTenant(any(TenantId.class)); verify(ctx, times(1)).getEndpointManager(); verify(ctx, times(1)).getCurrentPolicy(); verify(ofWriter, times(1)).writeFlow(eq(NODE_ID), eq(tableId), eq(flow)); @@ -440,17 +442,19 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { OfOverlayContextBuilder ofOverlayContextBuilder = new OfOverlayContextBuilder(); ofOverlayContextBuilder.setNodeConnectorId(new NodeConnectorId(CONNECTOR_1)); EndpointBuilder endpointBuilder = buildEndpoint(IPV6_1, MAC_1, connectorId); + endpointBuilder.setNetworkContainment(SUBNET_0); endpointBuilder.addAugmentation(OfOverlayContext.class, ofOverlayContextBuilder.build()); endpointBuilder.setTenant(getTestIndexedTenant().getTenant().getId()); endpointBuilder.setMacAddress(null); Endpoint endpoint = endpointBuilder.build(); SubnetBuilder localSubnetBuilder = new SubnetBuilder(); - localSubnetBuilder.setId(new SubnetId(L3C_ID)); + localSubnetBuilder.setId(SUBNET_0); + localSubnetBuilder.setParent(L2FD_ID); Subnet localSubnet = localSubnetBuilder.build(); SubnetBuilder destSubnetBuilder = new SubnetBuilder(); - destSubnetBuilder.setId(new SubnetId(SUBNET_0)); + destSubnetBuilder.setId(SUBNET_1); Subnet destSubnet = destSubnetBuilder.build(); when(ctx.getTenant(any(TenantId.class))).thenReturn(getTestIndexedTenant()); @@ -469,15 +473,18 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { ofOverlayContextBuilder.setNodeConnectorId(new NodeConnectorId(CONNECTOR_1)); EndpointBuilder endpointBuilder = buildEndpoint(IPV6_1, MAC_1, connectorId); endpointBuilder.addAugmentation(OfOverlayContext.class, ofOverlayContextBuilder.build()); + endpointBuilder.setNetworkContainment(SUBNET_0); endpointBuilder.setTenant(getTestIndexedTenant().getTenant().getId()); Endpoint endpoint = endpointBuilder.build(); SubnetBuilder localSubnetBuilder = new SubnetBuilder(); - localSubnetBuilder.setId(new SubnetId(L3C_ID)); + localSubnetBuilder.setId(SUBNET_0); + localSubnetBuilder.setParent(L2FD_ID); Subnet localSubnet = localSubnetBuilder.build(); SubnetBuilder destSubnetBuilder = new SubnetBuilder(); - destSubnetBuilder.setId(new SubnetId(L3C_ID)); + destSubnetBuilder.setId(SUBNET_1); + destSubnetBuilder.setParent(L2FD_ID); Subnet destSubnet = destSubnetBuilder.build(); when(ctx.getTenant(any(TenantId.class))).thenReturn(getTestIndexedTenant()); @@ -500,11 +507,11 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { Endpoint endpoint = endpointBuilder.build(); SubnetBuilder localSubnetBuilder = new SubnetBuilder(); - localSubnetBuilder.setId(new SubnetId(L3C_ID)); + localSubnetBuilder.setId(SUBNET_0).setParent(L2FD_ID); Subnet localSubnet = localSubnetBuilder.build(); SubnetBuilder destSubnetBuilder = new SubnetBuilder(); - destSubnetBuilder.setId(new SubnetId(CONTEXT_ID)); + destSubnetBuilder.setId(SUBNET_1); Subnet destSubnet = destSubnetBuilder.build(); L3AddressBuilder l3AddressBuilder = new L3AddressBuilder(); @@ -516,7 +523,7 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { when(ctx.getCurrentPolicy()).thenReturn(policyInfo); flows.createLocalL3RoutedFlow(tableId, 80, endpoint, l3Address, localSubnet, destSubnet, ofWriter); - verify(ctx, times(3)).getTenant(any(TenantId.class)); + verify(ctx, times(4)).getTenant(any(TenantId.class)); verify(ctx, times(3)).getEndpointManager(); verify(ctx, times(1)).getCurrentPolicy(); verifyZeroInteractions(ofWriter); @@ -531,22 +538,25 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { EndpointBuilder endpointBuilder = buildEndpoint(IPV6_1, MAC_1, connectorId); endpointBuilder.addAugmentation(OfOverlayContext.class, ofOverlayContextBuilder.build()); endpointBuilder.setTenant(getTestIndexedTenant().getTenant().getId()); + endpointBuilder.setNetworkContainment(SUBNET_0); Endpoint endpoint = endpointBuilder.build(); SubnetBuilder localSubnetBuilder = new SubnetBuilder(); - localSubnetBuilder.setId(new SubnetId(L3C_ID)); + localSubnetBuilder.setId(SUBNET_0); + localSubnetBuilder.setParent(L2FD_ID); Subnet localSubnet = localSubnetBuilder.build(); SubnetBuilder destSubnetBuilder = new SubnetBuilder(); - destSubnetBuilder.setId(new SubnetId(CONTEXT_ID)); + destSubnetBuilder.setId(SUBNET_1); + destSubnetBuilder.setParent(L2FD_ID); Subnet destSubnet = destSubnetBuilder.build(); L3AddressBuilder l3AddressBuilder = new L3AddressBuilder(); - l3AddressBuilder.setIpAddress(new IpAddress(new Ipv4Address(IPV4_0))); + l3AddressBuilder.setIpAddress(new IpAddress((IPV4_0))); L3Address l3Address = l3AddressBuilder.build(); List l3ApplyActions = new ArrayList<>(); - l3ApplyActions.add(setDlDstAction((new MacAddress(MAC_1)))); + l3ApplyActions.add(setDlDstAction((MAC_1))); l3ApplyActions.add(decNwTtlAction()); l3ApplyActions.add(setDlSrcAction(destMac)); @@ -567,9 +577,9 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { l3instructions.add(applyActionsIns); l3instructions.add(gotoTable); - MatchBuilder matchBuilder = new MatchBuilder().setEthernetMatch(ethernetMatch(null, new MacAddress(destMac), IPv4)) + MatchBuilder matchBuilder = new MatchBuilder().setEthernetMatch(ethernetMatch(null, destMac, IPv4)) .setLayer3Match(new Ipv4MatchBuilder().setIpv4Destination(new Ipv4Prefix(IPV4_0.getValue() + IP_PREFIX_32)).build()); - addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg6.class, (long) 0)); + addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg6.class, (long) 5)); Match match = matchBuilder.build(); InstructionsBuilder instructionsBuilder = new InstructionsBuilder(); instructionsBuilder.setInstruction(l3instructions); @@ -582,7 +592,7 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { when(ctx.getCurrentPolicy()).thenReturn(policyInfo); flows.createLocalL3RoutedFlow(tableId, 80, endpoint, l3Address, localSubnet, destSubnet, ofWriter); - verify(ctx, times(3)).getTenant(any(TenantId.class)); + verify(ctx, times(4)).getTenant(any(TenantId.class)); verify(ctx, times(3)).getEndpointManager(); verify(ctx, times(1)).getCurrentPolicy(); verify(ofWriter, times(1)).writeFlow(eq(NODE_ID), eq(tableId), eq(flow)); @@ -597,22 +607,25 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { EndpointBuilder endpointBuilder = buildEndpoint(IPV6_1,MAC_1, connectorId); endpointBuilder.addAugmentation(OfOverlayContext.class, ofOverlayContextBuilder.build()); endpointBuilder.setTenant(getTestIndexedTenant().getTenant().getId()); + endpointBuilder.setNetworkContainment(SUBNET_0); Endpoint endpoint = endpointBuilder.build(); SubnetBuilder localSubnetBuilder = new SubnetBuilder(); - localSubnetBuilder.setId(new SubnetId(L3C_ID)); + localSubnetBuilder.setId(SUBNET_0); + localSubnetBuilder.setParent(L2FD_ID); Subnet localSubnet = localSubnetBuilder.build(); SubnetBuilder destSubnetBuilder = new SubnetBuilder(); - destSubnetBuilder.setId(new SubnetId(CONTEXT_ID)); + destSubnetBuilder.setId(SUBNET_1); + destSubnetBuilder.setParent(L2FD_ID); Subnet destSubnet = destSubnetBuilder.build(); L3AddressBuilder l3AddressBuilder = new L3AddressBuilder(); - l3AddressBuilder.setIpAddress(new IpAddress(new Ipv6Address(IPV6_1))); + l3AddressBuilder.setIpAddress(new IpAddress((IPV6_1))); L3Address l3Address = l3AddressBuilder.build(); List l3ApplyActions = new ArrayList<>(); - l3ApplyActions.add(setDlDstAction((new MacAddress(MAC_1)))); + l3ApplyActions.add(setDlDstAction(MAC_1)); l3ApplyActions.add(decNwTtlAction()); l3ApplyActions.add(setDlSrcAction(destMac)); @@ -633,9 +646,9 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { l3instructions.add(applyActionsIns); l3instructions.add(gotoTable); - MatchBuilder matchBuilder = new MatchBuilder().setEthernetMatch(ethernetMatch(null, new MacAddress(destMac), IPv6)) + MatchBuilder matchBuilder = new MatchBuilder().setEthernetMatch(ethernetMatch(null, destMac, IPv6)) .setLayer3Match(new Ipv6MatchBuilder().setIpv6Destination(new Ipv6Prefix(IPV6_1.getValue() + IP_PREFIX_128)).build()); - addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg6.class, (long) 0)); + addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg6.class, (long) 5)); Match match = matchBuilder.build(); InstructionsBuilder instructionsBuilder = new InstructionsBuilder(); instructionsBuilder.setInstruction(l3instructions); @@ -648,7 +661,7 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { when(ctx.getCurrentPolicy()).thenReturn(policyInfo); flows.createLocalL3RoutedFlow(tableId, 80, endpoint, l3Address, localSubnet, destSubnet, ofWriter); - verify(ctx, times(3)).getTenant(any(TenantId.class)); + verify(ctx, times(4)).getTenant(any(TenantId.class)); verify(ctx, times(3)).getEndpointManager(); verify(ctx, times(1)).getCurrentPolicy(); verify(ofWriter, times(1)).writeFlow(eq(NODE_ID), eq(tableId), eq(flow)); @@ -664,7 +677,7 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { flows.createRemoteL2Flow(tableId, 70, endpointBuilder.build(), null, null, new NodeConnectorId(CONNECTOR_1), ofWriter); - verify(ctx, times(2)).getTenant(any(TenantId.class)); + verify(ctx, times(3)).getTenant(any(TenantId.class)); verify(ctx, times(1)).getEndpointManager(); verify(ctx, times(1)).getCurrentPolicy(); verifyZeroInteractions(ofWriter); @@ -698,8 +711,8 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { instructionsBuilder.setInstruction(instructions); MatchBuilder matchBuilder = new MatchBuilder() - .setEthernetMatch(ethernetMatch(null, new MacAddress(MAC_0), null)); - addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg4.class, (long) 0)); + .setEthernetMatch(ethernetMatch(null, MAC_0, null)); + addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg4.class, (long) 3)); Match match = matchBuilder.build(); Flow flow = buildFlow(FlowIdUtils.newFlowId(tableId, "remoteL2", match), tableId, 70, match, @@ -711,7 +724,7 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { flows.createRemoteL2Flow(tableId, 70, endpointBuilder.build(), peerEndpointBuilder.build(), ipAddress, connectorId, ofWriter); - verify(ctx, times(2)).getTenant(any(TenantId.class)); + verify(ctx, times(3)).getTenant(any(TenantId.class)); verify(ctx, times(1)).getEndpointManager(); verify(ctx, times(1)).getCurrentPolicy(); verify(ofWriter, times(1)).writeFlow(eq(NODE_ID), eq(tableId), eq(flow)); @@ -730,7 +743,7 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { flows.createRemoteL2Flow(tableId, 70, endpointBuilder.build(), peerEndpointBuilder.build(), ipAddress, connectorId, ofWriter); - verify(ctx, times(2)).getTenant(any(TenantId.class)); + verify(ctx, times(3)).getTenant(any(TenantId.class)); verify(ctx, times(1)).getEndpointManager(); verify(ctx, times(1)).getCurrentPolicy(); verifyZeroInteractions(ofWriter); @@ -751,12 +764,14 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { Endpoint endpoint = endpointBuilder.build(); SubnetBuilder destSubnetBuilder = new SubnetBuilder(); - destSubnetBuilder.setId(new SubnetId(L3C_ID)); + destSubnetBuilder.setId(SUBNET_0); + destSubnetBuilder.setParent(L2FD_ID); Subnet destSubnet = destSubnetBuilder.build(); SubnetBuilder localSubnetBuilder = new SubnetBuilder(); - localSubnetBuilder.setId(new SubnetId(L3C_ID)); - localSubnetBuilder.setVirtualRouterIp(new IpAddress(new Ipv4Address(IPV4_1))); + localSubnetBuilder.setId(SUBNET_1); + localSubnetBuilder.setVirtualRouterIp(new IpAddress(IPV4_1)); + localSubnetBuilder.setParent(L2FD_ID); Subnet localSubnet = localSubnetBuilder.build(); when(ctx.getTenant(Mockito.any(TenantId.class))).thenReturn(getTestIndexedTenant()); @@ -764,7 +779,7 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { when(ctx.getCurrentPolicy()).thenReturn(policyInfo); flows.createRemoteL3RoutedFlow(tableId, 60, endpoint, null, destSubnet, null, null, localSubnet, ofWriter); - verify(ctx, times(3)).getTenant(any(TenantId.class)); + verify(ctx, times(4)).getTenant(any(TenantId.class)); verify(ctx, times(2)).getEndpointManager(); verify(ctx, times(1)).getCurrentPolicy(); verifyZeroInteractions(ofWriter); @@ -773,15 +788,18 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { @Test public void createRemoteL3RoutedFlow_noIp() { EndpointBuilder endpointBuilder = buildEndpoint(IPV6_1, MAC_1, CONNECTOR_0); + endpointBuilder.setNetworkContainment(SUBNET_0); Endpoint endpoint = endpointBuilder.build(); SubnetBuilder destSubnetBuilder = new SubnetBuilder(); - destSubnetBuilder.setId(new SubnetId(L3C_ID)); + destSubnetBuilder.setId(SUBNET_1); + destSubnetBuilder.setParent(L2FD_ID); Subnet destSubnet = destSubnetBuilder.build(); SubnetBuilder localSubnetBuilder = new SubnetBuilder(); - localSubnetBuilder.setId(new SubnetId(L3C_ID)); - localSubnetBuilder.setVirtualRouterIp(new IpAddress(new Ipv4Address(IPV4_1))); + localSubnetBuilder.setId(SUBNET_0); + localSubnetBuilder.setVirtualRouterIp(new IpAddress(IPV4_1)); + localSubnetBuilder.setParent(L2FD_ID); Subnet localSubnet = localSubnetBuilder.build(); when(ctx.getTenant(Mockito.any(TenantId.class))).thenReturn(getTestIndexedTenant()); @@ -789,7 +807,7 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { when(ctx.getCurrentPolicy()).thenReturn(policyInfo); flows.createRemoteL3RoutedFlow(tableId, 60, endpoint, null, destSubnet, null, null, localSubnet, ofWriter); - verify(ctx, times(3)).getTenant(any(TenantId.class)); + verify(ctx, times(4)).getTenant(any(TenantId.class)); verify(ctx, times(3)).getEndpointManager(); verify(ctx, times(1)).getCurrentPolicy(); verifyZeroInteractions(ofWriter); @@ -797,18 +815,21 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { @Test public void createRemoteL3RoutedFlow_incorrectPortId() { - IpAddress ipAddress = new IpAddress(new Ipv4Address(IPV4_0)); + IpAddress ipAddress = new IpAddress(IPV4_0); NodeConnectorId connectorId = new NodeConnectorId(CONNECTOR_0); EndpointBuilder endpointBuilder = buildEndpoint(IPV6_1,MAC_1,CONNECTOR_0); + endpointBuilder.setNetworkContainment(SUBNET_0); Endpoint endpoint = endpointBuilder.build(); + SubnetBuilder destSubnetBuilder = new SubnetBuilder(); - destSubnetBuilder.setId(new SubnetId(L3C_ID)); + destSubnetBuilder.setId(SUBNET_1); + destSubnetBuilder.setParent(L2FD_ID); Subnet destSubnet = destSubnetBuilder.build(); SubnetBuilder localSubnetBuilder = new SubnetBuilder(); - localSubnetBuilder.setId(new SubnetId(SUBNET_0)); - localSubnetBuilder.setVirtualRouterIp(new IpAddress(new Ipv4Address(IPV4_1))); + localSubnetBuilder.setId(SUBNET_0); + localSubnetBuilder.setVirtualRouterIp(new IpAddress(IPV4_1)); Subnet localSubnet = localSubnetBuilder.build(); when(ctx.getTenant(Mockito.any(TenantId.class))).thenReturn(getTestIndexedTenant()); @@ -817,7 +838,7 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { flows.createRemoteL3RoutedFlow(tableId, 60, endpoint, null, destSubnet, ipAddress, connectorId, localSubnet, ofWriter); - verify(ctx, times(3)).getTenant(any(TenantId.class)); + verify(ctx, times(4)).getTenant(any(TenantId.class)); verify(ctx, times(3)).getEndpointManager(); verify(ctx, times(1)).getCurrentPolicy(); verifyZeroInteractions(ofWriter); @@ -826,26 +847,28 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { @Test public void createRemoteL3RoutedFlow_ipV4() { MacAddress routerMac = DestinationMapper.ROUTER_MAC; - IpAddress ipAddress = new IpAddress(new Ipv4Address(IPV4_1)); + IpAddress ipAddress = new IpAddress(IPV4_1); L3AddressBuilder l3AddressBuilder = new L3AddressBuilder(); - l3AddressBuilder.setIpAddress(new IpAddress(new Ipv4Address(IPV4_1))); + l3AddressBuilder.setIpAddress(new IpAddress(IPV4_1)); L3Address l3Address = l3AddressBuilder.build(); NodeConnectorId connectorId = new NodeConnectorId(OPENFLOW + CONNECTOR_0.getValue()); EndpointBuilder endpointBuilder = buildEndpoint(IPV4_0, MAC_1, CONNECTOR_0); Endpoint endpoint = endpointBuilder.build(); SubnetBuilder destSubnetBuilder = new SubnetBuilder(); - destSubnetBuilder.setId(new SubnetId(L3C_ID)); + destSubnetBuilder.setId(SUBNET_1); + destSubnetBuilder.setParent(L2FD_ID); Subnet destSubnet = destSubnetBuilder.build(); SubnetBuilder localSubnetBuilder = new SubnetBuilder(); - localSubnetBuilder.setId(new SubnetId(SUBNET_0)); - localSubnetBuilder.setVirtualRouterIp(new IpAddress(new Ipv4Address(IPV4_1))); + localSubnetBuilder.setId(SUBNET_0); + localSubnetBuilder.setVirtualRouterIp(new IpAddress(IPV4_1)); + localSubnetBuilder.setParent(L2FD_ID); Subnet localSubnet = localSubnetBuilder.build(); List l3ApplyActions = new ArrayList<>(); - l3ApplyActions.add(setDlSrcAction(new MacAddress(routerMac))); - l3ApplyActions.add(setDlDstAction(new MacAddress(MAC_1))); + l3ApplyActions.add(setDlSrcAction(routerMac)); + l3ApplyActions.add(setDlDstAction(MAC_1)); l3ApplyActions.add(decNwTtlAction()); List applyActions = new ArrayList<>(); applyActions.add(nxLoadRegAction(NxmNxReg2.class, BigInteger.valueOf(1))); @@ -865,9 +888,9 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { InstructionsBuilder instructionsBuilder = new InstructionsBuilder(); instructionsBuilder.setInstruction(l3instructions); - MatchBuilder matchBuilder = new MatchBuilder().setEthernetMatch(ethernetMatch(null, new MacAddress(routerMac), IPv4)) + MatchBuilder matchBuilder = new MatchBuilder().setEthernetMatch(ethernetMatch(null, routerMac, IPv4)) .setLayer3Match(new Ipv4MatchBuilder().setIpv4Destination(new Ipv4Prefix(IPV4_1.getValue() + IP_PREFIX_32)).build()); - addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg6.class, (long) 0)); + addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg6.class, (long) 5)); Match match = matchBuilder.build(); Flow flow = buildFlow(FlowIdUtils.newFlowId(tableId, "remoteL3", match), tableId, 60, match, @@ -879,7 +902,7 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { flows.createRemoteL3RoutedFlow(tableId, 60, endpoint, l3Address, destSubnet, ipAddress, connectorId, localSubnet, ofWriter); - verify(ctx, times(3)).getTenant(any(TenantId.class)); + verify(ctx, times(4)).getTenant(any(TenantId.class)); verify(ctx, times(3)).getEndpointManager(); verify(ctx, times(1)).getCurrentPolicy(); verify(ofWriter, times(1)).writeFlow(eq(NODE_ID), eq(tableId), eq(flow)); @@ -889,19 +912,21 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { public void createRemoteL3RoutedFlow_ipV6() { IpAddress ipAddress = new IpAddress(new Ipv6Address(IPV6_1)); L3AddressBuilder l3AddressBuilder = new L3AddressBuilder(); - l3AddressBuilder.setIpAddress(new IpAddress(new Ipv4Address(IPV4_1))); + l3AddressBuilder.setIpAddress(new IpAddress(IPV4_1)); L3Address l3Address = l3AddressBuilder.build(); NodeConnectorId connectorId = new NodeConnectorId(OPENFLOW + CONNECTOR_0); EndpointBuilder endpointBuilder = buildEndpoint(IPV4_0, MAC_1, CONNECTOR_0); Endpoint endpoint = endpointBuilder.build(); SubnetBuilder destSubnetBuilder = new SubnetBuilder(); - destSubnetBuilder.setId(new SubnetId(L3C_ID)); + destSubnetBuilder.setId(SUBNET_1); + destSubnetBuilder.setParent(L2FD_ID); Subnet destSubnet = destSubnetBuilder.build(); SubnetBuilder localSubnetBuilder = new SubnetBuilder(); - localSubnetBuilder.setId(new SubnetId(SUBNET_0)); - localSubnetBuilder.setVirtualRouterIp(new IpAddress(new Ipv4Address(IPV4_1))); + localSubnetBuilder.setId(SUBNET_0); + localSubnetBuilder.setParent(L2FD_ID); + localSubnetBuilder.setVirtualRouterIp(new IpAddress(IPV4_1)); Subnet localSubnet = localSubnetBuilder.build(); when(ctx.getTenant(Mockito.any(TenantId.class))).thenReturn(getTestIndexedTenant()); @@ -910,7 +935,7 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { flows.createRemoteL3RoutedFlow(tableId, 60, endpoint, l3Address, destSubnet, ipAddress, connectorId, localSubnet, ofWriter); - verify(ctx, times(3)).getTenant(any(TenantId.class)); + verify(ctx, times(4)).getTenant(any(TenantId.class)); verify(ctx, times(3)).getEndpointManager(); verify(ctx, times(1)).getCurrentPolicy(); verifyZeroInteractions(ofWriter); @@ -929,18 +954,19 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { public void createRouterArpFlow_ipV4() throws Exception { IndexedTenant tenant = getTestIndexedTenant(); SubnetBuilder subnetBuilder = new SubnetBuilder(); - subnetBuilder.setId(new SubnetId(L3C_ID)); - subnetBuilder.setVirtualRouterIp(new IpAddress(new Ipv4Address(IPV4_0))); + subnetBuilder.setId(SUBNET_0); + subnetBuilder.setParent(L2FD_ID); + subnetBuilder.setVirtualRouterIp(new IpAddress(IPV4_0)); MatchBuilder matchBuilder = new MatchBuilder().setEthernetMatch(ethernetMatch(null, null, ARP)) .setLayer3Match(new ArpMatchBuilder().setArpOp(1) .setArpTargetTransportAddress(new Ipv4Prefix(IPV4_0.getValue() + IP_PREFIX_32)).build()); - addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg6.class, (long) 1)); + addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg6.class, (long) 5)); Match match = matchBuilder.build(); List actions = new ArrayList<>(); actions.add(nxMoveEthSrcToEthDstAction()); - actions.add(setDlSrcAction(new MacAddress(DestinationMapper.ROUTER_MAC))); + actions.add(setDlSrcAction(DestinationMapper.ROUTER_MAC)); actions.add(nxLoadArpOpAction(BigInteger.valueOf(2L))); actions.add(nxMoveArpShaToArpThaAction()); actions.add(nxLoadArpShaAction(new BigInteger(1, bytesFromHexString(DestinationMapper.ROUTER_MAC.getValue())))); @@ -968,8 +994,9 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { public void createRouterArpFlow_ipV6() throws Exception { IndexedTenant tenant = getTestIndexedTenant(); SubnetBuilder subnetBuilder = new SubnetBuilder(); - subnetBuilder.setId(new SubnetId(L3C_ID)); - subnetBuilder.setVirtualRouterIp(new IpAddress(new Ipv6Address(IPV6_1))); + subnetBuilder.setId(SUBNET_1); + subnetBuilder.setParent(L2FD_ID); + subnetBuilder.setVirtualRouterIp(new IpAddress(IPV6_1)); when(ctx.getEndpointManager()).thenReturn(endpointManager); @@ -991,14 +1018,14 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { OrdinalFactory.EndpointFwdCtxOrdinals ordinals = utils.getEndpointOrdinals(endpointBuilder.build()); - verify(ctx, times(2)).getTenant(any(TenantId.class)); + verify(ctx, times(3)).getTenant(any(TenantId.class)); verify(ctx, times(1)).getEndpointManager(); verify(ctx, times(1)).getCurrentPolicy(); MatchBuilder matchBuilder = new MatchBuilder() .setEthernetMatch(new EthernetMatchBuilder() - .setEthernetDestination(new EthernetDestinationBuilder().setAddress(new MacAddress(MAC_0)) - .setMask(new MacAddress(MAC_0)).build()) + .setEthernetDestination(new EthernetDestinationBuilder().setAddress(MAC_0) + .setMask(MAC_0).build()) .build()); addNxRegMatch(matchBuilder, FlowUtils.RegMatch.of(NxmNxReg5.class, (long) ordinals.getFdId())); Match match = matchBuilder.build(); @@ -1015,7 +1042,7 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { Flow flow = buildFlow(FlowIdUtils.newFlowId(tableId, "broadcast", match), tableId, 40, match, instructionsBuilder.build()).build(); - flows.createBroadcastFlow(40, ordinals, new MacAddress(MAC_0), ofWriter); + flows.createBroadcastFlow(40, ordinals, MAC_0, ofWriter); verify(ofWriter, times(1)).writeFlow(any(NodeId.class), anyShort(), eq(flow)); } @@ -1029,8 +1056,9 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { IndexedTenant tenant = getTestIndexedTenant(); SubnetBuilder localSubnetBuilder = new SubnetBuilder(); - localSubnetBuilder.setId(new SubnetId(L3C_ID)); - localSubnetBuilder.setVirtualRouterIp(new IpAddress(new Ipv4Address(IPV4_0))); + localSubnetBuilder.setId(SUBNET_1); + localSubnetBuilder.setVirtualRouterIp(new IpAddress((IPV4_0))); + localSubnetBuilder.setParent(L2FD_ID); Subnet localSubnet = localSubnetBuilder.build(); when(ctx.getEndpointManager()).thenReturn(endpointManager); @@ -1043,7 +1071,6 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { @Test public void createL3PrefixFlow_externalExceptionCaught() { EndpointBuilder gatewayEpBuilder = buildEndpoint(IPV4_0, MAC_0, CONNECTOR_0); - OfOverlayContextBuilder ofOverlayContextBuilder = new OfOverlayContextBuilder(); ofOverlayContextBuilder.setNodeConnectorId(new NodeConnectorId(CONNECTOR_1)); gatewayEpBuilder.addAugmentation(OfOverlayContext.class, ofOverlayContextBuilder.build()); @@ -1058,8 +1085,9 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { IndexedTenant tenant = new IndexedTenant(tenantBuilder.build()); SubnetBuilder localSubnetBuilder = new SubnetBuilder(); - localSubnetBuilder.setId(new SubnetId(L3C_ID)); - localSubnetBuilder.setVirtualRouterIp(new IpAddress(new Ipv4Address(IPV4_0))); + localSubnetBuilder.setId(SUBNET_1); + localSubnetBuilder.setVirtualRouterIp(new IpAddress(IPV4_0)); + localSubnetBuilder.setParent(L2FD_ID); Subnet localSubnet = localSubnetBuilder.build(); Set externalPorts = new HashSet<>(); @@ -1088,12 +1116,13 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { IndexedTenant tenant = getTestIndexedTenant(); SubnetBuilder localSubnetBuilder = new SubnetBuilder(); - localSubnetBuilder.setId(new SubnetId(L3C_ID)); - localSubnetBuilder.setVirtualRouterIp(new IpAddress(new Ipv4Address(IPV4_0))); + localSubnetBuilder.setId(SUBNET_0); + localSubnetBuilder.setParent(L2FD_ID); + localSubnetBuilder.setVirtualRouterIp(new IpAddress(IPV4_0)); Subnet localSubnet = localSubnetBuilder.build(); List l3ApplyActions = new ArrayList<>(); - l3ApplyActions.add(setDlDstAction(new MacAddress(MAC_0))); + l3ApplyActions.add(setDlDstAction(MAC_0)); l3ApplyActions.add(decNwTtlAction()); List applyActions = new ArrayList<>(); applyActions.add(nxLoadRegAction(NxmNxReg2.class, BigInteger.valueOf(1))); @@ -1113,8 +1142,8 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { instructionsBuilder.setInstruction(l3instructions); MatchBuilder matchBuilder = new MatchBuilder().setEthernetMatch(ethernetMatch(null, - new MacAddress(DestinationMapper.ROUTER_MAC), IPv4)); - addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg6.class, (long) 0)); + DestinationMapper.ROUTER_MAC, IPv4)); + addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg6.class, (long) 5)); Match match = matchBuilder.build(); Integer prefixLength = Integer.valueOf(l3Prefix.getIpPrefix().getIpv4Prefix().getValue().split("/")[1]); @@ -1127,7 +1156,7 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { flows.createL3PrefixFlow(tableId, 30, gatewayEp.build(), l3Prefix, tenant, localSubnet, null, ofWriter); - verify(ctx, times(2)).getTenant(any(TenantId.class)); + verify(ctx, times(3)).getTenant(any(TenantId.class)); verify(ctx, times(2)).getEndpointManager(); verify(ctx, times(1)).getCurrentPolicy(); verify(ofWriter, times(1)).writeFlow(any(NodeId.class), anyShort(), eq(flow)); @@ -1137,6 +1166,7 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { public void createL3PrefixFlow_externalIpv6() throws Exception { NodeConnectorId connectorId = new NodeConnectorId(OPENFLOW + CONNECTOR_0.getValue()); EndpointBuilder gatewayEpBuilder = buildEndpoint(IPV6_1, MAC_0, connectorId); + gatewayEpBuilder.setNetworkContainment(SUBNET_0); OfOverlayContextBuilder ofOverlayContextBuilder = new OfOverlayContextBuilder(); ofOverlayContextBuilder.setNodeConnectorId(new NodeConnectorId(OPENFLOW + CONNECTOR_1)); @@ -1152,8 +1182,9 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { IndexedTenant tenant = new IndexedTenant(tenantBuilder.build()); SubnetBuilder localSubnetBuilder = new SubnetBuilder(); - localSubnetBuilder.setId(new SubnetId(L3C_ID)); - localSubnetBuilder.setVirtualRouterIp(new IpAddress(new Ipv6Address(IPV6_2))); + localSubnetBuilder.setId(SUBNET_0); + localSubnetBuilder.setVirtualRouterIp(new IpAddress(IPV6_2)); + localSubnetBuilder.setParent(L2FD_ID); Subnet localSubnet = localSubnetBuilder.build(); Set externalPorts = new HashSet<>(); @@ -1165,7 +1196,7 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { EndpointL3Prefix l3Prefix = l3PrefixBuilder.build(); List l3ApplyActions = new ArrayList<>(); - l3ApplyActions.add(setDlDstAction(new MacAddress(MAC_0))); + l3ApplyActions.add(setDlDstAction(MAC_0)); l3ApplyActions.add(decNwTtlAction()); List applyActions = new ArrayList<>(); applyActions.add(nxLoadRegAction(NxmNxReg2.class, BigInteger.valueOf(1))); @@ -1185,8 +1216,8 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { instructionsBuilder.setInstruction(l3instructions); MatchBuilder matchBuilder = new MatchBuilder().setEthernetMatch(ethernetMatch(null, - new MacAddress(DestinationMapper.ROUTER_MAC), IPv6)); - addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg6.class, (long) 0)); + DestinationMapper.ROUTER_MAC, IPv6)); + addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg6.class, (long) 5)); Match match = matchBuilder.build(); Integer prefixLength = Integer.valueOf(l3Prefix.getIpPrefix().getIpv6Prefix().getValue().split("/")[1]); @@ -1200,7 +1231,7 @@ public class DestinationMapperFlowsTest extends MapperUtilsTest { flows.createL3PrefixFlow(tableId, 30, gatewayEpBuilder.build(), l3Prefix, tenant, localSubnet, externalPorts, ofWriter); - verify(ctx, times(4)).getTenant(any(TenantId.class)); + verify(ctx, times(6)).getTenant(any(TenantId.class)); verify(ctx, times(3)).getEndpointManager(); verify(ctx, times(2)).getCurrentPolicy(); verify(ofWriter, times(1)).writeFlow(any(NodeId.class), anyShort(), eq(flow)); diff --git a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/destination/DestinationMapperTest.java b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/destination/DestinationMapperTest.java index 40b3d0840..38155b74f 100644 --- a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/destination/DestinationMapperTest.java +++ b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/destination/DestinationMapperTest.java @@ -19,6 +19,8 @@ import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types. import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ContextId; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2BridgeDomainId; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2FloodDomainId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L3ContextId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.NetworkDomainId; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.SubnetId; @@ -37,6 +39,10 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.TenantBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.ForwardingContextBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.PolicyBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2BridgeDomain; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2BridgeDomainBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2FloodDomain; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2FloodDomainBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L3Context; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L3ContextBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.Subnet; @@ -90,7 +96,7 @@ public class DestinationMapperTest extends MapperUtilsTest { destinationMapper.syncFlows(flows, endpointBuilder.build(), null, ofWriter); // Verify usage - verify(ctx, times(2)).getTenant(any(TenantId.class)); + verify(ctx, times(3)).getTenant(any(TenantId.class)); verify(ctx, times(5)).getEndpointManager(); verify(ctx, times(2)).getPolicyManager(); verify(ctx, times(2)).getCurrentPolicy(); @@ -113,6 +119,7 @@ public class DestinationMapperTest extends MapperUtilsTest { EndpointBuilder endpointBuilder = buildEndpoint(IPV4_1, MAC_1, CONNECTOR_1); // Peer endpoint EndpointBuilder peerEndpointBuilder = buildEndpoint(IPV4_2, MAC_0, CONNECTOR_0); + peerEndpointBuilder.setNetworkContainment(new SubnetId(SUBNET_1)); // External Implicit groups List externalImplicitGroups = new ArrayList<>(); ExternalImplicitGroupBuilder externalImplicitGroupBuilder = new ExternalImplicitGroupBuilder(); @@ -140,8 +147,8 @@ public class DestinationMapperTest extends MapperUtilsTest { destinationMapper.syncEndpointFlows(flows, NODE_ID, endpointBuilder.build(), ofWriter); // Verify usage - verify(ctx, times(11)).getTenant(any(TenantId.class)); - verify(ctx, times(6)).getEndpointManager(); + verify(ctx, times(14)).getTenant(any(TenantId.class)); + verify(ctx, times(7)).getEndpointManager(); verify(ctx, times(1)).getPolicyManager(); verify(ctx, times(4)).getCurrentPolicy(); verify(flows, times(1)).createExternalL2Flow(anyShort(), anyInt(), any(Endpoint.class), @@ -166,11 +173,9 @@ public class DestinationMapperTest extends MapperUtilsTest { // Endpoint EndpointBuilder endpointBuilder = buildEndpoint(IPV4_1, MAC_1, CONNECTOR_1); endpointBuilder.setL3Address(getL3AddressList(IPV4_1, L3C_ID)); - endpointBuilder.setNetworkContainment(new NetworkDomainId(SUBNET_0)); Endpoint endpoint = endpointBuilder.build(); // Peer EndpointBuilder peerEndpointBuilder = buildEndpoint(IPV4_2, MAC_0, CONNECTOR_0); - peerEndpointBuilder.setNetworkContainment(new NetworkDomainId(SUBNET_0)); // External implicit groups List subnets = new ArrayList<>(); SubnetBuilder subnetBuilder = new SubnetBuilder(); @@ -190,14 +195,13 @@ public class DestinationMapperTest extends MapperUtilsTest { forwardingContextBuilder.setSubnet(subnets); forwardingContextBuilder.setL3Context(l3Contexts); TenantBuilder peerTenantBuilder = buildTenant(); - peerTenantBuilder.setForwardingContext(forwardingContextBuilder.build()); + peerTenantBuilder.setForwardingContext(buildTenant().getForwardingContext()); peerTenantBuilder.setPolicy(new PolicyBuilder() .setSubjectFeatureInstances(getSubjectFeatureInstances()) .setEndpointGroup(getEndpointGroups()) .setExternalImplicitGroup(externalImplicitGroups) .build()); Tenant peerTenant = peerTenantBuilder.build(); - peerEndpointBuilder.setNetworkContainment(new NetworkDomainId(SUBNET_1)); Endpoint peerEndpoint = peerEndpointBuilder.build(); Collection peerEndpoints = new ArrayList<>(); peerEndpoints.add(peerEndpoint); @@ -218,7 +222,7 @@ public class DestinationMapperTest extends MapperUtilsTest { destinationMapper.syncEndpointFlows(flows, NODE_ID, endpoint, ofWriter); // Verify usage - verify(ctx, times(13)).getTenant(any(TenantId.class)); + verify(ctx, times(16)).getTenant(any(TenantId.class)); verify(ctx, times(9)).getEndpointManager(); verify(ctx, times(1)).getPolicyManager(); verify(ctx, times(4)).getCurrentPolicy(); @@ -234,24 +238,40 @@ public class DestinationMapperTest extends MapperUtilsTest { endpointBuilder.setNetworkContainment(SUBNET_0); // Peer EndpointBuilder peerEndpointBuilder = buildEndpoint(IPV4_2, MAC_0, CONNECTOR_0); + peerEndpointBuilder.setNetworkContainment(new NetworkDomainId(SUBNET_0)); // Subnets, l3Context and forwarding context - List subnets = new ArrayList<>(); - SubnetBuilder subnetBuilder = new SubnetBuilder(); - subnetBuilder.setId(new SubnetId(SUBNET_0)); - subnetBuilder.setParent(new ContextId(L3C_ID)); - subnetBuilder.setVirtualRouterIp(new IpAddress(new Ipv4Address(IPV4_2))); - subnets.add(subnetBuilder.build()); List l3Contexts = new ArrayList<>(); L3ContextBuilder l3ContextBuilder = new L3ContextBuilder(); l3ContextBuilder.setId(L3C_ID); l3Contexts.add(l3ContextBuilder.build()); + + List l2BDomains = new ArrayList<>(); + L2BridgeDomainBuilder l2bdBuilder = new L2BridgeDomainBuilder(); + l2bdBuilder.setId(L2BD_ID); + l2bdBuilder.setParent(L3C_ID); + l2BDomains.add(l2bdBuilder.build()); + + List l2FDomains = new ArrayList<>(); + L2FloodDomainBuilder l2fdBuilder = new L2FloodDomainBuilder(); + l2fdBuilder.setId(L2FD_ID); + l2fdBuilder.setParent(L2BD_ID); + l2FDomains.add(l2fdBuilder.build()); + + List subnets = new ArrayList<>(); + SubnetBuilder subnetBuilder = new SubnetBuilder(); + subnetBuilder.setId(SUBNET_0); + subnetBuilder.setParent(L2FD_ID); + subnetBuilder.setVirtualRouterIp(new IpAddress(IPV4_2)); + subnets.add(subnetBuilder.build()); + ForwardingContextBuilder forwardingContextBuilder = new ForwardingContextBuilder(); forwardingContextBuilder.setSubnet(subnets); forwardingContextBuilder.setL3Context(l3Contexts); + forwardingContextBuilder.setL2BridgeDomain(l2BDomains); + forwardingContextBuilder.setL2FloodDomain(l2FDomains); TenantBuilder peerTenantBuilder = new TenantBuilder(getTestIndexedTenant().getTenant()); - peerTenantBuilder.setForwardingContext(forwardingContextBuilder.build()); + peerTenantBuilder.setForwardingContext(buildTenant().getForwardingContext()); Tenant peerTenant = peerTenantBuilder.build(); - peerEndpointBuilder.setNetworkContainment(new NetworkDomainId(SUBNET_0)); Endpoint peerEndpoint = peerEndpointBuilder.build(); Collection peerEndpoints = new ArrayList<>(); peerEndpoints.add(peerEndpoint); @@ -266,7 +286,7 @@ public class DestinationMapperTest extends MapperUtilsTest { destinationMapper.syncFlows(flows, endpointBuilder.build(), NODE_ID, ofWriter); // Verify usage - verify(ctx, times(18)).getTenant(any(TenantId.class)); + verify(ctx, times(24)).getTenant(any(TenantId.class)); verify(ctx, times(9)).getEndpointManager(); verify(ctx, times(2)).getPolicyManager(); verify(ctx, times(4)).getCurrentPolicy(); @@ -286,19 +306,32 @@ public class DestinationMapperTest extends MapperUtilsTest { // Peer EndpointBuilder peerEndpointBuilder = buildEndpoint(IPV4_2, MAC_0, CONNECTOR_0); // Subnets, l3Context and forwarding context - List subnets = new ArrayList<>(); - SubnetBuilder subnetBuilder = new SubnetBuilder(); - subnetBuilder.setId(new SubnetId(SUBNET_0)); - subnetBuilder.setParent(new ContextId(L3C_ID)); - subnetBuilder.setVirtualRouterIp(new IpAddress(new Ipv4Address(IPV4_2))); - subnets.add(subnetBuilder.build()); + List l3Contexts = new ArrayList<>(); L3ContextBuilder l3ContextBuilder = new L3ContextBuilder(); l3ContextBuilder.setId(L3C_ID); l3Contexts.add(l3ContextBuilder.build()); + List l2BDomains = new ArrayList<>(); + L2BridgeDomainBuilder l2bdBuilder = new L2BridgeDomainBuilder(); + l2bdBuilder.setId(L2BD_ID); + l2bdBuilder.setParent(L3C_ID); + l2BDomains.add(l2bdBuilder.build()); + List l2FDomains = new ArrayList<>(); + L2FloodDomainBuilder l2fdBuilder = new L2FloodDomainBuilder(); + l2fdBuilder.setId(L2FD_ID); + l2fdBuilder.setParent(L2BD_ID); + l2FDomains.add(l2fdBuilder.build()); + List subnets = new ArrayList<>(); + SubnetBuilder subnetBuilder = new SubnetBuilder(); + subnetBuilder.setId(SUBNET_0); + subnetBuilder.setParent(L2FD_ID); + subnetBuilder.setVirtualRouterIp(new IpAddress(IPV4_2)); + subnets.add(subnetBuilder.build()); ForwardingContextBuilder forwardingContextBuilder = new ForwardingContextBuilder(); forwardingContextBuilder.setSubnet(subnets); forwardingContextBuilder.setL3Context(l3Contexts); + forwardingContextBuilder.setL2BridgeDomain(l2BDomains); + forwardingContextBuilder.setL2FloodDomain(l2FDomains); TenantBuilder peerTenantBuilder = buildTenant(); peerTenantBuilder.setForwardingContext(forwardingContextBuilder.build()); Tenant peerTenant = peerTenantBuilder.build(); @@ -306,7 +339,8 @@ public class DestinationMapperTest extends MapperUtilsTest { OfOverlayContextBuilder ofOverlayContextBuilder = new OfOverlayContextBuilder(); ofOverlayContextBuilder.setNodeConnectorId(new NodeConnectorId(CONNECTOR_0)); ofOverlayContextBuilder.setNodeId(new NodeId("remoteNodeID")); - peerEndpointBuilder.setNetworkContainment(new NetworkDomainId(SUBNET_0)); + peerEndpointBuilder.setNetworkContainment(SUBNET_0); + endpointBuilder.setNetworkContainment(SUBNET_0); peerEndpointBuilder.addAugmentation(OfOverlayContext.class, ofOverlayContextBuilder.build()); Endpoint peerEndpoint = peerEndpointBuilder.build(); Collection peerEndpoints = new ArrayList<>(); @@ -327,8 +361,8 @@ public class DestinationMapperTest extends MapperUtilsTest { destinationMapper.syncEndpointFlows(flows, NODE_ID, endpointBuilder.build(), ofWriter); // Verify usage - verify(ctx, times(13)).getTenant(any(TenantId.class)); - verify(ctx, times(5)).getEndpointManager(); + verify(ctx, times(15)).getTenant(any(TenantId.class)); + verify(ctx, times(6)).getEndpointManager(); verify(ctx, times(1)).getPolicyManager(); verify(ctx, times(3)).getCurrentPolicy(); @@ -350,14 +384,26 @@ public class DestinationMapperTest extends MapperUtilsTest { l3ContextBuilder.setId(L3C_ID); l3Contexts.add(l3ContextBuilder.build()); HashSet subnets = new HashSet<>(); + List l2BDomains = new ArrayList<>(); + L2BridgeDomainBuilder l2bdBuilder = new L2BridgeDomainBuilder(); + l2bdBuilder.setId(L2BD_ID); + l2bdBuilder.setParent(L3C_ID); + l2BDomains.add(l2bdBuilder.build()); + List l2FDomains = new ArrayList<>(); + L2FloodDomainBuilder l2fdBuilder = new L2FloodDomainBuilder(); + l2fdBuilder.setId(L2FD_ID); + l2fdBuilder.setParent(L2BD_ID); + l2FDomains.add(l2fdBuilder.build()); SubnetBuilder subnetBuilder = new SubnetBuilder(); - subnetBuilder.setId(new SubnetId(SUBNET_0)); - subnetBuilder.setParent(new ContextId(L3C_ID)); - subnetBuilder.setVirtualRouterIp(new IpAddress(new Ipv4Address(IPV4_2))); + subnetBuilder.setId(SUBNET_0); + subnetBuilder.setParent(L2FD_ID); + subnetBuilder.setVirtualRouterIp(new IpAddress(IPV4_2)); subnets.add(subnetBuilder.build()); ForwardingContextBuilder forwardingContextBuilder = new ForwardingContextBuilder(); forwardingContextBuilder.setSubnet(new ArrayList<>(subnets)); forwardingContextBuilder.setL3Context(l3Contexts); + forwardingContextBuilder.setL2BridgeDomain(l2BDomains); + forwardingContextBuilder.setL2FloodDomain(l2FDomains); TenantBuilder tenantBuilder = buildTenant(); tenantBuilder.setForwardingContext(forwardingContextBuilder.build()); Tenant tenant = tenantBuilder.build(); @@ -379,21 +425,34 @@ public class DestinationMapperTest extends MapperUtilsTest { L3ContextBuilder l3ContextBuilder = new L3ContextBuilder(); l3ContextBuilder.setId(L3C_ID); l3Contexts.add(l3ContextBuilder.build()); + List l2BDomains = new ArrayList<>(); + L2BridgeDomainBuilder l2bdBuilder = new L2BridgeDomainBuilder(); + l2bdBuilder.setId(L2BD_ID); + l2bdBuilder.setParent(L3C_ID); + l2BDomains.add(l2bdBuilder.build()); + List l2FDomains = new ArrayList<>(); + L2FloodDomainBuilder l2fdBuilder = new L2FloodDomainBuilder(); + l2fdBuilder.setId(L2FD_ID); + l2fdBuilder.setParent(L2BD_ID); + l2FDomains.add(l2fdBuilder.build()); HashSet subnets = new HashSet<>(); SubnetBuilder subnetBuilder = new SubnetBuilder(); - subnetBuilder.setId(new SubnetId(SUBNET_0)); - subnetBuilder.setParent(new ContextId(L3C_ID)); + subnetBuilder.setId(SUBNET_0); + subnetBuilder.setParent(L2FD_ID); subnetBuilder.setVirtualRouterIp(new IpAddress(IPV4_2)); subnets.add(subnetBuilder.build()); + ForwardingContextBuilder forwardingContextBuilder = new ForwardingContextBuilder(); forwardingContextBuilder.setL3Context(l3Contexts); forwardingContextBuilder.setSubnet(new ArrayList<>(subnets)); + forwardingContextBuilder.setL2BridgeDomain(l2BDomains); + forwardingContextBuilder.setL2FloodDomain(l2FDomains); TenantBuilder tenantBuilder = buildTenant(); tenantBuilder.setForwardingContext(forwardingContextBuilder.build()); Tenant tenant = tenantBuilder.build(); Collection endpoints = new ArrayList<>(); EndpointBuilder endpointBuilder = buildEndpoint(IPV4_1, MAC_1, CONNECTOR_1); - endpointBuilder.setNetworkContainment(new NetworkDomainId(SUBNET_0)); + endpointBuilder.setNetworkContainment(SUBNET_0); Endpoint endpoint = endpointBuilder.build(); endpoints.add(endpoint); @@ -421,7 +480,7 @@ public class DestinationMapperTest extends MapperUtilsTest { destinationMapper.syncL3PrefixFlow(flows, l3Prefixes, null, NODE_ID, ofWriter); - verify(ctx, times(5)).getTenant(any(TenantId.class)); + verify(ctx, times(6)).getTenant(any(TenantId.class)); verify(ctx, times(4)).getEndpointManager(); verify(ctx, times(1)).getSwitchManager(); verify(ctx, times(1)).getPolicyManager(); diff --git a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/destination/DestinationMapperUtilsTest.java b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/destination/DestinationMapperUtilsTest.java index 1702c9ff6..fcc8da389 100644 --- a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/destination/DestinationMapperUtilsTest.java +++ b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/destination/DestinationMapperUtilsTest.java @@ -97,7 +97,8 @@ public class DestinationMapperUtilsTest extends MapperUtilsTest { @Test public void getL3ContextForSubnet_l3Context() { SubnetBuilder subnetBuilder = new SubnetBuilder(); - subnetBuilder.setId(new SubnetId(L3C_ID)); + subnetBuilder.setId(SUBNET_0); + subnetBuilder.setParent(L2FD_ID); // expected result L3ContextBuilder expectedL3Context = new L3ContextBuilder(); @@ -148,9 +149,7 @@ public class DestinationMapperUtilsTest extends MapperUtilsTest { TenantBuilder tenantBuilder = new TenantBuilder(buildTenant().build()); Tenant tenant = tenantBuilder.build(); epWithSubnet.setTenant(tenant.getId()); - epWithSubnet.setNetworkContainment(new NetworkDomainId(SUBNET_0)); epWithSubnet.setTenant(tenant.getId()); - epWithSubnet.setNetworkContainment(new NetworkDomainId(SUBNET_1)); endpoints.add(epWithoutSubnet.build()); endpoints.add(epWithSubnet.build()); @@ -316,7 +315,7 @@ public class DestinationMapperUtilsTest extends MapperUtilsTest { OrdinalFactory.EndpointFwdCtxOrdinals ordinals = utils.getEndpointOrdinals(endpointBuilder.build()); assertEquals(ordinals.getEp().toString(), new EpKey(new L2ContextId(L2BD_ID), new MacAddress(MAC_0)).toString()); - assertEquals(ordinals.getNetworkContainment(), NET_DOMAIN_ID); + assertEquals(ordinals.getNetworkContainment(), SUBNET_0); } @Test diff --git a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/external/ExternalMapperTest.java b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/external/ExternalMapperTest.java index 4a4403b4e..144b481c4 100755 --- a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/external/ExternalMapperTest.java +++ b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/external/ExternalMapperTest.java @@ -103,7 +103,6 @@ public class ExternalMapperTest extends MapperUtilsTest { Tenant tenant = tenantBuilder.build(); // L2 Endpoint EndpointBuilder endpointBuilder = buildEndpoint(IPV4_0, MAC_0, CONNECTOR_0) - .setNetworkContainment(L2_FD_ID_EXT) .setL2Context(L2BD_ID); // L3 Endpoint with Nat EndpointL3Builder endpointL3Builder = buildL3Endpoint(natAddr, IPV4_1, MAC_0, null) @@ -122,7 +121,7 @@ public class ExternalMapperTest extends MapperUtilsTest { mapper.sync(endpointBuilder.build(), ofWriter); - verify(ofWriter, times(4)).writeFlow(any(NodeId.class), any(Short.class), any(Flow.class)); + verify(ofWriter, times(3)).writeFlow(any(NodeId.class), any(Short.class), any(Flow.class)); } @Test @@ -132,6 +131,8 @@ public class ExternalMapperTest extends MapperUtilsTest { when(ctx.getEndpointManager()).thenReturn(endpointManager); when(ctx.getTenant(any(TenantId.class))).thenReturn(getTestIndexedTenant()); + when(ctx.getCurrentPolicy()).thenReturn(policyInfo); + when(ctx.getSwitchManager()).thenReturn(switchManager); when(endpointManager.getEndpointNodeId(any(Endpoint.class))).thenReturn(NODE_ID); mapper.sync(endpointBuilder.build(), ofWriter); diff --git a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/ingressnat/IngressNatMapperFlowsTest.java b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/ingressnat/IngressNatMapperFlowsTest.java index 3d3438383..23a310fa0 100755 --- a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/ingressnat/IngressNatMapperFlowsTest.java +++ b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/ingressnat/IngressNatMapperFlowsTest.java @@ -95,7 +95,7 @@ public class IngressNatMapperFlowsTest extends MapperUtilsTest { InOrder order = inOrder(ctx); order.verify(ctx, times(1)).getEndpointManager(); order.verify(ctx, times(1)).getCurrentPolicy(); - verify(ctx, times(2)).getTenant(TENANT_ID); + verify(ctx, times(3)).getTenant(TENANT_ID); assertNotNull(ordinals); List instructions = new ArrayList<>(); @@ -103,9 +103,9 @@ public class IngressNatMapperFlowsTest extends MapperUtilsTest { FlowUtils.setDlDstAction(new MacAddress(MAC_0))}; Action[] ordinalsAction = {FlowUtils.nxLoadRegAction(NxmNxReg0.class, BigInteger.valueOf(1)), FlowUtils.nxLoadRegAction(NxmNxReg1.class, BigInteger.valueOf(0)), - FlowUtils.nxLoadRegAction(NxmNxReg4.class, BigInteger.valueOf(0)), - FlowUtils.nxLoadRegAction(NxmNxReg5.class, BigInteger.valueOf(0)), - FlowUtils.nxLoadRegAction(NxmNxReg6.class, BigInteger.valueOf(0)), + FlowUtils.nxLoadRegAction(NxmNxReg4.class, BigInteger.valueOf(3)), + FlowUtils.nxLoadRegAction(NxmNxReg5.class, BigInteger.valueOf(4)), + FlowUtils.nxLoadRegAction(NxmNxReg6.class, BigInteger.valueOf(5)), FlowUtils.nxLoadTunIdAction(BigInteger.valueOf(ordinals.getTunnelId()), false)}; instructions.add(new InstructionBuilder().setOrder(0) .setInstruction(FlowUtils.applyActionIns(ArrayUtils.addAll(ipActions, ordinalsAction))).build()); @@ -172,15 +172,15 @@ public class IngressNatMapperFlowsTest extends MapperUtilsTest { InOrder order = inOrder(ctx); order.verify(ctx, times(1)).getEndpointManager(); order.verify(ctx, times(1)).getCurrentPolicy(); - verify(ctx, times(2)).getTenant(TENANT_ID); + verify(ctx, times(3)).getTenant(TENANT_ID); assertNotNull(ordinals); List instructions = new ArrayList<>(); Action[] ordinalsAction = {FlowUtils.nxLoadRegAction(NxmNxReg0.class, BigInteger.valueOf(1)), FlowUtils.nxLoadRegAction(NxmNxReg1.class, BigInteger.valueOf(0)), - FlowUtils.nxLoadRegAction(NxmNxReg4.class, BigInteger.valueOf(0)), - FlowUtils.nxLoadRegAction(NxmNxReg5.class, BigInteger.valueOf(0)), - FlowUtils.nxLoadRegAction(NxmNxReg6.class, BigInteger.valueOf(0)), + FlowUtils.nxLoadRegAction(NxmNxReg4.class, BigInteger.valueOf(3)), + FlowUtils.nxLoadRegAction(NxmNxReg5.class, BigInteger.valueOf(4)), + FlowUtils.nxLoadRegAction(NxmNxReg6.class, BigInteger.valueOf(5)), FlowUtils.nxLoadTunIdAction(BigInteger.valueOf(ordinals.getTunnelId()), false)}; instructions.add(new InstructionBuilder().setOrder(0) .setInstruction(FlowUtils.applyActionIns(ArrayUtils.addAll(ordinalsAction))).build()); @@ -215,15 +215,15 @@ public class IngressNatMapperFlowsTest extends MapperUtilsTest { InOrder order = inOrder(ctx); order.verify(ctx, times(1)).getEndpointManager(); order.verify(ctx, times(1)).getCurrentPolicy(); - verify(ctx, times(2)).getTenant(TENANT_ID); + verify(ctx, times(3)).getTenant(TENANT_ID); assertNotNull(ordinals); List instructions = new ArrayList<>(); Action[] ordinalsAction = {FlowUtils.nxLoadRegAction(NxmNxReg0.class, BigInteger.valueOf(1)), FlowUtils.nxLoadRegAction(NxmNxReg1.class, BigInteger.valueOf(0)), - FlowUtils.nxLoadRegAction(NxmNxReg4.class, BigInteger.valueOf(0)), - FlowUtils.nxLoadRegAction(NxmNxReg5.class, BigInteger.valueOf(0)), - FlowUtils.nxLoadRegAction(NxmNxReg6.class, BigInteger.valueOf(0)), + FlowUtils.nxLoadRegAction(NxmNxReg4.class, BigInteger.valueOf(3)), + FlowUtils.nxLoadRegAction(NxmNxReg5.class, BigInteger.valueOf(4)), + FlowUtils.nxLoadRegAction(NxmNxReg6.class, BigInteger.valueOf(5)), FlowUtils.nxLoadTunIdAction(BigInteger.valueOf(ordinals.getTunnelId()), false)}; instructions.add(new InstructionBuilder().setOrder(0) .setInstruction(FlowUtils.applyActionIns(ArrayUtils.addAll(ordinalsAction))).build()); diff --git a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/source/SourceMapperFlowsTest.java b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/source/SourceMapperFlowsTest.java index 376563fd0..5b80c0a04 100755 --- a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/source/SourceMapperFlowsTest.java +++ b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/source/SourceMapperFlowsTest.java @@ -110,14 +110,14 @@ public class SourceMapperFlowsTest extends MapperUtilsTest { InOrder order = inOrder(ctx); order.verify(ctx, times(1)).getEndpointManager(); order.verify(ctx, times(1)).getCurrentPolicy(); - verify(ctx, times(2)).getTenant(TENANT_ID); + verify(ctx, times(3)).getTenant(TENANT_ID); assertNotNull(ordinals); Action reg0 = FlowUtils.nxLoadRegAction(NxmNxReg0.class, BigInteger.valueOf(1)); Action reg1 = FlowUtils.nxLoadRegAction(NxmNxReg1.class, BigInteger.valueOf(0)); - Action reg4 = FlowUtils.nxLoadRegAction(NxmNxReg4.class, BigInteger.valueOf(0)); - Action reg5 = FlowUtils.nxLoadRegAction(NxmNxReg5.class, BigInteger.valueOf(0)); - Action reg6 = FlowUtils.nxLoadRegAction(NxmNxReg6.class, BigInteger.valueOf(0)); + Action reg4 = FlowUtils.nxLoadRegAction(NxmNxReg4.class, BigInteger.valueOf(3)); + Action reg5 = FlowUtils.nxLoadRegAction(NxmNxReg5.class, BigInteger.valueOf(4)); + Action reg6 = FlowUtils.nxLoadRegAction(NxmNxReg6.class, BigInteger.valueOf(5)); Action tunnelId = FlowUtils.nxLoadTunIdAction(BigInteger.valueOf(ordinals.getTunnelId()), false); InstructionsBuilder instructionsBuilder = new InstructionsBuilder(); List instructions = new ArrayList<>(); @@ -155,14 +155,14 @@ public class SourceMapperFlowsTest extends MapperUtilsTest { InOrder order = inOrder(ctx); order.verify(ctx, times(1)).getEndpointManager(); order.verify(ctx, times(1)).getCurrentPolicy(); - verify(ctx, times(2)).getTenant(TENANT_ID); + verify(ctx, times(3)).getTenant(TENANT_ID); assertNotNull(ordinals); Action reg0 = FlowUtils.nxLoadRegAction(NxmNxReg0.class, BigInteger.valueOf(1)); Action reg1 = FlowUtils.nxLoadRegAction(NxmNxReg1.class, BigInteger.valueOf(0xffffff)); - Action reg4 = FlowUtils.nxLoadRegAction(NxmNxReg4.class, BigInteger.valueOf(0)); - Action reg5 = FlowUtils.nxLoadRegAction(NxmNxReg5.class, BigInteger.valueOf(0)); - Action reg6 = FlowUtils.nxLoadRegAction(NxmNxReg6.class, BigInteger.valueOf(0)); + Action reg4 = FlowUtils.nxLoadRegAction(NxmNxReg4.class, BigInteger.valueOf(3)); + Action reg5 = FlowUtils.nxLoadRegAction(NxmNxReg5.class, BigInteger.valueOf(4)); + Action reg6 = FlowUtils.nxLoadRegAction(NxmNxReg6.class, BigInteger.valueOf(5)); InstructionsBuilder instructionsBuilder = new InstructionsBuilder(); List instructions = new ArrayList<>(); InstructionBuilder ordinalsInstruction = new InstructionBuilder(); @@ -198,10 +198,10 @@ public class SourceMapperFlowsTest extends MapperUtilsTest { InOrder order = inOrder(ctx); order.verify(ctx, times(1)).getEndpointManager(); order.verify(ctx, times(1)).getCurrentPolicy(); - verify(ctx, times(2)).getTenant(TENANT_ID); + verify(ctx, times(3)).getTenant(TENANT_ID); assertNotNull(ordinals); - Action reg5 = FlowUtils.nxLoadRegAction(NxmNxReg5.class, BigInteger.valueOf(0)); + Action reg5 = FlowUtils.nxLoadRegAction(NxmNxReg5.class, BigInteger.valueOf(4)); InstructionsBuilder instructionsBuilder = new InstructionsBuilder(); List instructions = new ArrayList<>(); InstructionBuilder ordinalsInstruction = new InstructionBuilder(); @@ -214,7 +214,7 @@ public class SourceMapperFlowsTest extends MapperUtilsTest { MatchBuilder matchBuilder = new MatchBuilder(); matchBuilder.setInPort(new NodeConnectorId(CONNECTOR_1)); - FlowUtils.addNxTunIdMatch(matchBuilder, 0); + FlowUtils.addNxTunIdMatch(matchBuilder, 4); Match match = matchBuilder.build(); Flow testFlow = buildFlow(FlowIdUtils.newFlowId(tableId, "tunnelFdId", match), tableId, 80, match, diff --git a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/source/SourceMapperTest.java b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/source/SourceMapperTest.java index 0b61f1899..e68c1fd3f 100644 --- a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/source/SourceMapperTest.java +++ b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/mapper/source/SourceMapperTest.java @@ -52,8 +52,7 @@ public class SourceMapperTest extends MapperUtilsTest { // List of other endpoints (one entry is good enough) HashSet otherEndpoints = new HashSet<>(); Endpoint otherEndpoint = buildEndpoint(IPV4_1, MAC_1, CONNECTOR_1).build(); - EndpointBuilder otherEndpointBuilder = new EndpointBuilder(otherEndpoint); - otherEndpointBuilder.setEndpointGroup(ENDPOINT_GROUP_0); + EndpointBuilder otherEndpointBuilder = new EndpointBuilder(otherEndpoint).setEndpointGroup(ENDPOINT_GROUP_0); List endpointGroupIds = new ArrayList<>(); endpointGroupIds.add(ENDPOINT_GROUP_1); endpointGroupIds.add(ENDPOINT_GROUP_2); @@ -82,7 +81,7 @@ public class SourceMapperTest extends MapperUtilsTest { // Verify method usage verify(ctx, times(3)).getEndpointManager(); - verify(ctx, times(5)).getTenant(Mockito.any(TenantId.class)); + verify(ctx, times(7)).getTenant(Mockito.any(TenantId.class)); verify(ctx.getPolicyManager(), times(1)).getTABLEID_DESTINATION_MAPPER(); verify(ctx.getSwitchManager(), times(1)).getTunnelPort(NODE_ID, TunnelTypeVxlan.class); verify(ctx.getEndpointManager(), times(1)).getEndpointsForGroup(Mockito.any(EgKey.class)); @@ -126,7 +125,7 @@ public class SourceMapperTest extends MapperUtilsTest { sourceMapper.syncFlows(flows, endpointBuilder.build(), NODE_ID, ofWriter); // Verify OfContext method usage - verify(ctx, times(3)).getTenant(Mockito.any(TenantId.class)); + verify(ctx, times(4)).getTenant(Mockito.any(TenantId.class)); verify(ctx.getPolicyManager(), times(1)).getTABLEID_DESTINATION_MAPPER(); verify(ctx.getSwitchManager(), times(1)).getTunnelPort(NODE_ID, TunnelTypeVxlan.class); -- 2.36.6