Merge "Changes to LogicalSwitchUpdate as per new yang"
authorSam Hague <shague@redhat.com>
Wed, 25 Nov 2015 14:45:57 +0000 (14:45 +0000)
committerGerrit Code Review <gerrit@opendaylight.org>
Wed, 25 Nov 2015 14:45:57 +0000 (14:45 +0000)
openstack/net-virt-it/pom.xml
openstack/net-virt-it/src/test/java/org/opendaylight/ovsdb/openstack/netvirt/it/NetvirtIT.java
openstack/net-virt-it/src/test/java/org/opendaylight/ovsdb/openstack/netvirt/it/NetvirtITConstants.java
openstack/net-virt-providers/src/main/java/org/opendaylight/ovsdb/openstack/netvirt/providers/openflow13/OF13Provider.java
openstack/net-virt-providers/src/main/java/org/opendaylight/ovsdb/openstack/netvirt/providers/openflow13/services/L2ForwardingService.java
openstack/net-virt/src/main/java/org/opendaylight/ovsdb/openstack/netvirt/api/SecurityServicesManager.java
openstack/net-virt/src/main/java/org/opendaylight/ovsdb/openstack/netvirt/impl/SecurityServicesImpl.java
openstack/net-virt/src/test/java/org/opendaylight/ovsdb/openstack/netvirt/impl/SecurityGroupCacheManagerImplTest.java [new file with mode: 0644]
openstack/net-virt/src/test/java/org/opendaylight/ovsdb/openstack/netvirt/impl/SecurityServicesImplTest.java
utils/mdsal-openflow/src/main/java/org/opendaylight/ovsdb/utils/mdsal/openflow/FlowUtils.java
utils/mdsal-openflow/src/main/java/org/opendaylight/ovsdb/utils/mdsal/openflow/InstructionUtils.java

index 4bf8c654b5455ea490664f375b9b040e743c0df0..45699700631e75cf822ff6fa19e6a8a19b573fdc 100644 (file)
@@ -40,6 +40,14 @@ and is available at http://www.eclipse.org/legal/epl-v10.html
     <tag>HEAD</tag>
     <url>https://wiki.opendaylight.org/view/OVSDB_Integration:Main</url>
   </scm>
+
+  <properties>
+    <karaf.distro.groupId>org.opendaylight.ovsdb</karaf.distro.groupId>
+    <karaf.distro.artifactId>karaf</karaf.distro.artifactId>
+    <karaf.distro.version>${project.version}</karaf.distro.version>
+    <karaf.distro.type>zip</karaf.distro.type>
+  </properties>
+
   <dependencyManagement>
     <dependencies>
       <dependency>
@@ -85,61 +93,11 @@ and is available at http://www.eclipse.org/legal/epl-v10.html
       <groupId>org.opendaylight.controller</groupId>
       <artifactId>config-util</artifactId>
     </dependency>
-    <!-- Dependencies for pax exam karaf container -->
-    <dependency>
-      <groupId>org.ops4j.pax.exam</groupId>
-      <artifactId>pax-exam-container-karaf</artifactId>
-      <scope>compile</scope>
-    </dependency>
-    <dependency>
-      <groupId>org.ops4j.pax.exam</groupId>
-      <artifactId>pax-exam-junit4</artifactId>
-      <scope>compile</scope>
-    </dependency>
-    <dependency>
-      <groupId>org.ops4j.pax.exam</groupId>
-      <artifactId>pax-exam</artifactId>
-      <scope>compile</scope>
-    </dependency>
-    <dependency>
-      <groupId>org.ops4j.pax.url</groupId>
-      <artifactId>pax-url-aether</artifactId>
-      <scope>compile</scope>
-    </dependency>
-    <dependency>
-      <groupId>javax.inject</groupId>
-      <artifactId>javax.inject</artifactId>
-      <version>1</version>
-      <scope>compile</scope>
-    </dependency>
-    <dependency>
-      <groupId>org.apache.karaf.features</groupId>
-      <artifactId>org.apache.karaf.features.core</artifactId>
-      <version>${karaf.version}</version>
-      <scope>compile</scope>
-    </dependency>
-    <dependency>
-      <groupId>org.osgi</groupId>
-      <artifactId>org.osgi.core</artifactId>
-      <scope>compile</scope>
-    </dependency>
-    <dependency>
-      <groupId>junit</groupId>
-      <artifactId>junit</artifactId>
-      <scope>compile</scope>
-    </dependency>
     <dependency>
       <groupId>org.codehaus.sonar-plugins.java</groupId>
       <artifactId>sonar-jacoco-listeners</artifactId>
       <scope>test</scope>
     </dependency>
-    <!-- AbstractConfigTestBase::getKarafDistro() needs this to find its version -->
-    <dependency>
-      <groupId>org.opendaylight.ovsdb</groupId>
-      <artifactId>karaf</artifactId>
-      <version>${project.version}</version>
-      <scope>test</scope>
-    </dependency>
   </dependencies>
   <build>
     <plugins>
@@ -155,40 +113,6 @@ and is available at http://www.eclipse.org/legal/epl-v10.html
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-failsafe-plugin</artifactId>
       </plugin>
-      <!-- Needed if you use versionAsInProject() -->
-      <plugin>
-        <groupId>org.apache.servicemix.tooling</groupId>
-        <artifactId>depends-maven-plugin</artifactId>
-        <version>1.2</version>
-        <executions>
-          <execution>
-            <id>generate-depends-file</id>
-            <goals>
-              <goal>generate-depends-file</goal>
-            </goals>
-          </execution>
-        </executions>
-      </plugin>
     </plugins>
   </build>
-  <profiles>
-    <profile>
-      <id>default</id>
-      <activation>
-        <activeByDefault>true</activeByDefault>
-      </activation>
-      <properties>
-        <skipITs>true</skipITs>
-      </properties>
-    </profile>
-    <profile>
-      <id>integrationtest</id>
-      <activation>
-        <activeByDefault>false</activeByDefault>
-      </activation>
-      <properties>
-        <skipITs>false</skipITs>
-      </properties>
-    </profile>
-  </profiles>
 </project>
index 5c6181941e682e9f8f32ee9142f78eda111248c5..d335bfa6765694408e31655a38ffb204b32bf20e 100644 (file)
@@ -10,22 +10,22 @@ package org.opendaylight.ovsdb.openstack.netvirt.it;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotEquals;
 import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 import static org.ops4j.pax.exam.CoreOptions.composite;
 import static org.ops4j.pax.exam.CoreOptions.maven;
 import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
+import static org.ops4j.pax.exam.CoreOptions.propagateSystemProperties;
 import static org.ops4j.pax.exam.CoreOptions.vmOption;
-import static org.ops4j.pax.exam.CoreOptions.when;
 import static org.ops4j.pax.exam.CoreOptions.wrappedBundle;
 import static org.ops4j.pax.exam.MavenUtils.asInProject;
+import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.configureConsole;
 import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.editConfigurationFilePut;
-import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.karafDistributionConfiguration;
 import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.keepRuntimeFolder;
 
 import com.google.common.collect.ImmutableBiMap;
 import com.google.common.collect.Lists;
 
-import java.io.File;
 import java.net.InetAddress;
 import java.net.NetworkInterface;
 import java.net.UnknownHostException;
@@ -35,7 +35,6 @@ import java.util.List;
 import java.util.Map;
 import java.util.Properties;
 import java.util.concurrent.atomic.AtomicBoolean;
-import javax.inject.Inject;
 import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Ignore;
@@ -44,15 +43,19 @@ import org.junit.runner.RunWith;
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.controller.mdsal.it.base.AbstractMdsalTestBase;
+import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
+import org.opendaylight.ovsdb.openstack.netvirt.api.Constants;
 import org.opendaylight.ovsdb.openstack.netvirt.api.SecurityServicesManager;
 import org.opendaylight.ovsdb.openstack.netvirt.api.Southbound;
 import org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.AbstractServiceInstance;
 import org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.PipelineOrchestrator;
 import org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.Service;
+import org.opendaylight.ovsdb.utils.config.ConfigProperties;
 import org.opendaylight.ovsdb.utils.mdsal.openflow.FlowUtils;
 import org.opendaylight.ovsdb.utils.servicehelper.ServiceHelper;
 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.PortNumber;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Uri;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.*;
@@ -64,9 +67,14 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.re
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ConnectionInfo;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ConnectionInfoBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.InterfaceTypeEntryBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ManagerEntry;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.OpenvswitchOtherConfigs;
+import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
+import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TpId;
+import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
+import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPointBuilder;
@@ -75,13 +83,10 @@ import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.ops4j.pax.exam.Configuration;
 import org.ops4j.pax.exam.Option;
 import org.ops4j.pax.exam.junit.PaxExam;
-import org.ops4j.pax.exam.karaf.options.KarafDistributionOption;
 import org.ops4j.pax.exam.karaf.options.LogLevelOption;
 import org.ops4j.pax.exam.options.MavenUrlReference;
 import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
 import org.ops4j.pax.exam.spi.reactors.PerClass;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -99,63 +104,11 @@ public class NetvirtIT extends AbstractMdsalTestBase {
     private static String addressStr;
     private static String portStr;
     private static String connectionType;
+    private static String controllerStr;
     private static AtomicBoolean setup = new AtomicBoolean(false);
     private static MdsalUtils mdsalUtils = null;
     private static Southbound southbound = null;
-    private static final String NETVIRT = "org.opendaylight.ovsdb.openstack.net-virt";
-    private static final String NETVIRTPROVIDERS = "org.opendaylight.ovsdb.openstack.net-virt-providers";
-
-    // TODO Constants copied frmo AbstractConfigTestBase, need to be removed (see TODO below)
-    private static final String PAX_EXAM_UNPACK_DIRECTORY = "target/exam";
-    private static final String KARAF_DEBUG_PORT = "5005";
-    private static final String KARAF_DEBUG_PROP = "karaf.debug";
-    private static final String KEEP_UNPACK_DIRECTORY_PROP = "karaf.keep.unpack";
-
-    @Inject
-    private BundleContext bundleContext;
-
-    @Configuration
-    public Option[] config() {
-        // TODO Figure out how to use the parent Karaf setup, then just use super.config()
-        Option[] options = new Option[] {
-                when(Boolean.getBoolean(KARAF_DEBUG_PROP))
-                        .useOptions(KarafDistributionOption.debugConfiguration(KARAF_DEBUG_PORT, true)),
-                karafDistributionConfiguration().frameworkUrl(getKarafDistro())
-                        .unpackDirectory(new File(PAX_EXAM_UNPACK_DIRECTORY))
-                        .useDeployFolder(false),
-                when(Boolean.getBoolean(KEEP_UNPACK_DIRECTORY_PROP)).useOptions(keepRuntimeFolder()),
-                // Works only if we don't specify the feature repo and name
-                getLoggingOption()};
-        Option[] propertyOptions = getPropertiesOptions();
-        Option[] otherOptions = getOtherOptions();
-        Option[] combinedOptions = new Option[options.length + propertyOptions.length + otherOptions.length];
-        System.arraycopy(options, 0, combinedOptions, 0, options.length);
-        System.arraycopy(propertyOptions, 0, combinedOptions, options.length, propertyOptions.length);
-        System.arraycopy(otherOptions, 0, combinedOptions, options.length + propertyOptions.length,
-                otherOptions.length);
-        return combinedOptions;
-    }
-
-    private Option[] getOtherOptions() {
-        return new Option[] {
-                wrappedBundle(
-                        mavenBundle("org.opendaylight.ovsdb", "utils.mdsal-openflow")
-                                .version(asInProject())
-                                .type("jar")),
-                vmOption("-javaagent:../jars/org.jacoco.agent.jar=destfile=../../jacoco-it.exec"),
-                keepRuntimeFolder()
-        };
-    }
-
-    @Override
-    public String getKarafDistro() {
-        return maven()
-                .groupId("org.opendaylight.ovsdb")
-                .artifactId("karaf")
-                .versionAsInProject()
-                .type("zip")
-                .getURL();
-    }
+    private static final String NETVIRT_TOPOLOGY_ID = "netvirt:1";
 
     @Override
     public String getModuleName() {
@@ -182,10 +135,42 @@ public class NetvirtIT extends AbstractMdsalTestBase {
         return "odl-ovsdb-openstack";
     }
 
-    protected String usage() {
-        return "Integration Test needs a valid connection configuration as follows :\n"
-                + "active connection : mvn -Dovsdbserver.ipaddress=x.x.x.x -Dovsdbserver.port=yyyy verify\n"
-                + "passive connection : mvn -Dovsdbserver.connection=passive verify\n";
+    @Configuration
+    @Override
+    public Option[] config() {
+        Option[] parentOptions = super.config();
+        Option[] propertiesOptions = getPropertiesOptions();
+        Option[] otherOptions = getOtherOptions();
+        Option[] options = new Option[parentOptions.length + propertiesOptions.length + otherOptions.length];
+        System.arraycopy(parentOptions, 0, options, 0, parentOptions.length);
+        System.arraycopy(propertiesOptions, 0, options, parentOptions.length, propertiesOptions.length);
+        System.arraycopy(otherOptions, 0, options, parentOptions.length + propertiesOptions.length,
+                otherOptions.length);
+        return options;
+    }
+
+    private Option[] getOtherOptions() {
+        return new Option[] {
+                wrappedBundle(
+                        mavenBundle("org.opendaylight.ovsdb", "utils.mdsal-openflow")
+                                .version(asInProject())
+                                .type("jar")),
+                wrappedBundle(
+                        mavenBundle("org.opendaylight.ovsdb", "utils.config")
+                                .version(asInProject())
+                                .type("jar")),
+                configureConsole().startLocalConsole(),
+                vmOption("-javaagent:../jars/org.jacoco.agent.jar=destfile=../../jacoco-it.exec"),
+                keepRuntimeFolder()
+        };
+    }
+
+    public Option[] getPropertiesOptions() {
+        return new Option[] {
+                propagateSystemProperties(NetvirtITConstants.SERVER_IPADDRESS,
+                        NetvirtITConstants.SERVER_PORT, NetvirtITConstants.CONNECTION_TYPE,
+                        NetvirtITConstants.CONTROLLER_IPADDRESS),
+        };
     }
 
     @Override
@@ -194,32 +179,34 @@ public class NetvirtIT extends AbstractMdsalTestBase {
                 editConfigurationFilePut(NetvirtITConstants.ORG_OPS4J_PAX_LOGGING_CFG,
                         "log4j.logger.org.opendaylight.ovsdb",
                         LogLevelOption.LogLevel.TRACE.name()),
+                editConfigurationFilePut(ORG_OPS4J_PAX_LOGGING_CFG,
+                        logConfiguration(NetvirtIT.class),
+                        LogLevelOption.LogLevel.INFO.name()),
                 //editConfigurationFilePut(NetvirtITConstants.ORG_OPS4J_PAX_LOGGING_CFG,
                 //        "log4j.logger.org.opendaylight.ovsdb.lib",
                 //        LogLevelOption.LogLevel.INFO.name()),
                 super.getLoggingOption());
     }
 
-    private Option[] getPropertiesOptions() {
-        Properties props = new Properties(System.getProperties());
-        String addressStr = props.getProperty(NetvirtITConstants.SERVER_IPADDRESS,
-                NetvirtITConstants.DEFAULT_SERVER_IPADDRESS);
-        String portStr = props.getProperty(NetvirtITConstants.SERVER_PORT,
-                NetvirtITConstants.DEFAULT_SERVER_PORT);
-        String connectionType = props.getProperty(NetvirtITConstants.CONNECTION_TYPE,
-                NetvirtITConstants.CONNECTION_TYPE_ACTIVE);
-
-        LOG.info("getPropertiesOptions: Using the following properties: mode= {}, ip:port= {}:{}",
-                connectionType, addressStr, portStr);
+    protected String usage() {
+        return "Integration Test needs a valid connection configuration as follows :\n"
+                + "active connection : mvn -Dovsdbserver.ipaddress=x.x.x.x -Dovsdbserver.port=yyyy verify\n"
+                + "passive connection : mvn -Dovsdbserver.connection=passive verify\n";
+    }
 
-        return new Option[] {
-                editConfigurationFilePut(NetvirtITConstants.CUSTOM_PROPERTIES,
-                        NetvirtITConstants.SERVER_IPADDRESS, addressStr),
-                editConfigurationFilePut(NetvirtITConstants.CUSTOM_PROPERTIES,
-                        NetvirtITConstants.SERVER_PORT, portStr),
-                editConfigurationFilePut(NetvirtITConstants.CUSTOM_PROPERTIES,
-                        NetvirtITConstants.CONNECTION_TYPE, connectionType),
-        };
+    private void getProperties() {
+        Properties props = System.getProperties();
+        addressStr = props.getProperty(NetvirtITConstants.SERVER_IPADDRESS);
+        portStr = props.getProperty(NetvirtITConstants.SERVER_PORT, NetvirtITConstants.DEFAULT_SERVER_PORT);
+        connectionType = props.getProperty(NetvirtITConstants.CONNECTION_TYPE, "active");
+        controllerStr = props.getProperty(NetvirtITConstants.CONTROLLER_IPADDRESS);
+        LOG.info("setUp: Using the following properties: mode= {}, ip:port= {}:{}, controller ip: {}",
+                connectionType, addressStr, portStr, controllerStr);
+        if (connectionType.equalsIgnoreCase(NetvirtITConstants.CONNECTION_TYPE_ACTIVE)) {
+            if (addressStr == null) {
+                fail(usage());
+            }
+        }
     }
 
     @Before
@@ -236,40 +223,75 @@ public class NetvirtIT extends AbstractMdsalTestBase {
             e.printStackTrace();
         }
 
-        addressStr = bundleContext.getProperty(NetvirtITConstants.SERVER_IPADDRESS);
-        portStr = bundleContext.getProperty(NetvirtITConstants.SERVER_PORT);
-        connectionType = bundleContext.getProperty(NetvirtITConstants.CONNECTION_TYPE);
+        getProperties();
 
-        LOG.info("setUp: Using the following properties: mode= {}, ip:port= {}:{}",
-                connectionType, addressStr, portStr);
         if (connectionType.equalsIgnoreCase(NetvirtITConstants.CONNECTION_TYPE_ACTIVE)) {
             if (addressStr == null) {
                 fail(usage());
             }
         }
 
-        isBundleReady(bundleContext, NETVIRT);
-        isBundleReady(bundleContext, NETVIRTPROVIDERS);
-
-        //dataBroker = getSession().getSALService(DataBroker.class);
-        //Thread.sleep(3000);
-        //dataBroker = OvsdbInventoryServiceImpl.getDataBroker();
-        for (int i=0; i<20; i++) {
-            southbound = (Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this);
-            if (southbound != null) {
-                dataBroker = southbound.getDatabroker();
-                if (dataBroker != null) {
-                    break;
+        dataBroker = getDatabroker(getProviderContext());
+        mdsalUtils = new MdsalUtils(dataBroker);
+        assertNotNull("mdsalUtils should not be null", mdsalUtils);
+        assertTrue("Did not find " + NETVIRT_TOPOLOGY_ID, getNetvirtTopology());
+        southbound = (Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this);
+        assertNotNull("southbound should not be null", southbound);
+        setup.set(true);
+    }
+
+    private BindingAwareBroker.ProviderContext getProviderContext() {
+        BindingAwareBroker.ProviderContext providerContext = null;
+        for (int i=0; i < 60; i++) {
+            providerContext = getSession();
+            if (providerContext != null) {
+                break;
+            } else {
+                try {
+                    Thread.sleep(1000);
+                } catch (InterruptedException e) {
+                    e.printStackTrace();
                 }
             }
-            LOG.warn("NetvirtIT: dataBroker is null");
-            Thread.sleep(5000);
         }
-        Assert.assertNotNull("dataBroker should not be null", dataBroker);
-        Thread.sleep(5000);
-
-        mdsalUtils = new MdsalUtils(dataBroker);
-        setup.set(true);
+        assertNotNull("providercontext should not be null", providerContext);
+        /* One more second to let the provider finish initialization */
+        try {
+            Thread.sleep(1000);
+        } catch (InterruptedException e) {
+            e.printStackTrace();
+        }
+        return providerContext;
+    }
+
+    private DataBroker getDatabroker(BindingAwareBroker.ProviderContext providerContext) {
+        DataBroker dataBroker = providerContext.getSALService(DataBroker.class);
+        assertNotNull("dataBroker should not be null", dataBroker);
+        return dataBroker;
+    }
+
+    private Boolean getNetvirtTopology() {
+        LOG.info("getNetvirtTopology: looking for {}...", NETVIRT_TOPOLOGY_ID);
+        Boolean found = false;
+        final TopologyId topologyId = new TopologyId(new Uri(NETVIRT_TOPOLOGY_ID));
+        InstanceIdentifier<Topology> path =
+                InstanceIdentifier.create(NetworkTopology.class).child(Topology.class, new TopologyKey(topologyId));
+        for (int i = 0; i < 60; i++) {
+            Topology topology = mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, path);
+            if (topology != null) {
+                LOG.info("getNetvirtTopology: found {}...", NETVIRT_TOPOLOGY_ID);
+                found = true;
+                break;
+            } else {
+                LOG.info("getNetvirtTopology: still looking ({})...", i);
+                try {
+                    Thread.sleep(1000);
+                } catch (InterruptedException e) {
+                    e.printStackTrace();
+                }
+            }
+        }
+        return found;
     }
 
     /**
@@ -349,51 +371,136 @@ public class NetvirtIT extends AbstractMdsalTestBase {
         return true;
     }
 
+    private String getControllerIPAddress() {
+        String addressString = ConfigProperties.getProperty(this.getClass(), "ovsdb.controller.address");
+        if (addressString != null) {
+            try {
+                if (InetAddress.getByName(addressString) != null) {
+                    return addressString;
+                }
+            } catch (UnknownHostException e) {
+                LOG.error("Host {} is invalid", addressString);
+            }
+        }
+
+        addressString = ConfigProperties.getProperty(this.getClass(), "of.address");
+        if (addressString != null) {
+            try {
+                if (InetAddress.getByName(addressString) != null) {
+                    return addressString;
+                }
+            } catch (UnknownHostException e) {
+                LOG.error("Host {} is invalid", addressString);
+            }
+        }
+
+        return null;
+    }
+
+    private short getControllerOFPort() {
+        short openFlowPort = Constants.OPENFLOW_PORT;
+        String portString = ConfigProperties.getProperty(this.getClass(), "of.listenPort");
+        if (portString != null) {
+            try {
+                openFlowPort = Short.parseShort(portString);
+            } catch (NumberFormatException e) {
+                LOG.warn("Invalid port:{}, use default({})", portString,
+                        openFlowPort);
+            }
+        }
+        return openFlowPort;
+    }
+
+    private List<String> getControllersFromOvsdbNode(Node node) {
+        List<String> controllersStr = new ArrayList<>();
+
+        String controllerIpStr = getControllerIPAddress();
+        if (controllerIpStr != null) {
+            // If codepath makes it here, the ip address to be used was explicitly provided.
+            // Being so, also fetch openflowPort provided via ConfigProperties.
+            controllersStr.add(Constants.OPENFLOW_CONNECTION_PROTOCOL
+                    + ":" + controllerIpStr + ":" + getControllerOFPort());
+        } else {
+            // Check if ovsdb node has manager entries
+            OvsdbNodeAugmentation ovsdbNodeAugmentation = southbound.extractOvsdbNode(node);
+            if (ovsdbNodeAugmentation != null) {
+                List<ManagerEntry> managerEntries = ovsdbNodeAugmentation.getManagerEntry();
+                if (managerEntries != null && !managerEntries.isEmpty()) {
+                    for (ManagerEntry managerEntry : managerEntries) {
+                        if (managerEntry == null || managerEntry.getTarget() == null) {
+                            continue;
+                        }
+                        String[] tokens = managerEntry.getTarget().getValue().split(":");
+                        if (tokens.length == 3 && tokens[0].equalsIgnoreCase("tcp")) {
+                            controllersStr.add(Constants.OPENFLOW_CONNECTION_PROTOCOL
+                                    + ":" + tokens[1] + ":" + getControllerOFPort());
+                        } else if (tokens[0].equalsIgnoreCase("ptcp")) {
+                            ConnectionInfo connectionInfo = ovsdbNodeAugmentation.getConnectionInfo();
+                            if (connectionInfo != null && connectionInfo.getLocalIp() != null) {
+                                controllerIpStr = new String(connectionInfo.getLocalIp().getValue());
+                                controllersStr.add(Constants.OPENFLOW_CONNECTION_PROTOCOL
+                                        + ":" + controllerIpStr + ":" + Constants.OPENFLOW_PORT);
+                            } else {
+                                LOG.warn("Ovsdb Node does not contain connection info: {}", node);
+                            }
+                        } else {
+                            LOG.trace("Skipping manager entry {} for node {}",
+                                    managerEntry.getTarget(), node.getNodeId().getValue());
+                        }
+                    }
+                } else {
+                    LOG.warn("Ovsdb Node does not contain manager entries : {}", node);
+                }
+            }
+        }
+
+        if (controllersStr.isEmpty()) {
+            // Neither user provided ip nor ovsdb node has manager entries. Lets use local machine ip address.
+            LOG.debug("Use local machine ip address as a OpenFlow Controller ip address");
+            controllerIpStr = getLocalControllerHostIpAddress();
+            if (controllerIpStr != null) {
+                controllersStr.add(Constants.OPENFLOW_CONNECTION_PROTOCOL
+                        + ":" + controllerIpStr + ":" + Constants.OPENFLOW_PORT);
+            }
+        }
+
+        if (controllersStr.isEmpty()) {
+            LOG.warn("Failed to determine OpenFlow controller ip address");
+        } else if (LOG.isDebugEnabled()) {
+            controllerIpStr = "";
+            for (String currControllerIpStr : controllersStr) {
+                controllerIpStr += " " + currControllerIpStr;
+            }
+            LOG.debug("Found {} OpenFlow Controller(s) :{}", controllersStr.size(), controllerIpStr);
+        }
+
+        return controllersStr;
+    }
+
     private String getLocalControllerHostIpAddress() {
         String ipaddress = null;
         try{
-            for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
-                 ifaces.hasMoreElements();) {
+            for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();ifaces.hasMoreElements();){
                 NetworkInterface iface = ifaces.nextElement();
 
                 for (Enumeration<InetAddress> inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
                     InetAddress inetAddr = inetAddrs.nextElement();
-                    if (!inetAddr.isLoopbackAddress()) {
-                        if (inetAddr.isSiteLocalAddress()) {
-                            ipaddress = inetAddr.getHostAddress();
-                            break;
-                        }
+                    if (!inetAddr.isLoopbackAddress() && inetAddr.isSiteLocalAddress()) {
+                        ipaddress = inetAddr.getHostAddress();
+                        break;
                     }
                 }
             }
         }catch (Exception e){
-            LOG.warn("Exception while fetching local host ip address ",e);
+            LOG.warn("Exception while fetching local host ip address ", e);
         }
         return ipaddress;
     }
 
     private String getControllerTarget(Node ovsdbNode) {
-        String target = null;
-        String ipAddr = null;
-        OvsdbNodeAugmentation ovsdbNodeAugmentation = ovsdbNode.getAugmentation(OvsdbNodeAugmentation.class);
-        ConnectionInfo connectionInfo = ovsdbNodeAugmentation.getConnectionInfo();
-        LOG.info("connectionInfo: {}", connectionInfo);
-        if (connectionInfo != null && connectionInfo.getLocalIp() != null) {
-            ipAddr = new String(connectionInfo.getLocalIp().getValue());
-        }
-        if (ipAddr == null) {
-            ipAddr = getLocalControllerHostIpAddress();
-        }
-
-        if (ipAddr != null) {
-            target = NetvirtITConstants.OPENFLOW_CONNECTION_PROTOCOL + ":"
-                    + ipAddr + ":" + NetvirtITConstants.DEFAULT_OPENFLOW_PORT;
-        }
-
-        return target;
+        return getControllersFromOvsdbNode(ovsdbNode).get(0);
     }
 
-    @Ignore
     @Test
     public void testAddDeleteOvsdbNode() throws InterruptedException {
         ConnectionInfo connectionInfo = getConnectionInfo(addressStr, portStr);
@@ -640,31 +747,6 @@ public class NetvirtIT extends AbstractMdsalTestBase {
             bridge.getBridgeName());
     }
 
-    /**
-     * isBundleReady is used to check if the requested bundle is Active
-     */
-    public void isBundleReady(BundleContext bundleContext, String bundleName) throws InterruptedException {
-        boolean ready = false;
-
-        while (!ready) {
-            int state = Bundle.UNINSTALLED;
-            Bundle[] bundles = bundleContext.getBundles();
-            for (Bundle element : bundles) {
-                if (element.getSymbolicName().equals(bundleName)) {
-                    state = element.getState();
-                    LOG.info(">>>>> bundle is ready {}", bundleName);
-                    break;
-                }
-            }
-            if (state != Bundle.ACTIVE) {
-                LOG.info(">>>>> bundle not ready {}", bundleName);
-                Thread.sleep(5000);
-            } else {
-                ready = true;
-            }
-        }
-    }
-
     private void netVirtAddPort(ConnectionInfo connectionInfo) throws InterruptedException {
         OvsdbBridgeAugmentation bridge = getBridge(connectionInfo, NetvirtITConstants.INTEGRATION_BRIDGE_NAME);
         Assert.assertNotNull(bridge);
@@ -691,8 +773,7 @@ public class NetvirtIT extends AbstractMdsalTestBase {
      * </pre>
      * @throws InterruptedException
      */
-    // TODO add verification of flows
-    //@Ignore //
+    @Ignore
     @Test
     public void testNetVirt() throws InterruptedException {
         ConnectionInfo connectionInfo = getConnectionInfo(addressStr, portStr);
index e1dc6ad6928e87b11820f860abda2ddd9eb07182..4fea5264b6a2c99a7619c2611aa9d335468fe65c 100644 (file)
@@ -19,6 +19,7 @@ public final class NetvirtITConstants {
     public static final String CUSTOM_PROPERTIES = "etc/custom.properties";
     public static final String SERVER_IPADDRESS = "ovsdbserver.ipaddress";
     public static final String SERVER_PORT = "ovsdbserver.port";
+    public static final String CONTROLLER_IPADDRESS = "ovsdb.controller.address";
     public static final String SERVER_EXTRAS = "ovsdbserver.extras";
     public static final String CONNECTION_TYPE = "ovsdbserver.connection";
     public static final String CONNECTION_TYPE_ACTIVE = "active";
index 05b16236b05d5116480215932612bcf21b97d136..fc331129eced6e12f7015e52bf901cdb34092474 100644 (file)
@@ -1014,7 +1014,7 @@ public class OF13Provider implements ConfigInterface, NetworkingProvider {
             isLastPortinSubnet = false;
             if (isComputePort) {
                 isLastPortinSubnet = securityServicesManager.isLastPortinSubnet(node, intf);
-                srcAddressList = securityServicesManager.getIpAddressList(node, intf);
+                srcAddressList = securityServicesManager.getIpAddressList(intf);
                 if (null == srcAddressList) {
                     LOG.warn("programLocalRules: No Ip address assigned {}", intf);
                     return;
index ce2eec801263f3741e6ac00b4a885a34c6c8f6ab..0eeddf214344e46c86fc57b2ca7d3df9488168bc 100644 (file)
@@ -9,6 +9,8 @@
 package org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.services;
 
 import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Collections;
 import java.util.List;
 
 import org.opendaylight.ovsdb.openstack.netvirt.api.L2ForwardingProvider;
@@ -16,6 +18,7 @@ import org.opendaylight.ovsdb.openstack.netvirt.providers.ConfigInterface;
 import org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.AbstractServiceInstance;
 import org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.Service;
 import org.opendaylight.ovsdb.utils.mdsal.openflow.ActionUtils;
+import org.opendaylight.ovsdb.utils.mdsal.openflow.FlowUtils;
 import org.opendaylight.ovsdb.utils.mdsal.openflow.InstructionUtils;
 import org.opendaylight.ovsdb.utils.mdsal.openflow.MatchUtils;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Uri;
@@ -30,11 +33,11 @@ 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.inventory.rev130819.tables.table.FlowBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.Instructions;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.InstructionsBuilder;
 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.ApplyActionsCase;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.ApplyActionsCaseBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.apply.actions._case.ApplyActions;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.apply.actions._case.ApplyActionsBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionBuilder;
@@ -42,14 +45,11 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instru
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.VlanId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.dst.choice.grouping.dst.choice.DstNxRegCaseBuilder;
 import org.osgi.framework.BundleContext;
 import org.osgi.framework.ServiceReference;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.collect.Lists;
-
 public class L2ForwardingService extends AbstractServiceInstance implements ConfigInterface, L2ForwardingProvider {
     private static final Logger LOG = LoggerFactory.getLogger(L2ForwardingService.class);
     public L2ForwardingService() {
@@ -72,50 +72,35 @@ public class L2ForwardingService extends AbstractServiceInstance implements Conf
 
         String nodeName = OPENFLOW + dpidLong;
 
-        MatchBuilder matchBuilder = new MatchBuilder();
         NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
         FlowBuilder flowBuilder = new FlowBuilder();
 
         // Create the OF Match using MatchBuilder
-        flowBuilder.setMatch(MatchUtils.createTunnelIDMatch(matchBuilder, new BigInteger(segmentationId)).build());
-        flowBuilder.setMatch(MatchUtils.createDestEthMatch(matchBuilder, new MacAddress(attachedMac), null).build());
+        MatchBuilder matchBuilder = new MatchBuilder();
+        MatchUtils.createTunnelIDMatch(matchBuilder, new BigInteger(segmentationId));
+        MatchUtils.createDestEthMatch(matchBuilder, new MacAddress(attachedMac), null);
+        flowBuilder.setMatch(matchBuilder.build());
 
-        String flowId = "UcastOut_"+segmentationId+"_"+localPort+"_"+attachedMac;
         // Add Flow Attributes
-        flowBuilder.setId(new FlowId(flowId));
-        FlowKey key = new FlowKey(new FlowId(flowId));
-        flowBuilder.setStrict(true);
-        flowBuilder.setBarrier(false);
-        flowBuilder.setTableId(getTable());
-        flowBuilder.setKey(key);
-        flowBuilder.setFlowName(flowId);
-        flowBuilder.setHardTimeout(0);
-        flowBuilder.setIdleTimeout(0);
+        String flowName = "UcastOut_" + segmentationId + "_" + localPort + "_" + attachedMac;
+        FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable());
 
         if (write) {
-            // Instantiate the Builders for the OF Actions and Instructions
-            InstructionBuilder ib = new InstructionBuilder();
-            InstructionsBuilder isb = new InstructionsBuilder();
-
-            // Instructions List Stores Individual Instructions
-            List<Instruction> instructions = Lists.newArrayList();
-
             // Set the Output Port/Iface
-            InstructionUtils.createOutputPortInstructions(ib, dpidLong, localPort);
-            ib.setOrder(0);
-            ib.setKey(new InstructionKey(0));
-            instructions.add(ib.build());
-
-            // Add InstructionBuilder to the Instruction(s)Builder List
-            isb.setInstruction(instructions);
+            Instruction setOutputPortInstruction =
+                    InstructionUtils.createOutputPortInstructions(new InstructionBuilder(), dpidLong, localPort)
+                            .setOrder(0)
+                            .setKey(new InstructionKey(0))
+                            .build();
 
             // Add InstructionsBuilder to FlowBuilder
-            flowBuilder.setInstructions(isb.build());
+            InstructionUtils.setFlowBuilderInstruction(flowBuilder, setOutputPortInstruction);
             writeFlow(flowBuilder, nodeBuilder);
         } else {
             removeFlow(flowBuilder, nodeBuilder);
         }
     }
+
     /*
      * (Table:2) Local VLAN unicast
      * Match: VLAN ID and dMAC
@@ -129,54 +114,36 @@ public class L2ForwardingService extends AbstractServiceInstance implements Conf
 
         String nodeName = OPENFLOW + dpidLong;
 
-        MatchBuilder matchBuilder = new MatchBuilder();
         NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
         FlowBuilder flowBuilder = new FlowBuilder();
 
         // Create the OF Match using MatchBuilder
-        flowBuilder.setMatch(
-                MatchUtils.createVlanIdMatch(matchBuilder, new VlanId(Integer.valueOf(segmentationId)), true).build());
-        flowBuilder.setMatch(MatchUtils.createDestEthMatch(matchBuilder, new MacAddress(attachedMac), null).build());
+        MatchBuilder matchBuilder = new MatchBuilder();
+        MatchUtils.createVlanIdMatch(matchBuilder, new VlanId(Integer.valueOf(segmentationId)), true);
+        MatchUtils.createDestEthMatch(matchBuilder, new MacAddress(attachedMac), null);
+        flowBuilder.setMatch(matchBuilder.build());
 
-        String flowId = "VlanUcastOut_"+segmentationId+"_"+localPort+"_"+attachedMac;
         // Add Flow Attributes
-        flowBuilder.setId(new FlowId(flowId));
-        FlowKey key = new FlowKey(new FlowId(flowId));
-        flowBuilder.setStrict(true);
-        flowBuilder.setBarrier(false);
-        flowBuilder.setTableId(getTable());
-        flowBuilder.setKey(key);
-        flowBuilder.setFlowName(flowId);
-        flowBuilder.setHardTimeout(0);
-        flowBuilder.setIdleTimeout(0);
+        String flowName = "VlanUcastOut_" + segmentationId + "_" + localPort + "_" + attachedMac;
+        FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable());
 
         if (write) {
-            // Instantiate the Builders for the OF Actions and Instructions
-            InstructionBuilder ib = new InstructionBuilder();
-            InstructionsBuilder isb = new InstructionsBuilder();
-
-            // Instructions List Stores Individual Instructions
-            List<Instruction> instructions = Lists.newArrayList();
-            List<Instruction> instructions_tmp = Lists.newArrayList();
-
             /* Strip vlan and store to tmp instruction space*/
-            InstructionUtils.createPopVlanInstructions(ib);
-            ib.setOrder(0);
-            ib.setKey(new InstructionKey(0));
-            instructions_tmp.add(ib.build());
+            Instruction stripVlanInstruction = InstructionUtils.createPopVlanInstructions(new InstructionBuilder())
+                    .setOrder(0)
+                    .setKey(new InstructionKey(0))
+                    .build();
 
             // Set the Output Port/Iface
-            ib = new InstructionBuilder();
-            InstructionUtils.addOutputPortInstructions(ib, dpidLong, localPort, instructions_tmp);
-            ib.setOrder(1);
-            ib.setKey(new InstructionKey(0));
-            instructions.add(ib.build());
-
-            // Add InstructionBuilder to the Instruction(s)Builder List
-            isb.setInstruction(instructions);
+            Instruction setOutputPortInstruction =
+                    InstructionUtils.addOutputPortInstructions(new InstructionBuilder(), dpidLong, localPort,
+                            Collections.singletonList(stripVlanInstruction))
+                            .setOrder(1)
+                            .setKey(new InstructionKey(0))
+                            .build();
 
             // Add InstructionsBuilder to FlowBuilder
-            flowBuilder.setInstructions(isb.build());
+            InstructionUtils.setFlowBuilderInstruction(flowBuilder, setOutputPortInstruction);
             writeFlow(flowBuilder, nodeBuilder);
         } else {
             removeFlow(flowBuilder, nodeBuilder);
@@ -184,33 +151,6 @@ public class L2ForwardingService extends AbstractServiceInstance implements Conf
     }
 
 
-    /**
-     * Utility function used by the flooding logic to allow a flow to be resubmitted
-     * to the local port flooding rule, after being outputed to all available tunnel
-     * or VLAN egress ports.
-     */
-    private void appendResubmitLocalFlood(InstructionBuilder ib) {
-
-        //Update the ApplyActions instructions
-        ApplyActionsCase aac = (ApplyActionsCase) ib.getInstruction();
-        List<Action> actionList = aac.getApplyActions().getAction();
-
-        int index = actionList.size();
-        ActionBuilder ab = new ActionBuilder();
-        ab.setAction(ActionUtils.nxLoadRegAction(new DstNxRegCaseBuilder().setNxReg(ClassifierService.REG_FIELD).build(),
-                BigInteger.valueOf(ClassifierService.REG_VALUE_FROM_REMOTE)));
-        ab.setOrder(index);
-        ab.setKey(new ActionKey(index));
-        actionList.add(ab.build());
-
-        index++;
-        ab = new ActionBuilder();
-        ab.setAction(ActionUtils.nxResubmitAction(null, this.getTable()));
-        ab.setOrder(index);
-        ab.setKey(new ActionKey(index));
-        actionList.add(ab.build());
-    }
-
     /*
      * (Table:2) Local Broadcast Flood
      * Match: Tunnel ID and dMAC (::::FF:FF)
@@ -223,61 +163,45 @@ public class L2ForwardingService extends AbstractServiceInstance implements Conf
 
         String nodeName = OPENFLOW + dpidLong;
 
-        MatchBuilder matchBuilder = new MatchBuilder();
         NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
         FlowBuilder flowBuilder = new FlowBuilder();
 
         // Create the OF Match using MatchBuilder
-        MatchUtils.addNxRegMatch(matchBuilder, new MatchUtils.RegMatch(ClassifierService.REG_FIELD, ClassifierService.REG_VALUE_FROM_REMOTE));
-        flowBuilder.setMatch(MatchUtils.createTunnelIDMatch(matchBuilder, new BigInteger(segmentationId)).build());
-        flowBuilder.setMatch(MatchUtils.createDestEthMatch(matchBuilder, new MacAddress("01:00:00:00:00:00"),
-                new MacAddress("01:00:00:00:00:00")).build());
+        MatchBuilder matchBuilder = new MatchBuilder();
+        MatchUtils.addNxRegMatch(matchBuilder,
+                new MatchUtils.RegMatch(ClassifierService.REG_FIELD, ClassifierService.REG_VALUE_FROM_REMOTE));
+        MatchUtils.createTunnelIDMatch(matchBuilder, new BigInteger(segmentationId));
+        MatchUtils.createDestEthMatch(matchBuilder, new MacAddress("01:00:00:00:00:00"),
+                new MacAddress("01:00:00:00:00:00"));
+        flowBuilder.setMatch(matchBuilder.build());
 
-        String flowId = "BcastOut_"+segmentationId;
         // Add Flow Attributes
-        flowBuilder.setId(new FlowId(flowId));
-        FlowKey key = new FlowKey(new FlowId(flowId));
-        flowBuilder.setStrict(true);
-        flowBuilder.setBarrier(false);
-        flowBuilder.setTableId(getTable());
-        flowBuilder.setKey(key);
-        flowBuilder.setPriority(16384);
-        flowBuilder.setFlowName(flowId);
-        flowBuilder.setHardTimeout(0);
-        flowBuilder.setIdleTimeout(0);
+        String flowName = "BcastOut_" + segmentationId;
+        FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable())
+                .setPriority(16384);
+
         Flow flow = this.getFlow(flowBuilder, nodeBuilder);
-        // Instantiate the Builders for the OF Actions and Instructions
-        InstructionBuilder ib = new InstructionBuilder();
-        InstructionsBuilder isb = new InstructionsBuilder();
-        List<Instruction> instructions = Lists.newArrayList();
-        List<Instruction> existingInstructions = null;
-        if (flow != null) {
-            Instructions ins = flow.getInstructions();
-            if (ins != null) {
-                existingInstructions = ins.getInstruction();
-            }
-        }
+
+        // Retrieve the existing instructions
+        List<Instruction> existingInstructions = InstructionUtils.extractExistingInstructions(flow);
 
         if (write) {
             // Create output port list
-            createOutputPortInstructions(ib, dpidLong, localPort, existingInstructions);
-            ib.setOrder(0);
-            ib.setKey(new InstructionKey(0));
+            Instruction outputPortInstruction =
+                    createOutputPortInstructions(new InstructionBuilder(), dpidLong, localPort, existingInstructions)
+                            .setOrder(0)
+                            .setKey(new InstructionKey(0))
+                            .build();
 
-            /* Alternative method to address Bug 2004 is to make a call
-             * here to appendResubmitLocalFlood(ib) so that we send the
-             * flow back to the local flood rule.
-             */
-            instructions.add(ib.build());
-
-            // Add InstructionBuilder to the Instruction(s)Builder List
-            isb.setInstruction(instructions);
+            /* Alternative method to address Bug 2004 is to use appendResubmitLocalFlood(ib) so that we send the
+             * flow back to the local flood rule. (See git history.) */
 
             // Add InstructionsBuilder to FlowBuilder
-            flowBuilder.setInstructions(isb.build());
+            InstructionUtils.setFlowBuilderInstruction(flowBuilder, outputPortInstruction);
 
             writeFlow(flowBuilder, nodeBuilder);
         } else {
+            InstructionBuilder ib = new InstructionBuilder();
             boolean flowRemove = InstructionUtils.removeOutputPortFromInstructions(ib, dpidLong, localPort,
                     existingInstructions);
             if (flowRemove) {
@@ -285,15 +209,14 @@ public class L2ForwardingService extends AbstractServiceInstance implements Conf
                 removeFlow(flowBuilder, nodeBuilder);
             } else {
                 /* Install instruction with new output port list*/
-                ib.setOrder(0);
-                ib.setKey(new InstructionKey(0));
-                instructions.add(ib.build());
-
-                // Add InstructionBuilder to the Instruction(s)Builder List
-                isb.setInstruction(instructions);
+                Instruction outputPortInstruction = ib
+                        .setOrder(0)
+                        .setKey(new InstructionKey(0))
+                        .build();
 
                 // Add InstructionsBuilder to FlowBuilder
-                flowBuilder.setInstructions(isb.build());
+                InstructionUtils.setFlowBuilderInstruction(flowBuilder, outputPortInstruction);
+
                 writeFlow(flowBuilder, nodeBuilder);
             }
         }
@@ -313,78 +236,69 @@ public class L2ForwardingService extends AbstractServiceInstance implements Conf
 
         String nodeName = OPENFLOW + dpidLong;
 
-        MatchBuilder matchBuilder = new MatchBuilder();
         NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
         FlowBuilder flowBuilder = new FlowBuilder();
 
         // Create the OF Match using MatchBuilder
-        flowBuilder.setMatch(
-                MatchUtils.createVlanIdMatch(matchBuilder, new VlanId(Integer.valueOf(segmentationId)), true).build());
-        flowBuilder.setMatch(MatchUtils.createDestEthMatch(matchBuilder, new MacAddress("01:00:00:00:00:00"),
-                new MacAddress("01:00:00:00:00:00")).build());
+        MatchBuilder matchBuilder = new MatchBuilder();
+        MatchUtils.createVlanIdMatch(matchBuilder, new VlanId(Integer.valueOf(segmentationId)), true);
+        MatchUtils.createDestEthMatch(matchBuilder, new MacAddress("01:00:00:00:00:00"),
+                new MacAddress("01:00:00:00:00:00"));
+        flowBuilder.setMatch(matchBuilder.build());
 
-        String flowId = "VlanBcastOut_"+segmentationId+"_"+ethPort;
         // Add Flow Attributes
-        flowBuilder.setId(new FlowId(flowId));
-        FlowKey key = new FlowKey(new FlowId(flowId));
-        flowBuilder.setStrict(true);
-        flowBuilder.setBarrier(false);
-        flowBuilder.setTableId(getTable());
-        flowBuilder.setKey(key);
-        flowBuilder.setPriority(16384);
-        flowBuilder.setFlowName(flowId);
-        flowBuilder.setHardTimeout(0);
-        flowBuilder.setIdleTimeout(0);
+        String flowName = "VlanBcastOut_" + segmentationId + "_" + ethPort;
+        FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable())
+                .setPriority(16384);
         Flow flow = this.getFlow(flowBuilder, nodeBuilder);
-        // Instantiate the Builders for the OF Actions and Instructions
-        List<Instruction> existingInstructions = null;
-        if (flow != null) {
-            Instructions ins = flow.getInstructions();
-            if (ins != null) {
-                existingInstructions = ins.getInstruction();
-            }
-        }
 
-        List<Instruction> instructions = Lists.newArrayList();
-        InstructionBuilder ib = new InstructionBuilder();
-        List<Action> actionList;
+        // Retrieve the existing instructions
+        List<Instruction> existingInstructions = InstructionUtils.extractExistingInstructions(flow);
+
         if (write) {
-            if (existingInstructions == null) {
+            List<Action> actionList;
+            if (existingInstructions == null || existingInstructions.isEmpty()) {
                 /* First time called there should be no instructions.
                  * We can simply add the output:ethPort first, followed by
                  * popVlan and then the local port. The next calls will append
                  * the rest of the local ports.
                  */
-                ActionBuilder ab = new ActionBuilder();
-                actionList = Lists.newArrayList();
-
-                ab.setAction(ActionUtils.outputAction(new NodeConnectorId(nodeName + ":" + ethPort)));
-                ab.setOrder(0);
-                ab.setKey(new ActionKey(0));
-                actionList.add(ab.build());
-
-                ab.setAction(ActionUtils.popVlanAction());
-                ab.setOrder(1);
-                ab.setKey(new ActionKey(1));
-                actionList.add(ab.build());
-
-                ab.setAction(ActionUtils.outputAction(new NodeConnectorId(nodeName + ":" + localPort)));
-                ab.setOrder(2);
-                ab.setKey(new ActionKey(2));
-                actionList.add(ab.build());
+                actionList = new ArrayList<>();
+
+                actionList.add(
+                        new ActionBuilder()
+                                .setAction(ActionUtils.outputAction(new NodeConnectorId(nodeName + ":" + ethPort)))
+                                .setOrder(0)
+                                .setKey(new ActionKey(0))
+                                .build());
+
+                actionList.add(
+                        new ActionBuilder()
+                                .setAction(ActionUtils.popVlanAction())
+                                .setOrder(1)
+                                .setKey(new ActionKey(1))
+                                .build());
+
+                actionList.add(
+                        new ActionBuilder()
+                                .setAction(ActionUtils.outputAction(new NodeConnectorId(nodeName + ":" + localPort)))
+                                .setOrder(2)
+                                .setKey(new ActionKey(2))
+                                .build());
             } else {
                 /* Subsequent calls require appending any new local ports for this tenant. */
                 Instruction in = existingInstructions.get(0);
                 actionList = (((ApplyActionsCase) in.getInstruction()).getApplyActions().getAction());
 
                 NodeConnectorId ncid = new NodeConnectorId(nodeName + ":" + localPort);
+                final Uri nodeConnectorUri = new Uri(ncid);
                 boolean addNew = true;
 
                 /* Check if the port is already in the output list */
                 for (Action action : actionList) {
                     if (action.getAction() instanceof OutputActionCase) {
                         OutputActionCase opAction = (OutputActionCase) action.getAction();
-                        if (opAction.getOutputAction().getOutputNodeConnector().equals(new Uri(ncid))) {
+                        if (opAction.getOutputAction().getOutputNodeConnector().equals(nodeConnectorUri)) {
                             addNew = false;
                             break;
                         }
@@ -392,32 +306,29 @@ public class L2ForwardingService extends AbstractServiceInstance implements Conf
                 }
 
                 if (addNew) {
-                    ActionBuilder ab = new ActionBuilder();
-
-                    ab.setAction(ActionUtils.outputAction(new NodeConnectorId(nodeName + ":" + localPort)));
-                    ab.setOrder(actionList.size());
-                    ab.setKey(new ActionKey(actionList.size()));
-                    actionList.add(ab.build());
+                    actionList.add(
+                            new ActionBuilder()
+                                    .setAction(
+                                            ActionUtils.outputAction(new NodeConnectorId(nodeName + ":" + localPort)))
+                                    .setOrder(actionList.size())
+                                    .setKey(new ActionKey(actionList.size()))
+                                    .build());
                 }
             }
 
-            ApplyActionsBuilder aab = new ApplyActionsBuilder();
-            aab.setAction(actionList);
-            ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
-            ib.setOrder(0);
-            ib.setKey(new InstructionKey(0));
-            instructions.add(ib.build());
-
-            // Add InstructionBuilder to the Instruction(s)Builder List
-            InstructionsBuilder isb = new InstructionsBuilder();
-            isb.setInstruction(instructions);
+            ApplyActions applyActions = new ApplyActionsBuilder().setAction(actionList).build();
+            Instruction applyActionsInstruction =
+                    new InstructionBuilder()
+                            .setInstruction(new ApplyActionsCaseBuilder().setApplyActions(applyActions).build())
+                            .setOrder(0)
+                            .setKey(new InstructionKey(0))
+                            .build();
 
             // Add InstructionsBuilder to FlowBuilder
-            flowBuilder.setInstructions(isb.build());
+            InstructionUtils.setFlowBuilderInstruction(flowBuilder, applyActionsInstruction);
             writeFlow(flowBuilder, nodeBuilder);
         } else {
-            //boolean flowRemove = removeOutputPortFromGroup(nodeBuilder, ib, dpidLong,
-            //                     localPort, existingInstructions);
+            InstructionBuilder ib = new InstructionBuilder();
             boolean flowRemove = removeOutputPortFromInstructions(ib, dpidLong, localPort, ethPort,
                     existingInstructions);
             if (flowRemove) {
@@ -425,16 +336,13 @@ public class L2ForwardingService extends AbstractServiceInstance implements Conf
                 removeFlow(flowBuilder, nodeBuilder);
             } else {
                 /* Install instruction with new output port list*/
-                ib.setOrder(0);
-                ib.setKey(new InstructionKey(0));
-                instructions.add(ib.build());
-
-                // Add InstructionBuilder to the Instruction(s)Builder List
-                InstructionsBuilder isb = new InstructionsBuilder();
-                isb.setInstruction(instructions);
+                Instruction outputPortInstruction = ib
+                        .setOrder(0)
+                        .setKey(new InstructionKey(0))
+                        .build();
 
                 // Add InstructionsBuilder to FlowBuilder
-                flowBuilder.setInstructions(isb.build());
+                InstructionUtils.setFlowBuilderInstruction(flowBuilder, outputPortInstruction);
                 writeFlow(flowBuilder, nodeBuilder);
             }
         }
@@ -442,43 +350,44 @@ public class L2ForwardingService extends AbstractServiceInstance implements Conf
 
     private boolean removeOutputPortFromInstructions(InstructionBuilder ib, Long dpidLong, Long localPort,
                                                      Long ethPort, List<Instruction> instructions) {
-        List<Action> actionList = Lists.newArrayList();
+        List<Action> actionList = new ArrayList<>();
         boolean removeFlow = true;
 
-        if (instructions != null) {
+        if (instructions != null && !instructions.isEmpty()) {
             Instruction in = instructions.get(0);
             List<Action> oldActionList = (((ApplyActionsCase) in.getInstruction()).getApplyActions().getAction());
             NodeConnectorId ncid = new NodeConnectorId(OPENFLOW + dpidLong + ":" + localPort);
+            final Uri localNodeConnectorUri = new Uri(ncid);
             NodeConnectorId ncidEth = new NodeConnectorId(OPENFLOW + dpidLong + ":" + ethPort);
+            final Uri ethNodeConnectorUri = new Uri(ncidEth);
 
             // Remove the port from the output list
-            ActionBuilder ab = new ActionBuilder();
             int index = 2;
-            //for (ListIterator<Action> it = oldActionList.listIterator(oldActionList.size()); it.hasPrevious();) {
-            //    Action action = it.previous();
             for (Action action : oldActionList) {
                 if (action.getAction() instanceof OutputActionCase) {
                     OutputActionCase opAction = (OutputActionCase) action.getAction();
-                    if (opAction.getOutputAction().getOutputNodeConnector().equals(new Uri(ncidEth))) {
+                    if (opAction.getOutputAction().getOutputNodeConnector().equals(ethNodeConnectorUri)) {
                         actionList.add(action);
-                    } else if (!opAction.getOutputAction().getOutputNodeConnector().equals(new Uri(ncid))) {
-                        ab.setAction(action.getAction());
-                        ab.setOrder(index);
-                        ab.setKey(new ActionKey(index));
-                        actionList.add(ab.build());
+                    } else if (!opAction.getOutputAction().getOutputNodeConnector().equals(localNodeConnectorUri)) {
+                        actionList.add(
+                                new ActionBuilder()
+                                        .setAction(action.getAction())
+                                        .setOrder(index)
+                                        .setKey(new ActionKey(index))
+                                        .build());
                         index++;
                     }
                 } else {
                     actionList.add(action);
                 }
             }
-            ApplyActionsBuilder aab = new ApplyActionsBuilder();
-            aab.setAction(actionList);
-            ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
+            ApplyActions applyActions = new ApplyActionsBuilder().setAction(actionList).build();
+            ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(applyActions).build());
         }
 
         if (actionList.size() > 2) {
             // Add InstructionBuilder to the Instruction(s)Builder List
+            // TODO This doesn't actually do anything
             InstructionsBuilder isb = new InstructionsBuilder();
             isb.setInstruction(instructions);
             removeFlow = false;
@@ -499,46 +408,28 @@ public class L2ForwardingService extends AbstractServiceInstance implements Conf
 
         String nodeName = OPENFLOW + dpidLong;
 
-        MatchBuilder matchBuilder = new MatchBuilder();
         NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
         FlowBuilder flowBuilder = new FlowBuilder();
 
         // Create Match(es) and Set them in the FlowBuilder Object
-        flowBuilder.setMatch(MatchUtils.createTunnelIDMatch(matchBuilder, new BigInteger(segmentationId)).build());
+        flowBuilder.setMatch(
+                MatchUtils.createTunnelIDMatch(new MatchBuilder(), new BigInteger(segmentationId)).build());
 
         if (write) {
-            // Create the OF Actions and Instructions
-            InstructionBuilder ib = new InstructionBuilder();
-            InstructionsBuilder isb = new InstructionsBuilder();
-
-            // Instructions List Stores Individual Instructions
-            List<Instruction> instructions = Lists.newArrayList();
-
             // Call the InstructionBuilder Methods Containing Actions
-            InstructionUtils.createDropInstructions(ib);
-            ib.setOrder(0);
-            ib.setKey(new InstructionKey(0));
-            instructions.add(ib.build());
-
-            // Add InstructionBuilder to the Instruction(s)Builder List
-            isb.setInstruction(instructions);
+            Instruction dropInstruction = InstructionUtils.createDropInstructions(new InstructionBuilder())
+                    .setOrder(0)
+                    .setKey(new InstructionKey(0))
+                    .build();
 
             // Add InstructionsBuilder to FlowBuilder
-            flowBuilder.setInstructions(isb.build());
+            InstructionUtils.setFlowBuilderInstruction(flowBuilder, dropInstruction);
         }
 
-        String flowId = "LocalTableMiss_"+segmentationId;
         // Add Flow Attributes
-        flowBuilder.setId(new FlowId(flowId));
-        FlowKey key = new FlowKey(new FlowId(flowId));
-        flowBuilder.setStrict(true);
-        flowBuilder.setBarrier(false);
-        flowBuilder.setTableId(getTable());
-        flowBuilder.setKey(key);
-        flowBuilder.setPriority(8192);
-        flowBuilder.setFlowName(flowId);
-        flowBuilder.setHardTimeout(0);
-        flowBuilder.setIdleTimeout(0);
+        String flowName = "LocalTableMiss_" + segmentationId;
+        FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable())
+                .setPriority(8192);
         if (write) {
             writeFlow(flowBuilder, nodeBuilder);
         } else {
@@ -558,47 +449,29 @@ public class L2ForwardingService extends AbstractServiceInstance implements Conf
 
         String nodeName = OPENFLOW + dpidLong;
 
-        MatchBuilder matchBuilder = new MatchBuilder();
         NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
         FlowBuilder flowBuilder = new FlowBuilder();
 
         // Create Match(es) and Set them in the FlowBuilder Object
         flowBuilder.setMatch(
-                MatchUtils.createVlanIdMatch(matchBuilder, new VlanId(Integer.valueOf(segmentationId)), true).build());
+                MatchUtils.createVlanIdMatch(new MatchBuilder(), new VlanId(Integer.valueOf(segmentationId)),
+                        true).build());
 
         if (write) {
-            // Create the OF Actions and Instructions
-            InstructionBuilder ib = new InstructionBuilder();
-            InstructionsBuilder isb = new InstructionsBuilder();
-
-            // Instructions List Stores Individual Instructions
-            List<Instruction> instructions = Lists.newArrayList();
-
             // Call the InstructionBuilder Methods Containing Actions
-            InstructionUtils.createDropInstructions(ib);
-            ib.setOrder(0);
-            ib.setKey(new InstructionKey(0));
-            instructions.add(ib.build());
-
-            // Add InstructionBuilder to the Instruction(s)Builder List
-            isb.setInstruction(instructions);
+            Instruction dropInstruction = InstructionUtils.createDropInstructions(new InstructionBuilder())
+                    .setOrder(0)
+                    .setKey(new InstructionKey(0))
+                    .build();
 
             // Add InstructionsBuilder to FlowBuilder
-            flowBuilder.setInstructions(isb.build());
+            InstructionUtils.setFlowBuilderInstruction(flowBuilder, dropInstruction);
         }
 
-        String flowId = "LocalTableMiss_"+segmentationId;
         // Add Flow Attributes
-        flowBuilder.setId(new FlowId(flowId));
-        FlowKey key = new FlowKey(new FlowId(flowId));
-        flowBuilder.setStrict(true);
-        flowBuilder.setBarrier(false);
-        flowBuilder.setTableId(getTable());
-        flowBuilder.setKey(key);
-        flowBuilder.setPriority(8192);
-        flowBuilder.setFlowName(flowId);
-        flowBuilder.setHardTimeout(0);
-        flowBuilder.setIdleTimeout(0);
+        String flowName = "LocalTableMiss_" + segmentationId;
+        FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable())
+                .setPriority(8192);
         if (write) {
             writeFlow(flowBuilder, nodeBuilder);
         } else {
@@ -620,45 +493,29 @@ public class L2ForwardingService extends AbstractServiceInstance implements Conf
 
         String nodeName = OPENFLOW + dpidLong;
 
-        MatchBuilder matchBuilder = new MatchBuilder();
         NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
         FlowBuilder flowBuilder = new FlowBuilder();
 
         // Create the OF Match using MatchBuilder
-        flowBuilder.setMatch(MatchUtils.createTunnelIDMatch(matchBuilder, new BigInteger(segmentationId)).build());
-        flowBuilder.setMatch(MatchUtils.createDestEthMatch(matchBuilder, new MacAddress(attachedMac), null).build());
+        MatchBuilder matchBuilder = new MatchBuilder();
+        MatchUtils.createTunnelIDMatch(matchBuilder, new BigInteger(segmentationId));
+        MatchUtils.createDestEthMatch(matchBuilder, new MacAddress(attachedMac), null);
+        flowBuilder.setMatch(matchBuilder.build());
 
-        String flowId = "TunnelOut_"+segmentationId+"_"+OFPortOut+"_"+attachedMac;
         // Add Flow Attributes
-        flowBuilder.setId(new FlowId(flowId));
-        FlowKey key = new FlowKey(new FlowId(flowId));
-        flowBuilder.setStrict(true);
-        flowBuilder.setBarrier(false);
-        flowBuilder.setTableId(getTable());
-        flowBuilder.setKey(key);
-        flowBuilder.setFlowName(flowId);
-        flowBuilder.setHardTimeout(0);
-        flowBuilder.setIdleTimeout(0);
+        String flowName = "TunnelOut_" + segmentationId + "_" + OFPortOut + "_" + attachedMac;
+        FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable());
 
         if (write) {
-            // Instantiate the Builders for the OF Actions and Instructions
-            InstructionBuilder ib = new InstructionBuilder();
-            InstructionsBuilder isb = new InstructionsBuilder();
-
-            // Instructions List Stores Individual Instructions
-            List<Instruction> instructions = Lists.newArrayList();
-
             // Set the Output Port/Iface
-            InstructionUtils.createOutputPortInstructions(ib, dpidLong, OFPortOut);
-            ib.setOrder(0);
-            ib.setKey(new InstructionKey(1));
-            instructions.add(ib.build());
-
-            // Add InstructionBuilder to the Instruction(s)Builder List
-            isb.setInstruction(instructions);
+            Instruction outputPortInstruction =
+                    InstructionUtils.createOutputPortInstructions(new InstructionBuilder(), dpidLong, OFPortOut)
+                            .setOrder(0)
+                            .setKey(new InstructionKey(1))
+                            .build();
 
             // Add InstructionsBuilder to FlowBuilder
-            flowBuilder.setInstructions(isb.build());
+            InstructionUtils.setFlowBuilderInstruction(flowBuilder, outputPortInstruction);
 
             writeFlow(flowBuilder, nodeBuilder);
         } else {
@@ -679,44 +536,29 @@ public class L2ForwardingService extends AbstractServiceInstance implements Conf
 
         String nodeName = OPENFLOW + dpidLong;
 
-        MatchBuilder matchBuilder = new MatchBuilder();
         NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
         FlowBuilder flowBuilder = new FlowBuilder();
 
         // Create the OF Match using MatchBuilder
-        flowBuilder.setMatch(
-                MatchUtils.createVlanIdMatch(matchBuilder, new VlanId(Integer.valueOf(segmentationId)), true).build());
-        flowBuilder.setMatch(MatchUtils.createDestEthMatch(matchBuilder, new MacAddress(attachedMac), null).build());
+        MatchBuilder matchBuilder = new MatchBuilder();
+        MatchUtils.createVlanIdMatch(matchBuilder, new VlanId(Integer.valueOf(segmentationId)), true);
+        MatchUtils.createDestEthMatch(matchBuilder, new MacAddress(attachedMac), null);
+        flowBuilder.setMatch(matchBuilder.build());
 
-        String flowId = "VlanOut_"+segmentationId+"_"+ethPort+"_"+attachedMac;
         // Add Flow Attributes
-        flowBuilder.setId(new FlowId(flowId));
-        FlowKey key = new FlowKey(new FlowId(flowId));
-        flowBuilder.setStrict(true);
-        flowBuilder.setBarrier(false);
-        flowBuilder.setTableId(getTable());
-        flowBuilder.setKey(key);
-        flowBuilder.setFlowName(flowId);
-        flowBuilder.setHardTimeout(0);
-        flowBuilder.setIdleTimeout(0);
+        String flowName = "VlanOut_" + segmentationId + "_" + ethPort + "_" + attachedMac;
+        FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable());
 
         if (write) {
-            // Instantiate the Builders for the OF Actions and Instructions
-            InstructionBuilder ib = new InstructionBuilder();
-            InstructionsBuilder isb = new InstructionsBuilder();
-
             // Instructions List Stores Individual Instructions
-            List<Instruction> instructions = Lists.newArrayList();
-            InstructionUtils.createOutputPortInstructions(ib, dpidLong, ethPort);
-            ib.setOrder(0);
-            ib.setKey(new InstructionKey(1));
-            instructions.add(ib.build());
-
-            // Add InstructionBuilder to the Instruction(s)Builder List
-            isb.setInstruction(instructions);
+            Instruction outputPortInstruction =
+                    InstructionUtils.createOutputPortInstructions(new InstructionBuilder(), dpidLong, ethPort)
+                            .setOrder(0)
+                            .setKey(new InstructionKey(1))
+                            .build();
 
             // Add InstructionsBuilder to FlowBuilder
-            flowBuilder.setInstructions(isb.build());
+            InstructionUtils.setFlowBuilderInstruction(flowBuilder, outputPortInstruction);
 
             writeFlow(flowBuilder, nodeBuilder);
         } else {
@@ -736,59 +578,51 @@ public class L2ForwardingService extends AbstractServiceInstance implements Conf
 
         String nodeName = OPENFLOW + dpidLong;
 
-        MatchBuilder matchBuilder = new MatchBuilder();
         NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
         FlowBuilder flowBuilder = new FlowBuilder();
 
         // Create the OF Match using MatchBuilder
+        MatchBuilder matchBuilder = new MatchBuilder();
         // Match TunnelID
-        MatchUtils.addNxRegMatch(matchBuilder, new MatchUtils.RegMatch(ClassifierService.REG_FIELD, ClassifierService.REG_VALUE_FROM_LOCAL));
-        flowBuilder.setMatch(MatchUtils.createTunnelIDMatch(matchBuilder, new BigInteger(segmentationId)).build());
+        MatchUtils.addNxRegMatch(matchBuilder,
+                new MatchUtils.RegMatch(ClassifierService.REG_FIELD, ClassifierService.REG_VALUE_FROM_LOCAL));
+        MatchUtils.createTunnelIDMatch(matchBuilder, new BigInteger(segmentationId));
         // Match DMAC
-        flowBuilder.setMatch(MatchUtils.createDestEthMatch(matchBuilder, new MacAddress("01:00:00:00:00:00"),
-                new MacAddress("01:00:00:00:00:00")).build());
+        MatchUtils.createDestEthMatch(matchBuilder, new MacAddress("01:00:00:00:00:00"),
+                new MacAddress("01:00:00:00:00:00"));
+        flowBuilder.setMatch(matchBuilder.build());
 
-        String flowId = "TunnelFloodOut_"+segmentationId;
         // Add Flow Attributes
-        flowBuilder.setId(new FlowId(flowId));
-        FlowKey key = new FlowKey(new FlowId(flowId));
-        flowBuilder.setBarrier(true);
-        flowBuilder.setTableId(getTable());
-        flowBuilder.setKey(key);
-        flowBuilder.setPriority(16383);  // FIXME: change it back to 16384 once bug 3005 is fixed.
-        flowBuilder.setFlowName(flowId);
-        flowBuilder.setHardTimeout(0);
-        flowBuilder.setIdleTimeout(0);
+        String flowName = "TunnelFloodOut_" + segmentationId;
+        final FlowId flowId = new FlowId(flowName);
+        flowBuilder
+                .setId(flowId)
+                .setBarrier(true)
+                .setTableId(getTable())
+                .setKey(new FlowKey(flowId))
+                .setPriority(16383)  // FIXME: change it back to 16384 once bug 3005 is fixed.
+                .setFlowName(flowName)
+                .setHardTimeout(0)
+                .setIdleTimeout(0);
 
         Flow flow = this.getFlow(flowBuilder, nodeBuilder);
         // Instantiate the Builders for the OF Actions and Instructions
-        InstructionBuilder ib = new InstructionBuilder();
-        InstructionsBuilder isb = new InstructionsBuilder();
-        List<Instruction> instructions = Lists.newArrayList();
-        List<Instruction> existingInstructions = null;
-        if (flow != null) {
-            Instructions ins = flow.getInstructions();
-            if (ins != null) {
-                existingInstructions = ins.getInstruction();
-            }
-        }
+        List<Instruction> existingInstructions = InstructionUtils.extractExistingInstructions(flow);
 
         if (write) {
             // Set the Output Port/Iface
-            //createOutputGroupInstructions(nodeBuilder, ib, dpidLong, OFPortOut, existingInstructions);
-            createOutputPortInstructions(ib, dpidLong, OFPortOut, existingInstructions);
-            ib.setOrder(0);
-            ib.setKey(new InstructionKey(0));
-            instructions.add(ib.build());
-
-            // Add InstructionBuilder to the Instruction(s)Builder List
-            isb.setInstruction(instructions);
+            Instruction outputPortInstruction =
+                    createOutputPortInstructions(new InstructionBuilder(), dpidLong, OFPortOut, existingInstructions)
+                            .setOrder(0)
+                            .setKey(new InstructionKey(0))
+                            .build();
 
             // Add InstructionsBuilder to FlowBuilder
-            flowBuilder.setInstructions(isb.build());
+            InstructionUtils.setFlowBuilderInstruction(flowBuilder, outputPortInstruction);
 
             writeFlow(flowBuilder, nodeBuilder);
         } else {
+            InstructionBuilder ib = new InstructionBuilder();
             /* remove port from action list */
             boolean flowRemove = InstructionUtils.removeOutputPortFromInstructions(ib, dpidLong,
                     OFPortOut, existingInstructions);
@@ -797,15 +631,13 @@ public class L2ForwardingService extends AbstractServiceInstance implements Conf
                 removeFlow(flowBuilder, nodeBuilder);
             } else {
                 /* Install instruction with new output port list*/
-                ib.setOrder(0);
-                ib.setKey(new InstructionKey(0));
-                instructions.add(ib.build());
-
-                // Add InstructionBuilder to the Instruction(s)Builder List
-                isb.setInstruction(instructions);
+                Instruction instruction = ib
+                        .setOrder(0)
+                        .setKey(new InstructionKey(0))
+                        .build();
 
                 // Add InstructionsBuilder to FlowBuilder
-                flowBuilder.setInstructions(isb.build());
+                InstructionUtils.setFlowBuilderInstruction(flowBuilder, instruction);
                 writeFlow(flowBuilder, nodeBuilder);
             }
         }
@@ -824,50 +656,44 @@ public class L2ForwardingService extends AbstractServiceInstance implements Conf
 
         String nodeName = OPENFLOW + dpidLong;
 
-        MatchBuilder matchBuilder = new MatchBuilder();
         NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
         FlowBuilder flowBuilder = new FlowBuilder();
 
         // Create the OF Match using MatchBuilder
+        MatchBuilder matchBuilder = new MatchBuilder();
         // Match Vlan ID
-        flowBuilder.setMatch(
-                MatchUtils.createVlanIdMatch(matchBuilder, new VlanId(Integer.valueOf(segmentationId)), true).build());
+        MatchUtils.createVlanIdMatch(matchBuilder, new VlanId(Integer.valueOf(segmentationId)), true);
         // Match DMAC
-        flowBuilder.setMatch(MatchUtils.createDestEthMatch(matchBuilder, new MacAddress("01:00:00:00:00:00"),
-                new MacAddress("01:00:00:00:00:00")).build());
+        MatchUtils.createDestEthMatch(matchBuilder, new MacAddress("01:00:00:00:00:00"),
+                new MacAddress("01:00:00:00:00:00"));
+        flowBuilder.setMatch(matchBuilder.build());
 
-        String flowId = "VlanFloodOut_"+segmentationId+"_"+ethPort;
         // Add Flow Attributes
-        flowBuilder.setId(new FlowId(flowId));
-        FlowKey key = new FlowKey(new FlowId(flowId));
-        flowBuilder.setBarrier(true);
-        flowBuilder.setTableId(getTable());
-        flowBuilder.setKey(key);
-        flowBuilder.setPriority(16384);
-        flowBuilder.setFlowName(flowId);
-        flowBuilder.setHardTimeout(0);
-        flowBuilder.setIdleTimeout(0);
+        String flowName = "VlanFloodOut_" + segmentationId + "_" + ethPort;
+        final FlowId flowId = new FlowId(flowName);
+        flowBuilder
+                .setId(flowId)
+                .setBarrier(true)
+                .setTableId(getTable())
+                .setKey(new FlowKey(flowId))
+                .setPriority(16384)
+                .setFlowName(flowName)
+                .setHardTimeout(0)
+                .setIdleTimeout(0);
 
         //ToDo: Is there something to be done with result of the call to getFlow?
-
         Flow flow = this.getFlow(flowBuilder, nodeBuilder);
-        // Instantiate the Builders for the OF Actions and Instructions
-        InstructionBuilder ib = new InstructionBuilder();
-        InstructionsBuilder isb = new InstructionsBuilder();
-        List<Instruction> instructions = Lists.newArrayList();
 
         if (write) {
             // Set the Output Port/Iface
-            InstructionUtils.createOutputPortInstructions(ib, dpidLong, ethPort);
-            ib.setOrder(0);
-            ib.setKey(new InstructionKey(0));
-            instructions.add(ib.build());
-
-            // Add InstructionBuilder to the Instruction(s)Builder List
-            isb.setInstruction(instructions);
+            Instruction outputPortInstruction =
+                    InstructionUtils.createOutputPortInstructions(new InstructionBuilder(), dpidLong, ethPort)
+                            .setOrder(0)
+                            .setKey(new InstructionKey(0))
+                            .build();
 
             // Add InstructionsBuilder to FlowBuilder
-            flowBuilder.setInstructions(isb.build());
+            InstructionUtils.setFlowBuilderInstruction(flowBuilder, outputPortInstruction);
 
             writeFlow(flowBuilder, nodeBuilder);
         } else {
@@ -886,45 +712,28 @@ public class L2ForwardingService extends AbstractServiceInstance implements Conf
 
         String nodeName = OPENFLOW + dpidLong;
 
-        MatchBuilder matchBuilder = new MatchBuilder();
         NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
         FlowBuilder flowBuilder = new FlowBuilder();
 
         // Create Match(es) and Set them in the FlowBuilder Object
-        flowBuilder.setMatch(MatchUtils.createTunnelIDMatch(matchBuilder, new BigInteger(segmentationId)).build());
+        flowBuilder.setMatch(
+                MatchUtils.createTunnelIDMatch(new MatchBuilder(), new BigInteger(segmentationId)).build());
 
         if (write) {
-            // Create the OF Actions and Instructions
-            InstructionsBuilder isb = new InstructionsBuilder();
-
-            // Instructions List Stores Individual Instructions
-            List<Instruction> instructions = Lists.newArrayList();
-
             // Call the InstructionBuilder Methods Containing Actions
-            InstructionBuilder ib = this.getMutablePipelineInstructionBuilder();
-            ib.setOrder(0);
-            ib.setKey(new InstructionKey(0));
-            instructions.add(ib.build());
-
-            // Add InstructionBuilder to the Instruction(s)Builder List
-            isb.setInstruction(instructions);
+            Instruction mutablePipelineInstruction = getMutablePipelineInstructionBuilder()
+                    .setOrder(0)
+                    .setKey(new InstructionKey(0))
+                    .build();
 
             // Add InstructionsBuilder to FlowBuilder
-            flowBuilder.setInstructions(isb.build());
+            InstructionUtils.setFlowBuilderInstruction(flowBuilder, mutablePipelineInstruction);
         }
 
-        String flowId = "TunnelMiss_"+segmentationId;
         // Add Flow Attributes
-        flowBuilder.setId(new FlowId(flowId));
-        FlowKey key = new FlowKey(new FlowId(flowId));
-        flowBuilder.setStrict(true);
-        flowBuilder.setBarrier(false);
-        flowBuilder.setTableId(getTable());
-        flowBuilder.setKey(key);
-        flowBuilder.setPriority(8192);
-        flowBuilder.setFlowName(flowId);
-        flowBuilder.setHardTimeout(0);
-        flowBuilder.setIdleTimeout(0);
+        String flowName = "TunnelMiss_" + segmentationId;
+        FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable())
+                .setPriority(8192);
         if (write) {
             writeFlow(flowBuilder, nodeBuilder);
         } else {
@@ -945,47 +754,30 @@ public class L2ForwardingService extends AbstractServiceInstance implements Conf
 
         String nodeName = OPENFLOW + dpidLong;
 
-        MatchBuilder matchBuilder = new MatchBuilder();
         NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
         FlowBuilder flowBuilder = new FlowBuilder();
 
         // Create Match(es) and Set them in the FlowBuilder Object
         flowBuilder.setMatch(
-                MatchUtils.createVlanIdMatch(matchBuilder, new VlanId(Integer.valueOf(segmentationId)), true).build());
+                MatchUtils.createVlanIdMatch(new MatchBuilder(), new VlanId(Integer.valueOf(segmentationId)),
+                        true).build());
 
         if (write) {
-            // Create the OF Actions and Instructions
-            InstructionBuilder ib = new InstructionBuilder();
-            InstructionsBuilder isb = new InstructionsBuilder();
-
-            // Instructions List Stores Individual Instructions
-            List<Instruction> instructions = Lists.newArrayList();
-
             // Set the Output Port/Iface
-            InstructionUtils.createOutputPortInstructions(ib, dpidLong, ethPort);
-            ib.setOrder(0);
-            ib.setKey(new InstructionKey(1));
-            instructions.add(ib.build());
-
-            // Add InstructionBuilder to the Instruction(s)Builder List
-            isb.setInstruction(instructions);
+            Instruction outputPortInstruction =
+                    InstructionUtils.createOutputPortInstructions(new InstructionBuilder(), dpidLong, ethPort)
+                            .setOrder(0)
+                            .setKey(new InstructionKey(1))
+                            .build();
 
             // Add InstructionsBuilder to FlowBuilder
-            flowBuilder.setInstructions(isb.build());
+            InstructionUtils.setFlowBuilderInstruction(flowBuilder, outputPortInstruction);
         }
 
-        String flowId = "VlanMiss_"+segmentationId;
         // Add Flow Attributes
-        flowBuilder.setId(new FlowId(flowId));
-        FlowKey key = new FlowKey(new FlowId(flowId));
-        flowBuilder.setStrict(true);
-        flowBuilder.setBarrier(false);
-        flowBuilder.setTableId(getTable());
-        flowBuilder.setKey(key);
-        flowBuilder.setPriority(8192);
-        flowBuilder.setFlowName(flowId);
-        flowBuilder.setHardTimeout(0);
-        flowBuilder.setIdleTimeout(0);
+        String flowName = "VlanMiss_" + segmentationId;
+        FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable())
+                .setPriority(8192);
         if (write) {
             writeFlow(flowBuilder, nodeBuilder);
         } else {
@@ -1007,7 +799,7 @@ public class L2ForwardingService extends AbstractServiceInstance implements Conf
         NodeConnectorId ncid = new NodeConnectorId(OPENFLOW + dpidLong + ":" + port);
         LOG.debug("createOutputPortInstructions() Node Connector ID is - Type=openflow: DPID={} port={} existingInstructions={}", dpidLong, port, instructions);
 
-        List<Action> actionList = Lists.newArrayList();
+        List<Action> actionList = new ArrayList<>();
         ActionBuilder ab = new ActionBuilder();
 
         List<Action> existingActions;
index b09e06199bbef2e2022e5be93b41b962091bc735..f6dcea1a857e373585a926764eb709ca5c4f5c4a 100644 (file)
@@ -77,11 +77,10 @@ public interface SecurityServicesManager {
     boolean isLastPortinBridge(Node node, OvsdbTerminationPointAugmentation intf);
     /**
      * Returns the  list of ip address assigned to the interface.
-     * @param node The node to which the intf is connected.
      * @param intf the intf
      * @return the list of ip address associated with the vm
      */
-    List<Neutron_IPs> getIpAddressList(Node node, OvsdbTerminationPointAugmentation intf);
+    List<Neutron_IPs> getIpAddressList(OvsdbTerminationPointAugmentation intf);
     /**
      * Get the list of vm belonging to a security group.
      * @param portUuid the uuid of the port.
index aa9b946d9004c7e0dc95c22de883589e29fdd2c1..55f8fbf79ee26654c3e3bbdf8a5719d0afc72aad 100644 (file)
@@ -280,8 +280,7 @@ public class SecurityServicesImpl implements ConfigInterface, SecurityServicesMa
     }
 
     @Override
-    public List<Neutron_IPs> getIpAddressList(Node node,
-                                          OvsdbTerminationPointAugmentation terminationPointAugmentation) {
+    public List<Neutron_IPs> getIpAddressList(OvsdbTerminationPointAugmentation terminationPointAugmentation) {
         if (neutronPortCache == null) {
             LOG.error("getIpAddress: neutron port is null");
             return null;
diff --git a/openstack/net-virt/src/test/java/org/opendaylight/ovsdb/openstack/netvirt/impl/SecurityGroupCacheManagerImplTest.java b/openstack/net-virt/src/test/java/org/opendaylight/ovsdb/openstack/netvirt/impl/SecurityGroupCacheManagerImplTest.java
new file mode 100644 (file)
index 0000000..eaa2579
--- /dev/null
@@ -0,0 +1,204 @@
+/*
+ * Copyright (c) 2015 Hewlett-Packard Enterprise 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.ovsdb.openstack.netvirt.impl;
+
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyBoolean;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.opendaylight.ovsdb.openstack.netvirt.api.SecurityServicesManager;
+import org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronPort;
+import org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronSecurityGroup;
+import org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronSecurityRule;
+import org.opendaylight.ovsdb.openstack.netvirt.translator.Neutron_IPs;
+import org.opendaylight.ovsdb.openstack.netvirt.translator.crud.INeutronPortCRUD;
+import org.opendaylight.ovsdb.openstack.netvirt.translator.crud.INeutronSecurityGroupCRUD;
+import org.opendaylight.ovsdb.utils.servicehelper.ServiceHelper;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+/**
+ * Unit test fort {@link SecurityGroupCacheManagerImpl}
+ */
+@RunWith(PowerMockRunner.class)
+@PrepareForTest(ServiceHelper.class)
+public class SecurityGroupCacheManagerImplTest {
+
+    @InjectMocks private SecurityGroupCacheManagerImpl securityGroupCacheManagerImpl;
+    @Mock private INeutronPortCRUD neutronPortCache;
+    @Mock private INeutronSecurityGroupCRUD securityGroupCache;
+    @Mock NeutronPort neutronPort_Vm1;
+    @Mock NeutronPort neutronPort_Vm2;
+    @Mock NeutronPort neutronPort_Vm3;
+    @Mock NeutronPort neutronPort_Vm4;
+    @Mock NeutronPort neutronPort_Vm5;
+    @Mock SecurityServicesManager securityServicesManager;
+    @Mock NeutronSecurityGroup neutronSecurityGroup_1;
+    @Mock NeutronSecurityGroup neutronSecurityGroup_2;
+    @Mock NeutronSecurityGroup neutronSecurityGroup_3;
+    @Mock NeutronSecurityRule neutronSecurityRule_1;
+    @Mock NeutronSecurityRule neutronSecurityRule_2;
+    @Mock NeutronSecurityRule neutronSecurityRule_3;
+    @Mock Neutron_IPs neutron_ip_1;
+    @Mock Neutron_IPs neutron_ip_2;
+    @Mock Neutron_IPs neutron_ip_3;
+    @Mock Neutron_IPs neutron_ip_4;
+    @Mock Neutron_IPs neutron_ip_5;
+
+    private static final String NEUTRON_PORT_ID_VM_1 = "neutronID_VM_1";
+    private static final String NEUTRON_PORT_ID_VM_2 = "neutronID_VM_2";
+    private static final String NEUTRON_PORT_ID_VM_3 = "neutronID_VM_3";
+    private static final String NEUTRON_PORT_ID_VM_4 = "neutronID_VM_4";
+    private static final String NEUTRON_PORT_ID_VM_5 = "neutronID_VM_5";
+    private static final String SECURITY_GROUP_ID_1 = "securityGroupId_1";
+    private static final String SECURITY_GROUP_ID_2 = "securityGroupId_2";
+    private static final String SECURITY_GROUP_ID_3 = "securityGroupId_3";
+    private static final List<Neutron_IPs> neutron_IPs_1 = new ArrayList<>();
+    private static final List<Neutron_IPs> neutron_IPs_2 = new ArrayList<>();
+    private static final List<Neutron_IPs> neutron_IPs_3 = new ArrayList<>();
+    private static final List<Neutron_IPs> neutron_IPs_4 = new ArrayList<>();
+    private static final List<Neutron_IPs> neutron_IPs_5 = new ArrayList<>();
+
+    @Before
+    public void setUp() throws Exception {
+
+        List<NeutronSecurityGroup> securityGroups_Vm_1 = new ArrayList<>();
+        securityGroups_Vm_1.add(neutronSecurityGroup_1);
+        List<NeutronSecurityGroup> securityGroups_Vm_2 = new ArrayList<>();
+        securityGroups_Vm_2.add(neutronSecurityGroup_2);
+        List<NeutronSecurityGroup> securityGroups_Vm_3 = new ArrayList<>();
+        securityGroups_Vm_3.add(neutronSecurityGroup_3);
+        List<NeutronSecurityRule> securityRule_1 = new ArrayList<>();
+        securityRule_1.add(neutronSecurityRule_1);
+        List<NeutronSecurityRule> securityRule_2 = new ArrayList<>();
+        securityRule_2.add(neutronSecurityRule_2);
+        List<NeutronSecurityRule> securityRule_3 = new ArrayList<>();
+        securityRule_3.add(neutronSecurityRule_3);
+
+        neutron_IPs_1.add(neutron_ip_1);
+        neutron_IPs_2.add(neutron_ip_2);
+        neutron_IPs_3.add(neutron_ip_3);
+        neutron_IPs_4.add(neutron_ip_4);
+        neutron_IPs_5.add(neutron_ip_5);
+
+        when(neutronPort_Vm1.getID()).thenReturn(NEUTRON_PORT_ID_VM_1);
+        when(neutronPort_Vm2.getID()).thenReturn(NEUTRON_PORT_ID_VM_2);
+        when(neutronPort_Vm3.getID()).thenReturn(NEUTRON_PORT_ID_VM_3);
+        when(neutronPort_Vm4.getID()).thenReturn(NEUTRON_PORT_ID_VM_4);
+        when(neutronPort_Vm5.getID()).thenReturn(NEUTRON_PORT_ID_VM_5);
+        when(neutronPort_Vm1.getSecurityGroups()).thenReturn(securityGroups_Vm_1);
+        when(neutronPort_Vm2.getSecurityGroups()).thenReturn(securityGroups_Vm_1);
+        when(neutronPort_Vm3.getSecurityGroups()).thenReturn(securityGroups_Vm_3);
+        when(neutronPort_Vm4.getSecurityGroups()).thenReturn(securityGroups_Vm_1);
+        when(neutronPort_Vm5.getSecurityGroups()).thenReturn(securityGroups_Vm_3);
+        when(neutronSecurityGroup_1.getSecurityRules()).thenReturn(securityRule_1);
+        when(neutronSecurityGroup_2.getSecurityRules()).thenReturn(securityRule_2);
+        when(neutronSecurityGroup_3.getSecurityRules()).thenReturn(securityRule_3);
+        when(neutronSecurityGroup_1.getSecurityGroupUUID()).thenReturn(SECURITY_GROUP_ID_1);
+        when(neutronSecurityGroup_2.getSecurityGroupUUID()).thenReturn(SECURITY_GROUP_ID_2);
+        when(neutronSecurityGroup_3.getSecurityGroupUUID()).thenReturn(SECURITY_GROUP_ID_3);
+        when(neutronSecurityRule_1.getSecurityRemoteGroupID()).thenReturn(SECURITY_GROUP_ID_1);
+        when(neutronSecurityRule_3.getSecurityRemoteGroupID()).thenReturn(SECURITY_GROUP_ID_2);
+        when(neutronPort_Vm1.getFixedIPs()).thenReturn(neutron_IPs_1);
+        when(neutronPort_Vm2.getFixedIPs()).thenReturn(neutron_IPs_2);
+        when(neutronPort_Vm3.getFixedIPs()).thenReturn(neutron_IPs_3);
+        when(neutronPortCache.getPort(eq(NEUTRON_PORT_ID_VM_1))).thenReturn(neutronPort_Vm1);
+        when(neutronPortCache.getPort(eq(NEUTRON_PORT_ID_VM_2))).thenReturn(neutronPort_Vm2);
+        when(neutronPortCache.getPort(eq(NEUTRON_PORT_ID_VM_3))).thenReturn(neutronPort_Vm3);
+    }
+
+    /**
+     * Remote Cache is empty a new port is added.
+     */
+    @Test
+    public void testPortAddedWithNoRemoteSGInCache() {
+        securityGroupCacheManagerImpl.portAdded(SECURITY_GROUP_ID_1, NEUTRON_PORT_ID_VM_1);
+        verify(securityServicesManager, times(0)).syncSecurityRule(any(NeutronPort.class), any(NeutronSecurityRule.class), any(Neutron_IPs.class),anyBoolean());
+    }
+
+    /**
+     * Remote Cache is empty a new port is removed.
+     */
+    @Test
+    public void testPortRemovedWithNoRemoteSGInCache() {
+        securityGroupCacheManagerImpl.addToCache(SECURITY_GROUP_ID_1, NEUTRON_PORT_ID_VM_1);
+        securityGroupCacheManagerImpl.portRemoved(SECURITY_GROUP_ID_1, NEUTRON_PORT_ID_VM_1);
+        verify(securityServicesManager, times(0)).syncSecurityRule(any(NeutronPort.class), any(NeutronSecurityRule.class), any(Neutron_IPs.class),anyBoolean());
+    }
+
+    /**
+     * neutronSecurityGroup_1 has a rule which has neutronSecurityGroup_1 as remote SG.
+     * A port with neutronSecurityGroup_1 is present in cache and new one is added.
+     */
+    @Test
+    public void testPortAddedWithSelfInCache() {
+        securityGroupCacheManagerImpl.addToCache(SECURITY_GROUP_ID_1, NEUTRON_PORT_ID_VM_1);
+        securityGroupCacheManagerImpl.portAdded(SECURITY_GROUP_ID_1, NEUTRON_PORT_ID_VM_1);
+        securityGroupCacheManagerImpl.addToCache(SECURITY_GROUP_ID_1, NEUTRON_PORT_ID_VM_2);
+        securityGroupCacheManagerImpl.portAdded(SECURITY_GROUP_ID_1, NEUTRON_PORT_ID_VM_2);
+        verify(securityServicesManager, times(1)).syncSecurityRule(eq(neutronPort_Vm1), eq(neutronSecurityRule_1), eq(neutron_ip_2),eq(true));
+    }
+
+    /**
+     * neutronSecurityGroup_1 has a rule which has neutronSecurityGroup_1 as remote SG.
+     * Two port with neutronSecurityGroup_1 is present in cache and  one of them is removed.
+     */
+    @Test
+    public void testPortRemovedWithSelfInCache() {
+        securityGroupCacheManagerImpl.addToCache(SECURITY_GROUP_ID_1, NEUTRON_PORT_ID_VM_1);
+        securityGroupCacheManagerImpl.addToCache(SECURITY_GROUP_ID_1, NEUTRON_PORT_ID_VM_2);
+        securityGroupCacheManagerImpl.portRemoved(SECURITY_GROUP_ID_1, NEUTRON_PORT_ID_VM_2);
+        verify(securityServicesManager, times(1)).syncSecurityRule(eq(neutronPort_Vm1), eq(neutronSecurityRule_1), eq(neutron_ip_2),eq(false));
+    }
+
+    /**
+     * neutronSecurityGroup_3 has a rule which has neutronSecurityGroup_2 as remote SG.
+     * A port with neutronSecurityGroup_3 is present in cache. A new port is added with
+     * neutronSecurityGroup_2 as security group.
+     */
+    @Test
+    public void testPortAddedWithCidrInCache() {
+        securityGroupCacheManagerImpl.addToCache(SECURITY_GROUP_ID_2, NEUTRON_PORT_ID_VM_3);
+        securityGroupCacheManagerImpl.portAdded(SECURITY_GROUP_ID_2, NEUTRON_PORT_ID_VM_2);
+        verify(securityServicesManager, times(1)).syncSecurityRule(eq(neutronPort_Vm3), eq(neutronSecurityRule_3), eq(neutron_ip_2),eq(true));
+    }
+
+    /**
+     * neutronSecurityGroup_3 has a rule which has neutronSecurityGroup_2 as remote SG.
+     * A port with neutronSecurityGroup_3 is present in cache. A  port with
+     * neutronSecurityGroup_2 as security group is removed..
+     */
+    @Test
+    public void testPortRemovedWithCidrInCache() {
+        securityGroupCacheManagerImpl.addToCache(SECURITY_GROUP_ID_2, NEUTRON_PORT_ID_VM_3);
+        securityGroupCacheManagerImpl.portRemoved(SECURITY_GROUP_ID_2, NEUTRON_PORT_ID_VM_2);
+        verify(securityServicesManager, times(1)).syncSecurityRule(eq(neutronPort_Vm3), eq(neutronSecurityRule_3), eq(neutron_ip_2),eq(false));
+    }
+
+    /**
+     *  A port is removed from the cache.
+     */
+    @Test
+    public void testPortRemovedFromCache() {
+        securityGroupCacheManagerImpl.addToCache(SECURITY_GROUP_ID_2, NEUTRON_PORT_ID_VM_3);
+        securityGroupCacheManagerImpl.removeFromCache(SECURITY_GROUP_ID_2, NEUTRON_PORT_ID_VM_3);
+        securityGroupCacheManagerImpl.portRemoved(SECURITY_GROUP_ID_2, NEUTRON_PORT_ID_VM_2);
+        verify(securityServicesManager, times(0)).syncSecurityRule(any(NeutronPort.class), any(NeutronSecurityRule.class), any(Neutron_IPs.class),anyBoolean());
+    }
+}
index b0628218a19699c640911323eaa86836de67ee4e..bd048aa291817188291ab90cb21caaa9ad42db5c 100644 (file)
@@ -9,9 +9,13 @@ package org.opendaylight.ovsdb.openstack.netvirt.impl;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
 import static org.mockito.Matchers.any;
 import static org.mockito.Matchers.anyString;
+import static org.mockito.Matchers.eq;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
 import java.lang.reflect.Field;
@@ -23,13 +27,24 @@ import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.mockito.InjectMocks;
 import org.mockito.Mock;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronNetwork;
 import org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronPort;
 import org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronSecurityGroup;
+import org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronSecurityRule;
+import org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronSubnet;
+import org.opendaylight.ovsdb.openstack.netvirt.translator.Neutron_IPs;
+import org.opendaylight.ovsdb.openstack.netvirt.translator.crud.INeutronNetworkCRUD;
 import org.opendaylight.ovsdb.openstack.netvirt.translator.crud.INeutronPortCRUD;
+import org.opendaylight.ovsdb.openstack.netvirt.translator.crud.INeutronSubnetCRUD;
+import org.opendaylight.ovsdb.openstack.netvirt.api.ConfigurationService;
+import org.opendaylight.ovsdb.openstack.netvirt.api.EgressAclProvider;
+import org.opendaylight.ovsdb.openstack.netvirt.api.IngressAclProvider;
 import org.opendaylight.ovsdb.openstack.netvirt.api.Southbound;
 import org.opendaylight.ovsdb.utils.servicehelper.ServiceHelper;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbTerminationPointAugmentation;
-
+import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.osgi.framework.ServiceReference;
 import org.powermock.api.mockito.PowerMockito;
 import org.powermock.core.classloader.annotations.PrepareForTest;
@@ -43,27 +58,108 @@ import org.powermock.modules.junit4.PowerMockRunner;
 public class SecurityServicesImplTest {
 
     @InjectMocks private SecurityServicesImpl securityServicesImpl;
-
+    @Mock INeutronNetworkCRUD neutronNetworkCache;
     @Mock private INeutronPortCRUD neutronPortCache;
+    @Mock private INeutronSubnetCRUD subNetCache;
     @Mock private Southbound southbound;
+    @Mock private ConfigurationService configurationService;
+    @Mock NeutronNetwork neutronNetwork;
+    @Mock NeutronPort neutronPort_Vm1;
+    @Mock NeutronPort neutronPort_Vm2;
+    @Mock NeutronPort neutronPort_Vm3;
+    @Mock NeutronSecurityGroup neutronSecurityGroup_1;
+    @Mock NeutronSecurityGroup neutronSecurityGroup_2;
+    @Mock NeutronSecurityGroup neutronSecurityGroup_3;
+    @Mock NeutronSecurityRule neutronSecurityRule_1;
+    @Mock NeutronSecurityRule neutronSecurityRule_2;
+    @Mock NeutronSecurityRule neutronSecurityRule_3;
+    @Mock  NeutronPort neutronPort_Dhcp;
+    @Mock Neutron_IPs neutron_ip_1;
+    @Mock Neutron_IPs neutron_ip_2;
+    @Mock Neutron_IPs neutron_ip_3;
+    @Mock NeutronSubnet subnet;
+    @Mock Node node;
+    @Mock OvsdbTerminationPointAugmentation tp;
+    @Mock IngressAclProvider ingressAclService;
+    @Mock EgressAclProvider egressAclService;
 
-    @Mock private NeutronSecurityGroup neutronSecurityGroup;
-
-    private static final String NEUTRON_PORT_ID = "neutronID";
-    private static final String DEVICE_OWNER = "compute";
+    private static final String NEUTRON_PORT_ID_VM_1 = "neutronID_VM_1";
+    private static final String NEUTRON_PORT_ID_VM_2 = "neutronID_VM_2";
+    private static final String NEUTRON_PORT_ID_VM_3 = "neutronID_VM_3";
+    private static final String NEUTRON_PORT_ID_DHCP = "neutronID_VM_DHCP";
+    private static final String SECURITY_GROUP_ID_1 = "securityGroupId_1";
+    private static final String SECURITY_GROUP_ID_2 = "securityGroupId_2";
+    private static final String SECURITY_GROUP_ID_3 = "securityGroupId_3";
+    private static final String DEVICE_OWNER_VM = "compute";
+    private static final String DEVICE_OWNER_DHCP = "dhcp";
+    private static final String SUBNET_UUID = "subnet_uuid";
+    private static final List<Neutron_IPs> neutron_IPs_1 = new ArrayList<>();
+    private static final List<Neutron_IPs> neutron_IPs_2 = new ArrayList<>();
+    private static final List<Neutron_IPs> neutron_IPs_3 = new ArrayList<>();
 
     @Before
     public void setUp(){
-        NeutronPort neutronPort = mock(NeutronPort.class);
+        List<NeutronSecurityGroup> securityGroups_1 = new ArrayList<>();
+        securityGroups_1.add(neutronSecurityGroup_1);
+        List<NeutronSecurityGroup> securityGroups_2 = new ArrayList<>();
+        securityGroups_2.add(neutronSecurityGroup_2);
+        List<NeutronSecurityGroup> securityGroups_3 = new ArrayList<>();
+        securityGroups_3.add(neutronSecurityGroup_3);
+        List<NeutronSecurityRule> securityRule_1 = new ArrayList<>();
+        securityRule_1.add(neutronSecurityRule_1);
+        List<NeutronSecurityRule> securityRule_2 = new ArrayList<>();
+        securityRule_1.add(neutronSecurityRule_2);
+        List<NeutronSecurityRule> securityRule_3 = new ArrayList<>();
+        securityRule_1.add(neutronSecurityRule_3);
 
-        List<NeutronSecurityGroup> securityGroups = new ArrayList<>();
-        securityGroups.add(neutronSecurityGroup);
+        neutron_IPs_1.add(neutron_ip_1);
+        neutron_IPs_2.add(neutron_ip_2);
+        neutron_IPs_3.add(neutron_ip_3);
 
-        when(neutronPort.getSecurityGroups()).thenReturn(securityGroups);
-        when(neutronPort.getDeviceOwner()).thenReturn(DEVICE_OWNER);
+        when(neutronPort_Vm1.getID()).thenReturn(NEUTRON_PORT_ID_VM_1);
+        when(neutronPort_Vm2.getID()).thenReturn(NEUTRON_PORT_ID_VM_2);
+        when(neutronPort_Vm3.getID()).thenReturn(NEUTRON_PORT_ID_VM_3);
+        when(neutronPort_Vm1.getSecurityGroups()).thenReturn(securityGroups_1);
+        when(neutronPort_Vm2.getSecurityGroups()).thenReturn(securityGroups_2);
+        when(neutronPort_Vm3.getSecurityGroups()).thenReturn(securityGroups_3);
+        when(neutronSecurityGroup_1.getSecurityRules()).thenReturn(securityRule_1);
+        when(neutronSecurityGroup_2.getSecurityRules()).thenReturn(securityRule_2);
+        when(neutronSecurityGroup_3.getSecurityRules()).thenReturn(securityRule_3);
+        when(neutronSecurityGroup_1.getSecurityGroupUUID()).thenReturn(SECURITY_GROUP_ID_1);
+        when(neutronSecurityGroup_2.getSecurityGroupUUID()).thenReturn(SECURITY_GROUP_ID_2);
+        when(neutronSecurityGroup_3.getSecurityGroupUUID()).thenReturn(SECURITY_GROUP_ID_3);
+        when(neutronPort_Vm1.getDeviceOwner()).thenReturn(DEVICE_OWNER_VM);
+        when(neutronPort_Vm2.getDeviceOwner()).thenReturn(DEVICE_OWNER_VM);
+        when(neutronPort_Vm3.getDeviceOwner()).thenReturn(DEVICE_OWNER_VM);
+        when(neutronPort_Dhcp.getDeviceOwner()).thenReturn(DEVICE_OWNER_DHCP);
+        when(neutronPort_Vm1.getFixedIPs()).thenReturn(neutron_IPs_1);
+        when(neutronPort_Vm2.getFixedIPs()).thenReturn(neutron_IPs_2);
+        when(neutronPort_Vm3.getFixedIPs()).thenReturn(neutron_IPs_3);
+        when(neutron_ip_1.getSubnetUUID()).thenReturn(SUBNET_UUID);
+        List<NeutronPort> portList = new ArrayList<>();
+        portList.add(neutronPort_Vm1);
+        portList.add(neutronPort_Dhcp);
+        when(subnet.getPortsInSubnet()).thenReturn(portList);
 
-        when(southbound.getInterfaceExternalIdsValue(any(OvsdbTerminationPointAugmentation.class), anyString())).thenReturn(NEUTRON_PORT_ID);
-        when(neutronPortCache.getPort(anyString())).thenReturn(neutronPort);
+        List<Node> nodeList = new ArrayList<>();
+        nodeList.add(node);
+        List<OvsdbTerminationPointAugmentation> tpList = new ArrayList<>();
+        tpList.add(tp);
+        when(southbound.getInterfaceExternalIdsValue(any(OvsdbTerminationPointAugmentation.class), eq("iface-id"))).thenReturn(NEUTRON_PORT_ID_VM_1);
+        when(southbound.readOvsdbTopologyNodes()).thenReturn(nodeList);
+        when(southbound.getBridgeNode(any(Node.class), anyString())).thenReturn(node);
+        when(southbound.getTerminationPointsOfBridge(node)).thenReturn(tpList);
+        when(southbound.getDataPathId(node)).thenReturn(1L);
+        when(southbound.getBridgeName(node)).thenReturn("br-int");
+        when(southbound.getOFPort(any(OvsdbTerminationPointAugmentation.class))).thenReturn(2L);
+        when(southbound.getInterfaceExternalIdsValue(any(OvsdbTerminationPointAugmentation.class),eq("attached-mac"))).thenReturn("attached-mac");
+        when(configurationService.getIntegrationBridgeName()).thenReturn("br-int");
+        when(neutronNetworkCache.getNetwork(anyString())).thenReturn(neutronNetwork);
+        when(neutronNetwork.getProviderSegmentationID()).thenReturn("1000");
+        when(neutronPortCache.getPort(eq(NEUTRON_PORT_ID_VM_1))).thenReturn(neutronPort_Vm1);
+        when(neutronPortCache.getPort(eq(NEUTRON_PORT_ID_DHCP))).thenReturn(neutronPort_Dhcp);
+        when(neutronPortCache.getAllPorts()).thenReturn(portList);
+        when(subNetCache.getSubnet(eq(SUBNET_UUID))).thenReturn(subnet);
     }
 
     /**
@@ -80,7 +176,401 @@ public class SecurityServicesImplTest {
     @Test
     public void testSecurityGroupInPort(){
         assertEquals("Error, did not return the good neutronSecurityGroup of securityGroups",
-                     neutronSecurityGroup, securityServicesImpl.getSecurityGroupInPortList(mock(OvsdbTerminationPointAugmentation.class)).get(0));
+                     neutronSecurityGroup_1, securityServicesImpl.getSecurityGroupInPortList(mock(OvsdbTerminationPointAugmentation.class)).get(0));
+    }
+
+    /**
+     * Test getDhcpServerPort returning a valid port.
+     */
+    @Test
+    public void testGetDhcpServerPort() {
+        NeutronPort dhcpPort = securityServicesImpl.getDhcpServerPort(mock(OvsdbTerminationPointAugmentation.class));
+        assertEquals(dhcpPort,neutronPort_Dhcp);
+    }
+
+    /**
+     * Test getDhcpServerPort with null port id returned by the southbound.
+     */
+    @Test
+    public void testGetDhcpServerPortWithNullPortId() {
+        when(southbound.getInterfaceExternalIdsValue(any(OvsdbTerminationPointAugmentation.class), anyString())).thenReturn(null);
+        NeutronPort dhcpPort = securityServicesImpl.getDhcpServerPort(mock(OvsdbTerminationPointAugmentation.class));
+        assertEquals(dhcpPort,null);
+    }
+
+    /**
+     * Test getDhcpServerPort with port not present in cache.
+     */
+    @Test
+    public void testGetDhcpServerPortWithNullPort() {
+        when(neutronPortCache.getPort(eq(NEUTRON_PORT_ID_VM_1))).thenReturn(null);
+        NeutronPort dhcpPort = securityServicesImpl.getDhcpServerPort(mock(OvsdbTerminationPointAugmentation.class));
+        assertEquals(dhcpPort,null);
+    }
+
+    /**
+     * Test getDhcpServerPort with a dhcp port as the input port.
+     */
+    @Test
+    public void testGetDhcpServerPortWithDhcpPort() {
+        when(neutronPortCache.getPort(eq(NEUTRON_PORT_ID_VM_1))).thenReturn(neutronPort_Dhcp);
+        NeutronPort dhcpPort = securityServicesImpl.getDhcpServerPort(mock(OvsdbTerminationPointAugmentation.class));
+        assertEquals(dhcpPort,neutronPort_Dhcp);
+    }
+
+    /**
+     * Test getDhcpServerPort with a dhcp port with fixed ip null
+     * for the input port..
+     */
+    @Test
+    public void testGetDhcpServerPortWithFixedIpNull() {
+        when(neutronPort_Vm1.getFixedIPs()).thenReturn(null);
+        NeutronPort dhcpPort = securityServicesImpl.getDhcpServerPort(mock(OvsdbTerminationPointAugmentation.class));
+        assertEquals(dhcpPort,null);
+    }
+
+    /**
+     * Test getDhcpServerPort with a dhcp port with fixed ip empty
+     * for the input port.
+     */
+    @Test
+    public void testGetDhcpServerPortWithFixedIpEmpty() {
+        when(neutronPort_Vm1.getFixedIPs()).thenReturn(new ArrayList<Neutron_IPs>());
+        NeutronPort dhcpPort = securityServicesImpl.getDhcpServerPort(mock(OvsdbTerminationPointAugmentation.class));
+        assertEquals(dhcpPort,null);
+    }
+
+    /**
+     * Test getDhcpServerPort with a dhcp port with no port in subnet.
+     */
+    @Test
+    public void testGetDhcpServerPortWithNoPortinSubnet() {
+        when(subnet.getPortsInSubnet()).thenReturn(new ArrayList<NeutronPort>());
+        NeutronPort dhcpPort = securityServicesImpl.getDhcpServerPort(mock(OvsdbTerminationPointAugmentation.class));
+        assertEquals(dhcpPort,null);
+    }
+
+    /**
+     * Test getNeutronPortFromDhcpIntf with port not present in cache.
+     */
+    @Test
+    public void testGetNeutronPortFromDhcpIntfWithNullPort() {
+        when(neutronPortCache.getPort(eq(NEUTRON_PORT_ID_VM_1))).thenReturn(null);
+        NeutronPort dhcpPort = securityServicesImpl.getNeutronPortFromDhcpIntf(mock(OvsdbTerminationPointAugmentation.class));
+        assertEquals(dhcpPort,null);
+    }
+
+    /**
+     * Test getNeutronPortFromDhcpIntf with port id returned null
+     * from the southbound.
+     */
+    @Test
+    public void testGetNeutronPortFromDhcpIntfWithNullPortId() {
+        when(southbound.getInterfaceExternalIdsValue(any(OvsdbTerminationPointAugmentation.class), anyString())).thenReturn(null);
+        NeutronPort dhcpPort = securityServicesImpl.getNeutronPortFromDhcpIntf(mock(OvsdbTerminationPointAugmentation.class));
+        assertEquals(dhcpPort,null);
+    }
+
+    /**
+     * Test getNeutronPortFromDhcpIntf valid
+     */
+    @Test
+    public void testGetNeutronPortFromDhcpIntfWithDhcpPort() {
+        when(neutronPortCache.getPort(eq(NEUTRON_PORT_ID_VM_1))).thenReturn(neutronPort_Dhcp);
+        NeutronPort dhcpPort = securityServicesImpl.getNeutronPortFromDhcpIntf(mock(OvsdbTerminationPointAugmentation.class));
+        assertEquals(dhcpPort,neutronPort_Dhcp);
+    }
+
+    /**
+     * Test getNeutronPortFromDhcpIntf with the port passed
+     * a vm port.
+     */
+    @Test
+    public void testGetNeutronPortFromDhcpIntfWithVmPort() {
+        NeutronPort dhcpPort = securityServicesImpl.getNeutronPortFromDhcpIntf(mock(OvsdbTerminationPointAugmentation.class));
+        assertEquals(dhcpPort,null);
+    }
+
+    /**
+     * Test isComputePort with the port passed a vm port.
+     */
+    @Test
+    public void testIsComputePortWithComputePort() {
+        boolean isComputePort = securityServicesImpl.isComputePort(mock(OvsdbTerminationPointAugmentation.class));
+        assertEquals(isComputePort,true);
+    }
+
+    /**
+     * Test isComputePort with the port passed a dhcp port.
+     */
+    @Test
+    public void testIsComputePortWithDhcpPort() {
+        when(neutronPortCache.getPort(eq(NEUTRON_PORT_ID_VM_1))).thenReturn(neutronPort_Dhcp);
+        boolean isComputePort = securityServicesImpl.isComputePort(mock(OvsdbTerminationPointAugmentation.class));
+        assertEquals(isComputePort,false);
+    }
+
+    /**
+     * Test isComputePort with port id null from southbound.
+     */
+    @Test
+    public void testIsComputePortWithNullPortId() {
+        when(southbound.getInterfaceExternalIdsValue(any(OvsdbTerminationPointAugmentation.class), anyString())).thenReturn(null);
+        boolean isComputePort = securityServicesImpl.isComputePort(mock(OvsdbTerminationPointAugmentation.class));
+        assertEquals(isComputePort,false);
+    }
+
+    /**
+     * Test isComputePort with port not present in cache.
+     */
+    @Test
+    public void testIsComputePortWithNullPort() {
+        when(neutronPortCache.getPort(eq(NEUTRON_PORT_ID_VM_1))).thenReturn(null);
+        boolean isComputePort = securityServicesImpl.isComputePort(mock(OvsdbTerminationPointAugmentation.class));
+        assertEquals(isComputePort,false);
+    }
+
+    /**
+     * Test getIpAddressList valid.
+     */
+    @Test
+    public void testGetIpAddressList() {
+        List<Neutron_IPs> ipList = securityServicesImpl.getIpAddressList(mock(OvsdbTerminationPointAugmentation.class));
+        assertEquals(ipList,neutron_IPs_1);
+    }
+
+    /**
+     * Test getIpAddressList with port not present in cache..
+     */
+    @Test
+    public void testGetIpAddressListWithNullPort() {
+        when(neutronPortCache.getPort(eq(NEUTRON_PORT_ID_VM_1))).thenReturn(null);
+        List<Neutron_IPs> ipList = securityServicesImpl.getIpAddressList(mock(OvsdbTerminationPointAugmentation.class));
+        assertEquals(ipList,null);
+    }
+
+
+    /**
+     * Test getIpAddressList  with port id null from southbound.
+     */
+    @Test
+    public void testGetIpAddressListWithNullPortId() {
+        when(southbound.getInterfaceExternalIdsValue(any(OvsdbTerminationPointAugmentation.class), anyString())).thenReturn(null);
+        List<Neutron_IPs> ipList = securityServicesImpl.getIpAddressList(mock(OvsdbTerminationPointAugmentation.class));
+        assertEquals(ipList,null);
+    }
+
+    /**
+     * Test getVmListForSecurityGroup valid.
+     */
+    @Test
+    public void testGetVmListForSecurityGroup() {
+        List<NeutronPort> portList = new ArrayList<>();
+        portList.add(neutronPort_Vm1);
+        portList.add(neutronPort_Vm2);
+        portList.add(neutronPort_Vm3);
+        portList.add(neutronPort_Dhcp);
+        when(neutronPortCache.getAllPorts()).thenReturn(portList);
+        List<Neutron_IPs> ipList = securityServicesImpl.getVmListForSecurityGroup(NEUTRON_PORT_ID_VM_1, SECURITY_GROUP_ID_2);
+        assertEquals(ipList,neutron_IPs_2);
+    }
+
+    /**
+     * Test getVmListForSecurityGroup with no vm with the
+     * SG associated..
+     */
+    @Test
+    public void testGetVmListForSecurityGroupWithNoVm() {
+        List<NeutronPort> portList = new ArrayList<>();
+        portList.add(neutronPort_Vm1);
+        portList.add(neutronPort_Vm2);
+        portList.add(neutronPort_Vm3);
+        portList.add(neutronPort_Dhcp);
+        when(neutronPortCache.getAllPorts()).thenReturn(portList);
+        List<Neutron_IPs> ipList = securityServicesImpl.getVmListForSecurityGroup(NEUTRON_PORT_ID_VM_1, SECURITY_GROUP_ID_1);
+        assert(ipList.isEmpty());
+    }
+
+    /**
+     * Test syncSecurityGroup addition
+     */
+    @Test
+    public void testSyncSecurityGroupAddition() {
+        List<NeutronSecurityGroup> securityGroupsList = new ArrayList<>();
+        securityGroupsList.add(neutronSecurityGroup_1);
+        securityServicesImpl.syncSecurityGroup(neutronPort_Vm1, securityGroupsList, true);
+        verify(ingressAclService, times(1)).programPortSecurityGroup(eq(new Long(1)), eq("1000"), eq("attached-mac"), eq(2L), eq(neutronSecurityGroup_1), eq(NEUTRON_PORT_ID_VM_1), eq(true));
+        verify(egressAclService, times(1)).programPortSecurityGroup(eq(new Long(1)), eq("1000"), eq("attached-mac"), eq(2L), eq(neutronSecurityGroup_1), eq(NEUTRON_PORT_ID_VM_1), eq(true));
+    }
+
+    /**
+     * Test syncSecurityGroup deletion
+     */
+    @Test
+    public void testSyncSecurityGroupDeletion() {
+        List<NeutronSecurityGroup> securityGroupsList = new ArrayList<>();
+        securityGroupsList.add(neutronSecurityGroup_1);
+        securityServicesImpl.syncSecurityGroup(neutronPort_Vm1, securityGroupsList, false);
+        verify(ingressAclService, times(1)).programPortSecurityGroup(eq(new Long(1)), eq("1000"), eq("attached-mac"), eq(2L), eq(neutronSecurityGroup_1), eq(NEUTRON_PORT_ID_VM_1), eq(false));
+        verify(egressAclService, times(1)).programPortSecurityGroup(eq(new Long(1)), eq("1000"), eq("attached-mac"), eq(2L), eq(neutronSecurityGroup_1), eq(NEUTRON_PORT_ID_VM_1), eq(false));
+    }
+
+    /**
+     * Test syncSecurityGroup deletion with port null
+     */
+    @Test
+    public void testSyncSecurityGroupPortNull() {
+        List<NeutronSecurityGroup> securityGroupsList = new ArrayList<>();
+        securityGroupsList.add(neutronSecurityGroup_1);
+        securityServicesImpl.syncSecurityGroup(null, securityGroupsList, false);
+        verify(ingressAclService, times(0)).programPortSecurityGroup(eq(new Long(1)), eq("1000"), eq("attached-mac"), eq(2L), eq(neutronSecurityGroup_1), eq(NEUTRON_PORT_ID_VM_1), eq(false));
+        verify(egressAclService, times(0)).programPortSecurityGroup(eq(new Long(1)), eq("1000"), eq("attached-mac"), eq(2L), eq(neutronSecurityGroup_1), eq(NEUTRON_PORT_ID_VM_1), eq(false));
+    }
+
+    /**
+     * Test syncSecurityGroup deletion with Sg null
+     */
+    @Test
+    public void testSyncSecurityGroupSgNull() {
+        List<NeutronSecurityGroup> securityGroupsList = new ArrayList<>();
+        securityGroupsList.add(neutronSecurityGroup_1);
+        when(neutronPort_Vm1.getSecurityGroups()).thenReturn(null);
+        securityServicesImpl.syncSecurityGroup(neutronPort_Vm1, null, false);
+        verify(ingressAclService, times(0)).programPortSecurityGroup(eq(new Long(1)), eq("1000"), eq("attached-mac"), eq(2L), eq(neutronSecurityGroup_1), eq(NEUTRON_PORT_ID_VM_1), eq(false));
+        verify(egressAclService, times(0)).programPortSecurityGroup(eq(new Long(1)), eq("1000"), eq("attached-mac"), eq(2L), eq(neutronSecurityGroup_1), eq(NEUTRON_PORT_ID_VM_1), eq(false));
+    }
+
+    /**
+     * Test syncSecurityGroup deletion with Mac null
+     */
+    @Test
+    public void testSyncSecurityGroupAttachedMacNull() {
+        List<NeutronSecurityGroup> securityGroupsList = new ArrayList<>();
+        securityGroupsList.add(neutronSecurityGroup_1);
+        when(southbound.getInterfaceExternalIdsValue(any(OvsdbTerminationPointAugmentation.class),eq("attached-mac"))).thenReturn(null);
+        securityServicesImpl.syncSecurityGroup(neutronPort_Vm1, securityGroupsList, false);
+        verify(ingressAclService, times(0)).programPortSecurityGroup(eq(new Long(1)), eq("1000"), eq("attached-mac"), eq(2L), eq(neutronSecurityGroup_1), eq(NEUTRON_PORT_ID_VM_1), eq(false));
+        verify(egressAclService, times(0)).programPortSecurityGroup(eq(new Long(1)), eq("1000"), eq("attached-mac"), eq(2L), eq(neutronSecurityGroup_1), eq(NEUTRON_PORT_ID_VM_1), eq(false));
+    }
+
+    /**
+     * Test syncSecurityRule addition of egress rule.
+     */
+    @Test
+    public void testSyncSecurityRuleAdditionEgress() {
+        List<NeutronSecurityRule> securityRuleList = new ArrayList<>();
+        securityRuleList.add(neutronSecurityRule_1);
+        when(neutronSecurityRule_1.getSecurityRuleDirection()).thenReturn("egress");
+        when(neutronSecurityRule_1.getSecurityRuleEthertype()).thenReturn("IPv4");
+        securityServicesImpl.syncSecurityRule(neutronPort_Vm1, neutronSecurityRule_1, neutron_ip_1, true);
+        verify(egressAclService, times(1)).programPortSecurityRule(eq(new Long(1)), eq("1000"), eq("attached-mac"), eq(2L), eq(neutronSecurityRule_1), eq(neutron_ip_1), eq(true));
+    }
+
+    /**
+     * Test syncSecurityRule addition of ingress rule.
+     */
+    @Test
+    public void testSyncSecurityRuleAdditionIngress() {
+        List<NeutronSecurityRule> securityRuleList = new ArrayList<>();
+        securityRuleList.add(neutronSecurityRule_1);
+        when(neutronSecurityRule_1.getSecurityRuleDirection()).thenReturn("ingress");
+        when(neutronSecurityRule_1.getSecurityRuleEthertype()).thenReturn("IPv4");
+        securityServicesImpl.syncSecurityRule(neutronPort_Vm1, neutronSecurityRule_1, neutron_ip_1, true);
+        verify(ingressAclService, times(1)).programPortSecurityRule(eq(new Long(1)), eq("1000"), eq("attached-mac"), eq(2L), eq(neutronSecurityRule_1), eq(neutron_ip_1), eq(true));
+    }
+
+    /**
+     * Test syncSecurityRule deletion of egress rule.
+     */
+    @Test
+    public void testSyncSecurityRuleDeletionEgress() {
+        List<NeutronSecurityRule> securityRuleList = new ArrayList<>();
+        securityRuleList.add(neutronSecurityRule_1);
+        when(neutronSecurityRule_1.getSecurityRuleDirection()).thenReturn("egress");
+        when(neutronSecurityRule_1.getSecurityRuleEthertype()).thenReturn("IPv4");
+        securityServicesImpl.syncSecurityRule(neutronPort_Vm1, neutronSecurityRule_1, neutron_ip_1, false);
+        verify(egressAclService, times(1)).programPortSecurityRule(eq(new Long(1)), eq("1000"), eq("attached-mac"), eq(2L), eq(neutronSecurityRule_1), eq(neutron_ip_1), eq(false));
+    }
+
+    /**
+     * Test syncSecurityRule deletion of ingress rule.
+     */
+    @Test
+    public void testSyncSecurityRuleDeletionIngress() {
+        List<NeutronSecurityRule> securityRuleList = new ArrayList<>();
+        securityRuleList.add(neutronSecurityRule_1);
+        when(neutronSecurityRule_1.getSecurityRuleDirection()).thenReturn("ingress");
+        when(neutronSecurityRule_1.getSecurityRuleEthertype()).thenReturn("IPv4");
+        securityServicesImpl.syncSecurityRule(neutronPort_Vm1, neutronSecurityRule_1, neutron_ip_1, false);
+        verify(ingressAclService, times(1)).programPortSecurityRule(eq(new Long(1)), eq("1000"), eq("attached-mac"), eq(2L), eq(neutronSecurityRule_1), eq(neutron_ip_1), eq(false));
+    }
+
+    /**
+     * Test syncSecurityRule deletion of ingress rule with port null.
+     */
+    @Test
+    public void testSyncSecurityRuleDeletionIngressPortNull() {
+        List<NeutronSecurityRule> securityRuleList = new ArrayList<>();
+        securityRuleList.add(neutronSecurityRule_1);
+        when(neutronSecurityRule_1.getSecurityRuleDirection()).thenReturn("ingress");
+        when(neutronSecurityRule_1.getSecurityRuleEthertype()).thenReturn("IPv4");
+        securityServicesImpl.syncSecurityRule(null, neutronSecurityRule_1, neutron_ip_1, false);
+        verify(ingressAclService, times(0)).programPortSecurityRule(eq(new Long(1)), eq("1000"), eq("attached-mac"), eq(2L), eq(neutronSecurityRule_1), eq(neutron_ip_1), eq(false));
+    }
+
+    /**
+     * Test syncSecurityRule deletion of ingress rule with sg null.
+     */
+    @Test
+    public void testSyncSecurityRuleDeletionIngressSgNull() {
+        List<NeutronSecurityRule> securityRuleList = new ArrayList<>();
+        securityRuleList.add(neutronSecurityRule_1);
+        when(neutronPort_Vm1.getSecurityGroups()).thenReturn(null);
+        when(neutronSecurityRule_1.getSecurityRuleDirection()).thenReturn("ingress");
+        when(neutronSecurityRule_1.getSecurityRuleEthertype()).thenReturn("IPv4");
+        securityServicesImpl.syncSecurityRule(neutronPort_Vm1, neutronSecurityRule_1, neutron_ip_1, false);
+        verify(ingressAclService, times(0)).programPortSecurityRule(eq(new Long(1)), eq("1000"), eq("attached-mac"), eq(2L), eq(neutronSecurityRule_1), eq(neutron_ip_1), eq(false));
+    }
+
+    /**
+     * Test syncSecurityRule deletion of ingress rule with mac null.
+     */
+    @Test
+    public void testSyncSecurityRuleDeletionIngressAttachedMacNull() {
+        List<NeutronSecurityRule> securityRuleList = new ArrayList<>();
+        securityRuleList.add(neutronSecurityRule_1);
+        when(neutronSecurityRule_1.getSecurityRuleDirection()).thenReturn("ingress");
+        when(neutronSecurityRule_1.getSecurityRuleEthertype()).thenReturn("IPv4");
+        when(southbound.getInterfaceExternalIdsValue(any(OvsdbTerminationPointAugmentation.class),eq("attached-mac"))).thenReturn(null);
+        securityServicesImpl.syncSecurityRule(neutronPort_Vm1, neutronSecurityRule_1, neutron_ip_1, false);
+        verify(ingressAclService, times(0)).programPortSecurityRule(eq(new Long(1)), eq("1000"), eq("attached-mac"), eq(2L), eq(neutronSecurityRule_1), eq(neutron_ip_1), eq(false));
+    }
+
+
+    /**
+     * Test syncSecurityRule deletion of ingress rule no ipv4 ether.
+     */
+    @Test
+    public void testSyncSecurityRuleDeletionIngressNonIpV4() {
+        List<NeutronSecurityRule> securityRuleList = new ArrayList<>();
+        securityRuleList.add(neutronSecurityRule_1);
+        when(neutronSecurityRule_1.getSecurityRuleDirection()).thenReturn("ingress");
+        when(neutronSecurityRule_1.getSecurityRuleEthertype()).thenReturn("IPv6");
+        securityServicesImpl.syncSecurityRule(neutronPort_Vm1, neutronSecurityRule_1, neutron_ip_1, false);
+        verify(ingressAclService, times(0)).programPortSecurityRule(eq(new Long(1)), eq("1000"), eq("attached-mac"), eq(2L), eq(neutronSecurityRule_1), eq(neutron_ip_1), eq(false));
+    }
+
+    /**
+     * Test syncSecurityRule deletion of ingress rule with invalid direction.
+     */
+    @Test
+    public void testSyncSecurityRuleDeletionInvalidDirection() {
+        List<NeutronSecurityRule> securityRuleList = new ArrayList<>();
+        securityRuleList.add(neutronSecurityRule_1);
+        when(neutronSecurityRule_1.getSecurityRuleDirection()).thenReturn("outgress");
+        when(neutronSecurityRule_1.getSecurityRuleEthertype()).thenReturn("IPv4");
+        securityServicesImpl.syncSecurityRule(neutronPort_Vm1, neutronSecurityRule_1, neutron_ip_1, false);
+        verify(ingressAclService, times(0)).programPortSecurityRule(eq(new Long(1)), eq("1000"), eq("attached-mac"), eq(2L), eq(neutronSecurityRule_1), eq(neutron_ip_1), eq(false));
     }
 
     @Test
index f916026f33ca37d125907a559fb14bec266277db..74fea32479bf269bc184ff771c0d5a82cb35227b 100644 (file)
@@ -19,7 +19,6 @@ 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.Flow;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.OutputPortValues;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
@@ -101,17 +100,31 @@ public class FlowUtils {
         FlowBuilder flowBuilder = new FlowBuilder();
         flowBuilder.setMatch(new MatchBuilder().build());
 
-        String flowId = "DEFAULT_PIPELINE_FLOW_" + table;
-        flowBuilder.setId(new FlowId(flowId));
-        FlowKey key = new FlowKey(new FlowId(flowId));
-        flowBuilder.setStrict(true);
-        flowBuilder.setBarrier(false);
-        flowBuilder.setTableId(table);
-        flowBuilder.setKey(key);
-        flowBuilder.setFlowName(flowId);
-        flowBuilder.setHardTimeout(0);
-        flowBuilder.setIdleTimeout(0);
-        flowBuilder.setPriority(0);
+        String flowName = "DEFAULT_PIPELINE_FLOW_" + table;
+        return initFlowBuilder(flowBuilder, flowName, table)
+                .setPriority(0);
+    }
+
+    /**
+     * Sets up common defaults for the given flow builder: a flow identifier and key based on the given flow name,
+     * strict, no barrier, the given table identifier, no hard timeout and no idle timeout.
+     *
+     * @param flowBuilder The flow builder.
+     * @param flowName The flow name.
+     * @param table The table.
+     * @return The flow builder.
+     */
+    public static FlowBuilder initFlowBuilder(FlowBuilder flowBuilder, String flowName, short table) {
+        final FlowId flowId = new FlowId(flowName);
+        flowBuilder
+                .setId(flowId)
+                .setStrict(true)
+                .setBarrier(false)
+                .setTableId(table)
+                .setKey(new FlowKey(flowId))
+                .setFlowName(flowName)
+                .setHardTimeout(0)
+                .setIdleTimeout(0);
         return flowBuilder;
     }
 }
index 4534e8efc6eeb0d8bec24a36f511b7a7f6e97d11..4c59d45c555d382d70361647de70c6ff9620d4c6 100644 (file)
@@ -43,6 +43,8 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.acti
 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.ActionBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.ActionKey;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.address.address.Ipv4Builder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
+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.OutputPortValues;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.Instructions;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.InstructionsBuilder;
@@ -73,6 +75,7 @@ import org.slf4j.LoggerFactory;
 
 import java.math.BigInteger;
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.List;
 
 public class InstructionUtils {
@@ -1094,6 +1097,37 @@ public class InstructionUtils {
         return getInstructions(applyActionIns(dropAction()));
     }
 
+    /**
+     * Extracts the existing instructions (if any) from the flow.
+     *
+     * @param flow The flow.
+     * @return The instructions in the flow (empty if none).
+     */
+    public static List<Instruction> extractExistingInstructions(Flow flow) {
+        if (flow != null) {
+            Instructions ins = flow.getInstructions();
+            if (ins != null) {
+                return ins.getInstruction();
+            }
+        }
+        return Collections.emptyList();
+    }
+
+    /**
+     * Configures the flow builder to have the single given instruction.
+     *
+     * @param flowBuilder The flow builder.
+     * @param instruction The instruction.
+     * @return The flow builder.
+     */
+    public static FlowBuilder setFlowBuilderInstruction(FlowBuilder flowBuilder, Instruction instruction) {
+        flowBuilder.setInstructions(
+                new InstructionsBuilder()
+                        .setInstruction(Collections.singletonList(instruction))
+                        .build());
+        return flowBuilder;
+    }
+
     /**
      * Get a list of Instructions containing Nicira extensions that can have
      * additional OF/OXM instructions added to the returned Instruction list