This is no longer used, let’s just remove it.
Change-Id: Idc36a582a39279caace8981e235a3ebb426a6af4
Signed-off-by: Stephen Kitt <skitt@redhat.com>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-Copyright (C) 2015 Red Hat, Inc. and others. All rights reserved.
-
-This program and the accompanying materials are made available under the
-terms of the Eclipse Public License v1.0 which accompanies this distribution,
-and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>mdsal-it-parent</artifactId>
- <version>1.6.0-SNAPSHOT</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>it</artifactId>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>pom</packaging>
- <description>The OVSDB Plugin integration project is a project for OpenDaylight that will implement the Open vSwitch Database RFC 7047 management protocol allowing the Southbound configuration of vSwitches and a network virtualization implementation.</description>
- <licenses>
- <license>
- <name>Eclipse Public License v1.0</name>
- <url>http://www.eclipse.org/legal/epl-v10.html</url>
- </license>
- </licenses>
- <developers>
- <developer>
- <name>Sam Hague</name>
- <email>shague@gmail.com</email>
- <url>https://github.com/shague</url>
- </developer>
- </developers>
- <scm>
- <connection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</connection>
- <developerConnection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</developerConnection>
- <tag>HEAD</tag>
- <url>https://wiki.opendaylight.org/view/OVSDB_Integration:Main</url>
- </scm>
-
- <properties>
- <skip.surefire.tests>false</skip.surefire.tests>
- </properties>
- <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>
- <skip.surefire.tests>true</skip.surefire.tests>
- <skip.karaf.featureTest>true</skip.karaf.featureTest>
- <maven.javadoc.skip>true</maven.javadoc.skip>
- <maven.source.skip>true</maven.source.skip>
- <checkstyle.skip>true</checkstyle.skip>
- <findbugs.skip>true</findbugs.skip>
- <pmd.skip>true</pmd.skip>
- <cpd.skip>true</cpd.skip>
- <maven.site.skip>true</maven.site.skip>
- <invoker.skip>true</invoker.skip>
- <enforcer.skip>true</enforcer.skip>
- </properties>
- </profile>
- </profiles>
-
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.codehaus.sonar-plugins.java</groupId>
- <artifactId>sonar-jacoco-listeners</artifactId>
- <version>${sonar-jacoco-listeners.version}</version>
- <scope>test</scope>
- </dependency>
- </dependencies>
- </dependencyManagement>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.jacoco</groupId>
- <artifactId>jacoco-maven-plugin</artifactId>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-failsafe-plugin</artifactId>
- <configuration>
- <properties>
- <property>
- <name>listener</name>
- <value>org.sonar.java.jacoco.JUnitListener</value>
- </property>
- </properties>
- </configuration>
- </plugin>
- <plugin>
- <artifactId>maven-surefire-plugin</artifactId>
- <configuration>
- <skipTests>${skip.surefire.tests}</skipTests>
- </configuration>
- </plugin>
- <plugin>
- <artifactId>maven-antrun-plugin</artifactId>
- <executions>
- <execution>
- <id>prep-jacoco-agent</id>
- <phase>pre-integration-test</phase>
- <goals>
- <goal>run</goal>
- </goals>
- <configuration>
- <target>
- <copy file="${settings.localRepository}/org/jacoco/org.jacoco.agent/${jacoco.version}/org.jacoco.agent-${jacoco.version}-runtime.jar"
- tofile="target/exam/jars/org.jacoco.agent.jar" />
- </target>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-Copyright (C) 2015 Red Hat, Inc. and others. All rights reserved.
-
-This program and the accompanying materials are made available under the
-terms of the Eclipse Public License v1.0 which accompanies this distribution,
-and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>odlparent-lite</artifactId>
- <version>2.0.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>parents</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <packaging>pom</packaging>
- <description>The OVSDB Plugin integration project is a project for OpenDaylight that will implement the Open vSwitch Database RFC 7047 management protocol allowing the Southbound configuration of vSwitches and a network virtualization implementation.</description>
- <licenses>
- <license>
- <name>Eclipse Public License v1.0</name>
- <url>http://www.eclipse.org/legal/epl-v10.html</url>
- </license>
- </licenses>
- <developers>
- <developer>
- <name>Sam Hague</name>
- <email>shague@gmail.com</email>
- <url>https://github.com/shague</url>
- </developer>
- </developers>
- <scm>
- <connection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</connection>
- <developerConnection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</developerConnection>
- <tag>HEAD</tag>
- <url>https://wiki.opendaylight.org/view/OVSDB_Integration:Main</url>
- </scm>
-
- <modules>
- <module>it</module>
- </modules>
-
- <!-- DO NOT install or deploy the repo root pom as it's only needed to initiate a build -->
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-deploy-plugin</artifactId>
- <configuration>
- <skip>true</skip>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-install-plugin</artifactId>
- <configuration>
- <skip>true</skip>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright © 2017 Red Hat, Inc. and others.
-
- 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
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>feature-repo-parent</artifactId>
- <version>2.0.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>features-netvirt</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>feature</packaging>
-
- <dependencies>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-ovsdb-openstack</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-ovsdb-openstack-it</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- </dependencies>
-</project>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>single-feature-parent</artifactId>
- <version>2.0.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>odl-ovsdb-openstack-it</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>feature</packaging>
-
- <name>OpenDaylight :: OVSDB :: OpenStack Network Virtualization IT</name>
-
- <dependencies>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-ovsdb-openstack</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>utils.netvirt-it-utils</artifactId>
- <version>${project.version}</version>
- <exclusions>
- <exclusion>
- <groupId>org.apache.karaf.features</groupId>
- <artifactId>org.apache.karaf.features.core</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- </dependencies>
-</project>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright © 2017 Red Hat, Inc. and others.
-
- 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
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>single-feature-parent</artifactId>
- <version>2.0.0-SNAPSHOT</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>odl-ovsdb-openstack</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>feature</packaging>
-
- <name>OpenDaylight :: OVSDB :: OpenStack Network Virtualization</name>
-
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>odl-mdsal-broker</artifactId>
- <version>1.6.0-SNAPSHOT</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.openflowplugin</groupId>
- <artifactId>odl-openflowplugin-nsf-model</artifactId>
- <version>0.5.0-SNAPSHOT</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.neutron</groupId>
- <artifactId>odl-neutron-service</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.ovsdb</groupId>
- <artifactId>odl-ovsdb-southbound-impl-ui</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.openflowplugin</groupId>
- <artifactId>odl-openflowplugin-southbound</artifactId>
- <version>0.5.0-SNAPSHOT</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.openflowplugin</groupId>
- <artifactId>odl-openflowplugin-flow-services</artifactId>
- <version>0.5.0-SNAPSHOT</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.openflowplugin</groupId>
- <artifactId>odl-openflowplugin-nxm-extensions</artifactId>
- <version>0.5.0-SNAPSHOT</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>openstack.net-virt-providers</artifactId>
- <version>${project.version}</version>
- </dependency>
- </dependencies>
-</project>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright © 2017 Red Hat, Inc. and others.
-
- 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
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>odlparent-lite</artifactId>
- <version>2.0.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>features-netvirt-aggregator</artifactId>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>pom</packaging>
-
- <modules>
- <module>features-netvirt</module>
- <module>features4-netvirt</module>
- <module>odl-ovsdb-openstack</module>
- <module>odl-ovsdb-openstack-it</module>
- </modules>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-Copyright (C) 2015 Red Hat, Inc. and others. All rights reserved.
-
-This program and the accompanying materials are made available under the
-terms of the Eclipse Public License v1.0 which accompanies this distribution,
-and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>karaf4-parent</artifactId>
- <version>2.0.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>karaf</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <properties>
- <!-- uncomment the next line if you want karaf to automatically load the feature -->
- <!-- <karaf.localFeature>odl-ovsdb-openstack</karaf.localFeature> -->
- </properties>
- <description>The OVSDB Plugin integration project is a project for OpenDaylight that will implement the Open vSwitch Database RFC 7047 management protocol allowing the Southbound configuration of vSwitches and a network virtualization implementation.</description>
- <licenses>
- <license>
- <name>Eclipse Public License v1.0</name>
- <url>http://www.eclipse.org/legal/epl-v10.html</url>
- </license>
- </licenses>
- <developers>
- <developer>
- <name>Sam Hague</name>
- <email>shague@gmail.com</email>
- <url>https://github.com/shague</url>
- </developer>
- </developers>
- <scm>
- <connection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</connection>
- <developerConnection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</developerConnection>
- <tag>HEAD</tag>
- <url>https://wiki.opendaylight.org/view/OVSDB_Integration:Main</url>
- </scm>
- <dependencies>
- <dependency>
- <!-- scope is compile so all features (there is only one) are installed
- into startup.properties and the feature repo itself is not installed -->
- <groupId>org.apache.karaf.features</groupId>
- <artifactId>framework</artifactId>
- <version>${karaf.version}</version>
- <type>kar</type>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>features-netvirt</artifactId>
- <version>${project.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- <scope>runtime</scope>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <!-- DO NOT deploy the karaf artifact -->
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-deploy-plugin</artifactId>
- <configuration>
- <skip>true</skip>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- vi: set et smarttab sw=4 tabstop=4: --><!--
-Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
-
-This program and the accompanying materials are made available under the
-terms of the Eclipse Public License v1.0 which accompanies this distribution,
-and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
-
- <parent>
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>it</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <relativePath>../commons/it</relativePath>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <artifactId>openstack.net-virt-it</artifactId>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <packaging>jar</packaging>
- <description>The OVSDB Plugin integration project is a project for OpenDaylight that will implement the Open vSwitch Database RFC 7047 management protocol allowing the Southbound configuration of vSwitches and a network virtualization implementation.</description>
- <licenses>
- <license>
- <name>Eclipse Public License v1.0</name>
- <url>http://www.eclipse.org/legal/epl-v10.html</url>
- </license>
- </licenses>
- <developers>
- <developer>
- <name>Sam Hague</name>
- <email>shague@gmail.com</email>
- <url>https://github.com/shague</url>
- </developer>
- </developers>
- <scm>
- <connection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</connection>
- <developerConnection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</developerConnection>
- <tag>HEAD</tag>
- <url>https://wiki.opendaylight.org/view/OVSDB_Integration:Main</url>
- </scm>
-
- <properties>
- <controller.mdsal.version>1.6.0-SNAPSHOT</controller.mdsal.version>
- <karaf.distro.groupId>org.opendaylight.netvirt</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>
- <ovsdb.version>1.5.0-SNAPSHOT</ovsdb.version>
- </properties>
-
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-binding-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-common-api</artifactId>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>features-netvirt</artifactId>
- <version>${project.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-util</artifactId>
- </dependency>
- <dependency>
- <groupId>org.codehaus.sonar-plugins.java</groupId>
- <artifactId>sonar-jacoco-listeners</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>utils.mdsal-openflow</artifactId>
- <version>${project.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.ovsdb</groupId>
- <artifactId>utils.mdsal-utils</artifactId>
- <version>${ovsdb.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>utils.netvirt-it-utils</artifactId>
- <version>${project.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.ovsdb</groupId>
- <artifactId>utils.ovsdb-it-utils</artifactId>
- <version>${ovsdb.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>utils.neutron-utils</artifactId>
- <version>${project.version}</version>
- <scope>test</scope>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.jacoco</groupId>
- <artifactId>jacoco-maven-plugin</artifactId>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <!--<propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>-->
- <includeTestSourceDirectory>true</includeTestSourceDirectory>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-failsafe-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-/*
- * Copyright (c) 2015 - 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.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.vmOption;
-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.keepRuntimeFolder;
-import static org.ops4j.pax.exam.karaf.options.LogLevelOption.LogLevel.ERROR;
-import static org.ops4j.pax.exam.karaf.options.LogLevelOption.LogLevel.INFO;
-import static org.ops4j.pax.exam.karaf.options.LogLevelOption.LogLevel.TRACE;
-import static org.ops4j.pax.exam.karaf.options.LogLevelOption.LogLevel.WARN;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.UUID;
-import java.util.concurrent.atomic.AtomicBoolean;
-import javax.inject.Inject;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-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.netvirt.openstack.netvirt.NetworkHandler;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.openstack.netvirt.providers.NetvirtProvidersProvider;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.PipelineOrchestrator;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityGroup;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityRule;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSubnet;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronPortCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSecurityGroupCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSecurityRuleCRUD;
-import org.opendaylight.netvirt.utils.netvirt.it.utils.NetvirtItUtils;
-import org.opendaylight.netvirt.utils.netvirt.it.utils.NeutronNetItUtil;
-import org.opendaylight.netvirt.utils.netvirt.it.utils.PingableNeutronNetItUtil;
-import org.opendaylight.netvirt.utils.neutron.utils.NeutronUtils;
-import org.opendaylight.ovsdb.lib.notation.Version;
-import org.opendaylight.ovsdb.utils.mdsal.utils.MdsalUtils;
-import org.opendaylight.ovsdb.utils.mdsal.utils.NotifyingDataChangeListener;
-import org.opendaylight.ovsdb.utils.ovsdb.it.utils.DockerOvs;
-import org.opendaylight.ovsdb.utils.ovsdb.it.utils.ItConstants;
-import org.opendaylight.ovsdb.utils.ovsdb.it.utils.NodeInfo;
-import org.opendaylight.ovsdb.utils.ovsdb.it.utils.OvsdbItUtils;
-import org.opendaylight.ovsdb.utils.servicehelper.ServiceHelper;
-import org.opendaylight.ovsdb.utils.southbound.utils.SouthboundUtils;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbTerminationPointAugmentation;
-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.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.TopologyId;
-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.node.TerminationPoint;
-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.options.MavenUrlReference;
-import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
-import org.ops4j.pax.exam.spi.reactors.PerClass;
-import org.ops4j.pax.exam.util.Filter;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Integration tests for netvirt
- *
- * @author Sam Hague (shague@redhat.com)
- */
-@RunWith(PaxExam.class)
-@ExamReactorStrategy(PerClass.class)
-public class NetvirtIT extends AbstractMdsalTestBase {
- private static final Logger LOG = LoggerFactory.getLogger(NetvirtIT.class);
- private static OvsdbItUtils itUtils;
- private static NetvirtItUtils nvItUtils;
- private static String addressStr;
- private static String portStr;
- private static String connectionType;
- private static String controllerStr;
- private static String userSpaceEnabled = "";
- private static AtomicBoolean setup = new AtomicBoolean(false);
- private static MdsalUtils mdsalUtils = null;
- private static Southbound southbound = null;
- private static PipelineOrchestrator pipelineOrchestrator = null;
- private static SouthboundUtils southboundUtils;
- private static NeutronUtils neutronUtils = new NeutronUtils();
- private static final String NETVIRT_TOPOLOGY_ID = "netvirt:1";
- @Inject @Filter(timeout=60000)
- private static DataBroker dataBroker = null;
- @Override
- public MavenUrlReference getFeatureRepo() {
- return maven()
- .groupId("org.opendaylight.netvirt")
- .artifactId("features-netvirt")
- .classifier("features")
- .type("xml")
- .versionAsInProject();
- }
-
- @Override
- public String getFeatureName() {
- return "odl-ovsdb-openstack-it";
- }
-
- @Configuration
- @Override
- public Option[] config() {
- Option[] ovsProps = super.config();
- Option[] propertiesOptions = DockerOvs.getSysPropOptions();
- Option[] otherOptions = getOtherOptions();
- Option[] options = new Option[ovsProps.length + propertiesOptions.length + otherOptions.length];
- System.arraycopy(ovsProps, 0, options, 0, ovsProps.length);
- System.arraycopy(propertiesOptions, 0, options, ovsProps.length, propertiesOptions.length);
- System.arraycopy(otherOptions, 0, options, ovsProps.length + propertiesOptions.length,
- otherOptions.length);
- return options;
- }
-
- private Option[] getOtherOptions() {
- return new Option[] {
- wrappedBundle(
- mavenBundle("org.opendaylight.netvirt", "utils.mdsal-openflow")
- .version(asInProject())
- .type("jar")),
- wrappedBundle(
- mavenBundle("org.opendaylight.netvirt", "utils.config")
- .version(asInProject())
- .type("jar")),
- configureConsole().startLocalConsole(),
- vmOption("-javaagent:../jars/org.jacoco.agent.jar=destfile=../../jacoco-it.exec"),
- keepRuntimeFolder()
- };
- }
-
- @Override
- public Option getLoggingOption() {
- return composite(
- editConfigurationFilePut(ORG_OPS4J_PAX_LOGGING_CFG,
- logConfiguration(NetvirtIT.class),
- INFO.name()),
- editConfigurationFilePut(NetvirtITConstants.ORG_OPS4J_PAX_LOGGING_CFG,
- "log4j.logger.org.opendaylight.netvirt",
- TRACE.name()),
- editConfigurationFilePut(ORG_OPS4J_PAX_LOGGING_CFG,
- "log4j.logger.org.opendaylight.ovsdb.utils.southbound.utils.SouthboundUtils",
- TRACE.name()),
- editConfigurationFilePut(ORG_OPS4J_PAX_LOGGING_CFG,
- "log4j.logger.org.opendaylight.openflowjava.protocol.impl.util.ListDeserializer",
- ERROR.name()),
- editConfigurationFilePut(ORG_OPS4J_PAX_LOGGING_CFG,
- "log4j.logger.org.opendaylight.controller.configpusherfeature.internal.FeatureConfigPusher",
- ERROR.name()),
- editConfigurationFilePut(ORG_OPS4J_PAX_LOGGING_CFG,
- "log4j.logger.org.apache.aries.blueprint.container.ServiceRecipe",
- WARN.name()),
- editConfigurationFilePut(ORG_OPS4J_PAX_LOGGING_CFG,
- "log4j.logger.org.opendaylight.yangtools.yang.parser.repo.YangTextSchemaContextResolver",
- WARN.name()),
- super.getLoggingOption());
- }
-
- 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";
- }
-
- 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, "0.0.0.0");
- userSpaceEnabled = props.getProperty(NetvirtITConstants.USERSPACE_ENABLED, "no");
- LOG.info("setUp: Using the following properties: mode= {}, ip:port= {}:{}, controller ip: {}, " +
- "userspace.enabled: {}",
- connectionType, addressStr, portStr, controllerStr, userSpaceEnabled);
- }
-
- @Before
- @Override
- public void setup() throws InterruptedException {
- if (setup.get()) {
- LOG.info("Skipping setUp, already initialized");
- return;
- }
-
- try {
- super.setup();
- } catch (Exception e) {
- LOG.warn("Failed to setup test", e);
- fail("Failed to setup test: " + e);
- }
-
- getProperties();
-
- assertNotNull("dataBroker should not be null", dataBroker);
- itUtils = new OvsdbItUtils(dataBroker);
- nvItUtils = new NetvirtItUtils(dataBroker);
- 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);
- southboundUtils = new SouthboundUtils(mdsalUtils);
- pipelineOrchestrator =
- (PipelineOrchestrator) ServiceHelper.getGlobalInstance(PipelineOrchestrator.class, this);
- assertNotNull("pipelineOrchestrator should not be null", pipelineOrchestrator);
- setup.set(true);
- }
-
- 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) {
- LOG.warn("Interrupted while waiting for {}", NETVIRT_TOPOLOGY_ID, e);
- }
- }
- }
- return found;
- }
-
- private void readwait() {
- boolean ovsdb_wait = true;
- if (ovsdb_wait) {
- LOG.warn("Waiting, kill with ps -ef | grep java, kill xxx... ");
- try {
- System.in.read();
- } catch (IOException e) {
- LOG.error("readwait was interrupted", e);
- }
- }
- }
-
- /**
- * Test passive connection mode. The southbound starts in a listening mode waiting for connections on port
- * 6640. This test will wait for incoming connections for {@link NetvirtITConstants#CONNECTION_INIT_TIMEOUT} ms.
- *
- * @throws InterruptedException
- */
- @Ignore
- @Test
- public void testPassiveNode() throws InterruptedException {
- if (connectionType.equalsIgnoreCase(NetvirtITConstants.CONNECTION_TYPE_PASSIVE)) {
- //Wait for CONNECTION_INIT_TIMEOUT for the Passive connection to be initiated by the ovsdb-server.
- Thread.sleep(NetvirtITConstants.CONNECTION_INIT_TIMEOUT);
- }
- }
-
- private Node connectOvsdbNode(final ConnectionInfo connectionInfo) throws InterruptedException {
- LOG.info("connectOvsdbNode enter");
- Assert.assertTrue(southboundUtils.addOvsdbNode(connectionInfo));
- Node node = southboundUtils.getOvsdbNode(connectionInfo);
- Assert.assertNotNull("Should find OVSDB node after connect", node);
- LOG.info("Connected to {}", SouthboundUtils.connectionInfoToString(connectionInfo));
- return node;
- }
-
- private boolean disconnectOvsdbNode(final ConnectionInfo connectionInfo) throws InterruptedException {
- LOG.info("disconnectOvsdbNode enter");
- Assert.assertTrue(southboundUtils.deleteOvsdbNode(connectionInfo));
- Node node = southboundUtils.getOvsdbNode(connectionInfo);
- Assert.assertNull("Should not find OVSDB node after disconnect", node);
- LOG.info("Disconnected from {}", SouthboundUtils.connectionInfoToString(connectionInfo));
- return true;
- }
-
- // This is an extra test for local testing and testNetVirt covers this is more detail
- @Ignore
- @Test
- public void testAddDeleteOvsdbNode() throws InterruptedException {
- LOG.info("testAddDeleteOvsdbNode enter");
- ConnectionInfo connectionInfo = SouthboundUtils.getConnectionInfo(addressStr, portStr);
- Node ovsdbNode = connectOvsdbNode(connectionInfo);
- assertNotNull("connection failed", ovsdbNode);
- LOG.info("testNetVirt: should be connected: {}", ovsdbNode.getNodeId());
-
- assertTrue("Controller " + SouthboundUtils.connectionInfoToString(connectionInfo)
- + " is not connected", itUtils.isControllerConnected(connectionInfo));
-
- Assert.assertTrue(southboundUtils.deleteBridge(connectionInfo, NetvirtITConstants.INTEGRATION_BRIDGE_NAME));
- Thread.sleep(1000);
- Assert.assertTrue(disconnectOvsdbNode(connectionInfo));
- LOG.info("testAddDeleteOvsdbNode exit");
- }
-
- // TODO add tests for when L3 is enabled and check for br-ex
-
- // This is an extra test for local testing and testNetVirt covers this is more detail
- @Ignore
- @Test
- public void testAddDeleteOvsdbNodeWithTableOffset() throws Exception {
- LOG.info("testAddDeleteOvsdbNodeWithTableOffset enter");
- NetvirtProvidersProvider.setTableOffset((short)1);
- ConnectionInfo connectionInfo = SouthboundUtils.getConnectionInfo(addressStr, portStr);
- Node ovsdbNode = connectOvsdbNode(connectionInfo);
- assertNotNull("connection failed", ovsdbNode);
- LOG.info("testNetVirt: should be connected: {}", ovsdbNode.getNodeId());
-
- assertTrue("Controller " + SouthboundUtils.connectionInfoToString(connectionInfo)
- + " is not connected", itUtils.isControllerConnected(connectionInfo));
-
- // Verify the pipeline flows were installed
- Node bridgeNode = southbound.getBridgeNode(ovsdbNode, NetvirtITConstants.INTEGRATION_BRIDGE_NAME);
- assertNotNull("bridge " + NetvirtITConstants.INTEGRATION_BRIDGE_NAME + " was not found", bridgeNode);
- long datapathId = southbound.getDataPathId(bridgeNode);
- String datapathIdString = southbound.getDatapathId(bridgeNode);
- LOG.info("testNetVirt: bridgeNode: {}, datapathId: {} - {}", bridgeNode, datapathIdString, datapathId);
- assertNotEquals("datapathId was not found", datapathId, 0);
-
- List<Service> staticPipeline = pipelineOrchestrator.getStaticPipeline();
- List<Service> staticPipelineFound = new ArrayList<>();
- for (Service service : pipelineOrchestrator.getServiceRegistry().keySet()) {
- if (staticPipeline.contains(service)) {
- staticPipelineFound.add(service);
- }
- String flowId = "DEFAULT_PIPELINE_FLOW_" + pipelineOrchestrator.getTable(service);
- nvItUtils.verifyFlowByFields(datapathId, flowId, pipelineOrchestrator.getTable(service), 5000);
- }
- assertEquals("did not find all expected flows in static pipeline",
- staticPipeline.size(), staticPipelineFound.size());
-
- String flowId = "TableOffset_" + pipelineOrchestrator.getTable(Service.CLASSIFIER);
- nvItUtils.verifyFlowByFields(datapathId, flowId, Service.CLASSIFIER.getTable(), 5000);
-
- Assert.assertTrue(southboundUtils.deleteBridge(connectionInfo, NetvirtITConstants.INTEGRATION_BRIDGE_NAME));
- Thread.sleep(1000);
- Assert.assertTrue(disconnectOvsdbNode(connectionInfo));
- LOG.info("testAddDeleteOvsdbNodeWithTableOffset exit");
- }
-
- @Ignore
- @Test
- public void testOpenVSwitchOtherConfig() throws InterruptedException {
- ConnectionInfo connectionInfo = SouthboundUtils.getConnectionInfo(addressStr, portStr);
- Node ovsdbNode = connectOvsdbNode(connectionInfo);
- OvsdbNodeAugmentation ovsdbNodeAugmentation = ovsdbNode.getAugmentation(OvsdbNodeAugmentation.class);
- Assert.assertNotNull(ovsdbNodeAugmentation);
- List<OpenvswitchOtherConfigs> otherConfigsList = ovsdbNodeAugmentation.getOpenvswitchOtherConfigs();
- if (otherConfigsList != null) {
- for (OpenvswitchOtherConfigs otherConfig : otherConfigsList) {
- if (otherConfig.getOtherConfigKey().equals("local_ip")) {
- LOG.info("local_ip: {}", otherConfig.getOtherConfigValue());
- break;
- } else {
- LOG.info("other_config {}:{}", otherConfig.getOtherConfigKey(), otherConfig.getOtherConfigValue());
- }
- }
- } else {
- LOG.info("other_config is not present");
- }
- Assert.assertTrue(disconnectOvsdbNode(connectionInfo));
- }
-
- /**
- * Test for basic southbound events to netvirt.
- * <pre>The test will:
- * - connect to an OVSDB node and verify it is added to operational
- * - then verify that br-int was created on the node and stored in operational
- * - a port is then added to the bridge to verify that it is ignored by netvirt
- * - remove the bridge
- * - remove the node and verify it is not in operational
- * </pre>
- * @throws InterruptedException
- */
- @Test
- @SuppressWarnings("checkstyle:IllegalCatch")
- public void testNetVirt() throws InterruptedException {
- LOG.info("testNetVirt: starting test");
- try(DockerOvs ovs = new DockerOvs()) {
- ConnectionInfo connectionInfo =
- SouthboundUtils.getConnectionInfo(ovs.getOvsdbAddress(0), ovs.getOvsdbPort(0));
- NodeInfo nodeInfo = itUtils.createNodeInfo(connectionInfo, null);
- nodeInfo.connect();
- LOG.info("testNetVirt: should be connected: {}", nodeInfo.ovsdbNode.getNodeId());
-
- List<Service> staticPipeline = pipelineOrchestrator.getStaticPipeline();
- List<Service> staticPipelineFound = new ArrayList<>();
- String flowId;
- for (Service service : pipelineOrchestrator.getServiceRegistry().keySet()) {
- if (staticPipeline.contains(service)) {
- staticPipelineFound.add(service);
- }
- if (pipelineOrchestrator.getTable(service) == Service.RESUBMIT_ACL_SERVICE.getTable()) {
- flowId = "ReSubmit_";
- } else {
- flowId = "DEFAULT_PIPELINE_FLOW_" + pipelineOrchestrator.getTable(service);
- }
- nvItUtils.verifyFlowByFields(nodeInfo.datapathId, flowId, pipelineOrchestrator.getTable(service), 5000);
- }
- assertEquals("did not find all expected flows in static pipeline",
- staticPipeline.size(), staticPipelineFound.size());
-
- southboundUtils.addTerminationPoint(nodeInfo.bridgeNode,
- NetvirtITConstants.PORT_NAME, "internal", null, null, 0L);
- Thread.sleep(1000);
- OvsdbTerminationPointAugmentation ovsdbTerminationPointAugmentation =
- southbound.getTerminationPointOfBridge(nodeInfo.bridgeNode, NetvirtITConstants.PORT_NAME);
- Assert.assertNotNull("Did not find " + NetvirtITConstants.PORT_NAME, ovsdbTerminationPointAugmentation);
-
- nodeInfo.disconnect();
- } catch (Exception e) {
- LOG.warn("testNetVirt: Exception thrown by OvsDocker.OvsDocker()", e);
- }
- }
-
- @Test
- @SuppressWarnings("checkstyle:IllegalCatch")
- public void testNetVirtFixedSG() throws InterruptedException {
- final Version minSGOvsVersion = Version.fromString("1.10.2");
- final String portName = "sg1";
- final String networkId = "521e29d6-67b8-4b3c-8633-027d21195111";
- final String tenantId = "521e29d6-67b8-4b3c-8633-027d21195100";
- final String subnetId = "521e29d6-67b8-4b3c-8633-027d21195112";
- final String portId = "521e29d6-67b8-4b3c-8633-027d21195113";
- final String dhcpPortId ="521e29d6-67b8-4b3c-8633-027d21195115";
-
- try(DockerOvs ovs = new DockerOvs()) {
- ConnectionInfo connectionInfo =
- SouthboundUtils.getConnectionInfo(ovs.getOvsdbAddress(0), ovs.getOvsdbPort(0));
- NodeInfo nodeInfo = itUtils.createNodeInfo(connectionInfo, null);
- nodeInfo.connect();
- LOG.info("testNetVirtFixedSG: should be connected: {}", nodeInfo.ovsdbNode.getNodeId());
-
- //TBD: This should be a utility function
- // Verify the minimum version required for this test
- OvsdbNodeAugmentation ovsdbNodeAugmentation =
- nodeInfo.ovsdbNode.getAugmentation(OvsdbNodeAugmentation.class);
- Assert.assertNotNull(ovsdbNodeAugmentation);
- assertNotNull(ovsdbNodeAugmentation.getOvsVersion());
- String ovsVersion = ovsdbNodeAugmentation.getOvsVersion();
- Version version = Version.fromString(ovsVersion);
- if (version.compareTo(minSGOvsVersion) < 0) {
- LOG.warn("{} minimum version is required", minSGOvsVersion);
- Assert.assertTrue(southboundUtils.deleteBridge(connectionInfo,
- NetvirtITConstants.INTEGRATION_BRIDGE_NAME));
- Thread.sleep(1000);
- Assert.assertTrue(disconnectOvsdbNode(connectionInfo));
- return;
- }
-
- //TBD: Use NeutronNetItUtil
- NeutronNetwork nn = neutronUtils.createNeutronNetwork(networkId, tenantId,
- NetworkHandler.NETWORK_TYPE_VXLAN, "100");
- NeutronSubnet ns = neutronUtils.createNeutronSubnet(subnetId, tenantId, networkId, "10.0.0.0/24");
- NeutronPort nport = neutronUtils.createNeutronPort(networkId, subnetId, portId,
- "compute", "10.0.0.10", "f6:00:00:0f:00:01");
- NeutronPort dhcp = neutronUtils.createNeutronPort(networkId, subnetId, dhcpPortId,
- "dhcp", "10.0.0.1", "f6:00:00:0f:00:02");
-
- Thread.sleep(1000);
- Map<String, String> externalIds = new HashMap<>();
- externalIds.put("attached-mac", "f6:00:00:0f:00:01");
- externalIds.put("iface-id", portId);
- southboundUtils.addTerminationPoint(nodeInfo.bridgeNode, portName, "internal", null, externalIds, 3L);
- southboundUtils.addTerminationPoint(nodeInfo.bridgeNode, "vm1", "internal", null, null, 0L);
- southboundUtils.addTerminationPoint(nodeInfo.bridgeNode, "vm2", "internal", null, null, 0L);
- Map<String, String> options = new HashMap<>();
- options.put("key", "flow");
- options.put("remote_ip", "192.168.120.32");
- southboundUtils.addTerminationPoint(nodeInfo.bridgeNode, "vx", "vxlan", options, null, 4L);
- Thread.sleep(1000);
-
- String flowId = "Egress_DHCP_Client" + "_Permit_";
- nvItUtils.verifyFlowByFields(nodeInfo.datapathId, flowId,
- pipelineOrchestrator.getTable(Service.EGRESS_ACL), 5000);
-
- testDefaultSG(nport, nodeInfo.datapathId, nn, tenantId, portId);
- Thread.sleep(1000);
-
- assertTrue(neutronUtils.removeNeutronPort(dhcp.getID()));
- assertTrue(neutronUtils.removeNeutronPort(nport.getID()));
- assertTrue(neutronUtils.removeNeutronSubnet(ns.getID()));
- assertTrue(neutronUtils.removeNeutronNetwork(nn.getID()));
-
- nodeInfo.disconnect();
- } catch (Exception e) {
- LOG.warn("testNetVirtFixedSG: Exception thrown by OvsDocker.OvsDocker()", e);
- }
- }
-
- private void testDefaultSG(NeutronPort nport, long datapathId, NeutronNetwork nn, String tenantId, String portId)
- throws Exception {
- INeutronSecurityGroupCRUD ineutronSecurityGroupCRUD =
- (INeutronSecurityGroupCRUD) ServiceHelper.getGlobalInstance(INeutronSecurityGroupCRUD.class, this);
- assertNotNull("Could not find ineutronSecurityGroupCRUD Service", ineutronSecurityGroupCRUD);
- INeutronSecurityRuleCRUD ineutronSecurityRuleCRUD =
- (INeutronSecurityRuleCRUD) ServiceHelper.getGlobalInstance(INeutronSecurityRuleCRUD.class, this);
- assertNotNull("Could not find ineutronSecurityRuleCRUD Service", ineutronSecurityRuleCRUD);
-
- NeutronSecurityGroup neutronSG = new NeutronSecurityGroup();
- neutronSG.setSecurityGroupName("DefaultSG");
- neutronSG.setID("d3329053-bae5-4bf4-a2d1-7330f11ba5db");
- neutronSG.setSecurityGroupTenantID(tenantId);
-
- List<NeutronSecurityRule> nsrs = new ArrayList<>();
- NeutronSecurityRule nsrIN = new NeutronSecurityRule();
- nsrIN.setSecurityRemoteGroupID(null);
- nsrIN.setSecurityRuleDirection("ingress");
- nsrIN.setSecurityRuleEthertype("IPv4");
- nsrIN.setSecurityRuleGroupID("d3329053-bae5-4bf4-a2d1-7330f11ba5db");
- nsrIN.setSecurityRuleProtocol("tcp");
- nsrIN.setSecurityRuleRemoteIpPrefix("10.0.0.0/24");
- nsrIN.setID("823faaf7-175d-4f01-a271-0bf56fb1e7e6");
- nsrIN.setSecurityRuleTenantID(tenantId);
-
- NeutronSecurityRule nsrEG = new NeutronSecurityRule();
- nsrEG.setSecurityRemoteGroupID(null);
- nsrEG.setSecurityRuleDirection("egress");
- nsrEG.setSecurityRuleEthertype("IPv4");
- nsrEG.setSecurityRuleGroupID("d3329053-bae5-4bf4-a2d1-7330f11ba5db");
- nsrEG.setSecurityRuleProtocol("tcp");
- nsrEG.setSecurityRuleRemoteIpPrefix("10.0.0.0/24");
- nsrEG.setID("823faaf7-175d-4f01-a271-0bf56fb1e7e1");
- nsrEG.setSecurityRuleTenantID(tenantId);
-
- nsrs.add(nsrIN);
- nsrs.add(nsrEG);
-
- ineutronSecurityRuleCRUD.addNeutronSecurityRule(nsrIN);
- ineutronSecurityRuleCRUD.addNeutronSecurityRule(nsrEG);
- ineutronSecurityGroupCRUD.addNeutronSecurityGroup(neutronSG);
-
- List<NeutronSecurityGroup> sgs = new ArrayList<>();
- sgs.add(neutronSG);
- nport.setSecurityGroups(sgs);
-
- INeutronPortCRUD iNeutronPortCRUD =
- (INeutronPortCRUD) ServiceHelper.getGlobalInstance(INeutronPortCRUD.class, this);
- iNeutronPortCRUD.updatePort(portId, nport);
-
- LOG.info("Neutron ports have been added");
- Thread.sleep(10000);
- String flowId = "Egress_TCP_" + nn.getProviderSegmentationID() + "_"
- + nport.getMacAddress() + "_10.0.0.0/24_Permit";
- nvItUtils.verifyFlowByFields(datapathId, flowId, pipelineOrchestrator.getTable(Service.EGRESS_ACL), 5000);
-
- flowId = "Egress_TCP_Ipv4_" + nn.getProviderSegmentationID() + "_" + nport.getMacAddress() + "_DROP";
- nvItUtils.verifyFlowByFields(datapathId, flowId, pipelineOrchestrator.getTable(Service.EGRESS_ACL), 5000);
-
- flowId = "Ingress_TCP_" + nn.getProviderSegmentationID() + "_"
- + nport.getMacAddress() + "_10.0.0.0/24_Permit";
- nvItUtils.verifyFlowByFields(datapathId, flowId, pipelineOrchestrator.getTable(Service.INGRESS_ACL), 5000);
-
- flowId = "Ingress_TCP_Ipv4_" + nn.getProviderSegmentationID() + "_" + nport.getMacAddress() + "_DROP";
- nvItUtils.verifyFlowByFields(datapathId, flowId, pipelineOrchestrator.getTable(Service.INGRESS_ACL), 5000);
-
- ineutronSecurityGroupCRUD.removeNeutronSecurityGroup(neutronSG.getID());
- ineutronSecurityRuleCRUD.removeNeutronSecurityRule(nsrEG.getID());
- ineutronSecurityRuleCRUD.removeNeutronSecurityRule(nsrIN.getID());
- }
-
- /**
- * Test a basic neutron use case. This test constructs a Neutron network, subnet, dhcp port, and two "vm" ports
- * and validates that the correct flows are installed on OVS. Then it pings from one VM port to the other.
- * @throws InterruptedException if we're interrupted while waiting for some mdsal operation to complete
- */
- @Test
- @SuppressWarnings("checkstyle:IllegalCatch")
- public void testNeutronNet() throws InterruptedException {
- LOG.warn("testNeutronNet: starting test");
- try(DockerOvs ovs = new DockerOvs()) {
- logState(null, ovs, 0, "idle");
- ConnectionInfo connectionInfo = SouthboundUtils
- .getConnectionInfo(ovs.getOvsdbAddress(0), ovs.getOvsdbPort(0));
- NodeInfo nodeInfo = itUtils.createNodeInfo(connectionInfo, null);
- nodeInfo.connect();
- LOG.info("testNeutronNet: should be connected: {}", nodeInfo.ovsdbNode.getNodeId());
-
- Boolean isUserSpace = userSpaceEnabled.equals("yes");
- LOG.info("isUserSpace: {}, usingExternalDocker: {}", isUserSpace, ovs.usingExternalDocker());
- // Create the objects
- PingableNeutronNetItUtil net =
- new PingableNeutronNetItUtil(ovs, southboundUtils, UUID.randomUUID().toString(), isUserSpace);
- net.create();
- net.createPort(nodeInfo.bridgeNode, "dhcp", "network:dhcp");
- net.createPort(nodeInfo.bridgeNode, "vm1");
- net.createPort(nodeInfo.bridgeNode, "vm2");
-
- InstanceIdentifier<TerminationPoint> tpIid =
- southboundUtils.createTerminationPointInstanceIdentifier(nodeInfo.bridgeNode, "vm2");
- final NotifyingDataChangeListener portOperationalListener =
- new NotifyingDataChangeListener(LogicalDatastoreType.OPERATIONAL,
- NotifyingDataChangeListener.BIT_CREATE, tpIid, null);
- portOperationalListener.registerDataChangeListener(dataBroker);
- portOperationalListener.waitForCreation(10000);
- Thread.sleep(30000);
- logState(net, ovs, 0, "after ports");
-
- // Check flows created for all ports
- for (NeutronNetItUtil.PortInfo portInfo : net.portInfoByName.values()) {
- nvItUtils.verifyFlowByFields(nodeInfo.datapathId, "DropFilter_" + portInfo.ofPort,
- pipelineOrchestrator.getTable(Service.CLASSIFIER), 5000);
- nvItUtils.verifyFlowByFields(nodeInfo.datapathId, "LocalMac_" + net.segId + "_" + portInfo.ofPort
- + "_" + portInfo.mac, pipelineOrchestrator.getTable(Service.CLASSIFIER), 5000);
- nvItUtils.verifyFlowByFields(nodeInfo.datapathId, "ArpResponder_" + net.segId + "_" + portInfo.ip,
- pipelineOrchestrator.getTable(Service.ARP_RESPONDER), 5000);
- nvItUtils.verifyFlowByFields(nodeInfo.datapathId, "UcastOut_" + net.segId + "_" + portInfo.ofPort
- + "_" + portInfo.mac, pipelineOrchestrator.getTable(Service.L2_FORWARDING), 5000);
- }
-
- for (NeutronNetItUtil.PortInfo portInfo : net.portInfoByName.values()) {
- // Check flows created for vm ports only
- if (portInfo.name.equals("dhcp")) {
- continue;
- }
- nvItUtils.verifyFlowByFields(nodeInfo.datapathId,
- "Ingress_ARP_" + net.segId + "_" + portInfo.ofPort + "_",
- pipelineOrchestrator.getTable(Service.INGRESS_ACL), 5000);
- nvItUtils.verifyFlowByFields(nodeInfo.datapathId,
- "Egress_ARP_" + net.segId + "_" + portInfo.ofPort + "_",
- pipelineOrchestrator.getTable(Service.EGRESS_ACL), 5000);
- }
-
- // Check ingress/egress acl flows for DHCP
- nvItUtils.verifyFlowByFields(nodeInfo.datapathId, "Egress_DHCP_Client_Permit_",
- pipelineOrchestrator.getTable(Service.EGRESS_ACL), 5000);
- nvItUtils.verifyFlowByFields(nodeInfo.datapathId, "Egress_DHCPv6_Client_Permit_",
- pipelineOrchestrator.getTable(Service.EGRESS_ACL), 5000);
- nvItUtils.verifyFlowByFields(nodeInfo.datapathId,
- "Ingress_DHCPv6_Server_" + net.segId + "_" + net.macFor(1) + "_Permit",
- pipelineOrchestrator.getTable(Service.INGRESS_ACL), 5000);
- nvItUtils.verifyFlowByFields(nodeInfo.datapathId,
- "Ingress_DHCP_Server_" + net.segId + "_" + net.macFor(1) + "_Permit",
- pipelineOrchestrator.getTable(Service.INGRESS_ACL), 5000);
-
- // Check l2 broadcast flows
- nvItUtils.verifyFlowByFields(nodeInfo.datapathId, "TunnelFloodOut_" + net.segId,
- pipelineOrchestrator.getTable(Service.L2_FORWARDING), 5000);
- nvItUtils.verifyFlowByFields(nodeInfo.datapathId, "BcastOut_" + net.segId,
- pipelineOrchestrator.getTable(Service.L2_FORWARDING), 5000);
- nvItUtils.verifyFlowByFields(nodeInfo.datapathId, "TunnelMiss_" + net.segId,
- pipelineOrchestrator.getTable(Service.L2_FORWARDING), 5000);
-
- logState(net, ovs, 0, "after ports 2");
- net.preparePortForPing("vm1");
- net.preparePortForPing("vm2");
-
- LOG.info("wait for stuff to catch up");
- Thread.sleep(30000);
- logState(net, ovs, 0, "after preparePortForPing");
- net.ping("vm1", "vm2");
- LOG.info("after ping");
- logState(net, ovs, 0, "after ping");
- net.destroy();
- nodeInfo.disconnect();
- } catch (Exception e) {
- LOG.warn("testNeutronNet: Exception thrown by OvsDocker.OvsDocker()", e);
- Assert.fail("Exception thrown during testNeutronNet " + e.toString());
- }
- }
-
- @Test
- @Ignore //For now....fails every once in a while on connect. TODO: fix it
- @SuppressWarnings("checkstyle:IllegalCatch")
- public void twoNodes() throws InterruptedException {
-
- System.getProperties().setProperty(ItConstants.DOCKER_COMPOSE_FILE_NAME, "two_dockers-ovs-2.5.1.yml");
- try(DockerOvs ovs = new DockerOvs()) {
- ConnectionInfo connectionInfo = SouthboundUtils.getConnectionInfo(ovs.getOvsdbAddress(0), ovs.getOvsdbPort(0));
- NodeInfo nodeInfo0 = itUtils.createNodeInfo(connectionInfo, null);
- nodeInfo0.connect();
- LOG.warn("testTwoNodes: should be connected: {}", nodeInfo0.ovsdbNode.getNodeId());
- connectionInfo = SouthboundUtils.getConnectionInfo(ovs.getOvsdbAddress(1), ovs.getOvsdbPort(1));
- NodeInfo nodeInfo1 = itUtils.createNodeInfo(connectionInfo, null);
- nodeInfo1.connect();
- LOG.warn("testTwoNodes: should be connected: {}", nodeInfo1.ovsdbNode.getNodeId());
-
- nodeInfo0.disconnect();
- nodeInfo1.disconnect();
- } catch (Exception e) {
- LOG.warn("testTwoNodes: Exception thrown by OvsDocker.OvsDocker()", e);
- }
- }
-
- public void logState(PingableNeutronNetItUtil net, DockerOvs dockerOvs, int dockerInstance, String logText)
- throws IOException, InterruptedException {
- if (dockerOvs.usingExternalDocker()) {
- return;
- }
- dockerOvs.tryInContainer(logText, 5000, dockerInstance, "ip", "link");
- dockerOvs.tryInContainer(logText, 5000, dockerInstance, "ip", "addr");
- dockerOvs.tryInContainer(logText, 5000, dockerInstance, "ip", "route");
- dockerOvs.tryInContainer(logText, 5000, dockerInstance, "ip", "netns", "list");
-
- if (net != null) {
- for (String key : net.portInfoByName.keySet()) {
- String ns = "ns-" + key;
- dockerOvs.tryInContainer(logText, 5000, dockerInstance, "ip", "netns", "exec", ns, "ip", "link");
- dockerOvs.tryInContainer(logText, 5000, dockerInstance, "ip", "netns", "exec", ns, "ip", "addr");
- dockerOvs.tryInContainer(logText, 5000, dockerInstance, "ip", "netns", "exec", ns, "ip", "route");
- }
- }
- dockerOvs.tryInContainer(logText, 5000, dockerInstance, "ovs-vsctl", "show");
- dockerOvs.tryInContainer(logText, 5000, dockerInstance, "ovs-ofctl", "-OOpenFlow13", "show", "br-int");
- dockerOvs.tryInContainer(logText, 5000, dockerInstance, "ovs-ofctl", "-OOpenFlow13", "dump-flows", "br-int");
- //dockerOvs.tryInContainer(logText, 5000, dockerInstance, "ovs-appctl", "fdb/show", "br-int");
- //ovs-appctl -t /var/run/openvswitch/ovs-vswitchd.12.ctl fdb/show br-int
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt.it;
-
-/**
- * Constants for SouthboundIT
- */
-public final class NetvirtITConstants {
- private NetvirtITConstants() {
- throw new AssertionError("This class should not be instantiated.");
- }
-
- public static final String ORG_OPS4J_PAX_LOGGING_CFG = "etc/org.ops4j.pax.logging.cfg";
- 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 USERSPACE_ENABLED = "ovsdb.userspace.enabled";
- public static final String SERVER_EXTRAS = "ovsdbserver.extras";
- public static final String CONNECTION_TYPE = "ovsdbserver.connection";
- public static final String CONNECTION_TYPE_ACTIVE = "active";
- public static final String CONNECTION_TYPE_PASSIVE = "passive";
- public static final int CONNECTION_INIT_TIMEOUT = 10000;
- public static final String DEFAULT_SERVER_IPADDRESS = "127.0.0.1";
- public static final String DEFAULT_SERVER_PORT = "6640";
- public static final String DEFAULT_OPENFLOW_PORT = "6653";
- public static final String DEFAULT_SERVER_EXTRAS = "false";
- public static final String BRIDGE_NAME = "brtest";
- public static final String PORT_NAME = "porttest";
- public static final String INTEGRATION_BRIDGE_NAME = "br-int";
- public static final String OPENFLOW_CONNECTION_PROTOCOL = "tcp";
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
-
-This program and the accompanying materials are made available under the
-terms of the Eclipse Public License v1.0 which accompanies this distribution,
-and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <parent>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-parent</artifactId>
- <version>0.7.0-SNAPSHOT</version>
- <relativePath/>
- </parent>
- <modelVersion>4.0.0</modelVersion>
-
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>openstack.net-virt-providers</artifactId>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>bundle</packaging>
- <description>The OVSDB Plugin integration project is a project for OpenDaylight that will implement the Open vSwitch Database RFC 7047 management protocol allowing the Southbound configuration of vSwitches and a network virtualization implementation.</description>
- <licenses>
- <license>
- <name>Eclipse Public License v1.0</name>
- <url>http://www.eclipse.org/legal/epl-v10.html</url>
- </license>
- </licenses>
- <developers>
- <developer>
- <name>Sam Hague</name>
- <email>shague@gmail.com</email>
- <url>https://github.com/shague</url>
- </developer>
- </developers>
- <scm>
- <connection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</connection>
- <developerConnection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</developerConnection>
- <tag>HEAD</tag>
- <url>https://wiki.opendaylight.org/view/OVSDB_Integration:Main</url>
- </scm>
-
- <properties>
- <liblldp.version>0.13.0-SNAPSHOT</liblldp.version>
- <openflowplugin.version>0.5.0-SNAPSHOT</openflowplugin.version>
- <ovsdb.version>1.5.0-SNAPSHOT</ovsdb.version>
- <sonar.jacoco.itReportPath>../net-virt-it/target/jacoco-it.exec</sonar.jacoco.itReportPath>
- </properties>
-
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>openstack.net-virt</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>utils.mdsal-openflow</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.ovsdb</groupId>
- <artifactId>southbound-api</artifactId>
- <version>${ovsdb.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>utils.servicehelper</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.openflowplugin.model</groupId>
- <artifactId>model-flow-base</artifactId>
- <version>${openflowplugin.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.openflowplugin.model</groupId>
- <artifactId>model-flow-service</artifactId>
- <version>${openflowplugin.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.openflowplugin</groupId>
- <artifactId>openflowjava-extension-nicira</artifactId>
- <version>${openflowplugin.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.openflowplugin</groupId>
- <artifactId>openflowplugin-extension-nicira</artifactId>
- <version>${openflowplugin.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.openflowplugin</groupId>
- <artifactId>openflowplugin-api</artifactId>
- <version>${openflowplugin.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>ietf-inet-types-2013-07-15</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>ietf-yang-types-20130715</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>opendaylight-l2-types</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>ietf-topology</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>liblldp</artifactId>
- <version>${liblldp.version}</version>
- </dependency>
- <dependency>
- <groupId>io.netty</groupId>
- <artifactId>netty-buffer</artifactId>
- </dependency>
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
- </dependency>
- <dependency>
- <groupId>org.codehaus.sonar-plugins.java</groupId>
- <artifactId>sonar-jacoco-listeners</artifactId>
- <version>${sonar-jacoco-listeners.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-simple</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-core</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-core</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-module-junit4</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-api-mockito</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-api-support</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-reflect</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <extensions>true</extensions>
- <configuration>
- <instructions>
- <Embed-Dependency>utils.config,utils.mdsal-openflow;type=!pom;inline=false</Embed-Dependency>
- <Embed-Transitive>true</Embed-Transitive>
- <Export-Package>
- org.opendaylight.netvirt.openstack.netvirt.providers,
- org.opendaylight.netvirt.openstack.netvirt.providers.openflow13,
- org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.providers.config.rev160109
- </Export-Package>
- </instructions>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
- <configuration>
- <excludes>
- <exclude>**/services/*Test.java</exclude>
- </excludes>
- <properties>
- <property>
- <name>listener</name>
- <value>org.sonar.java.jacoco.JUnitListener</value>
- </property>
- </properties>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.jacoco</groupId>
- <artifactId>jacoco-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>default-instrument</id>
- <goals>
- <goal>instrument</goal>
- </goals>
- </execution>
- <execution>
- <id>default-restore-instrumented-classes</id>
- <goals>
- <goal>restore-instrumented-classes</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-/*
- * Copyright (c) 2015, 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.providers;
-
-import java.util.ArrayList;
-import java.util.Dictionary;
-import java.util.Hashtable;
-import java.util.List;
-
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
-import org.opendaylight.netvirt.openstack.netvirt.api.ArpProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.ClassifierProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.ConfigurationService;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-import org.opendaylight.netvirt.openstack.netvirt.api.EgressAclProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.GatewayMacResolver;
-import org.opendaylight.netvirt.openstack.netvirt.api.IcmpEchoProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.InboundNatProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.IngressAclProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.L2ForwardingLearnProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.L2ForwardingProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.L2RewriteProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.L3ForwardingProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.LoadBalancerProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.NetworkingProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.NetworkingProviderManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheListener;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.OutboundNatProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.ResubmitAclLearnProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.RoutingProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.VlanResponderProvider;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.AbstractServiceInstance;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.OF13Provider;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.PipelineOrchestrator;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.PipelineOrchestratorImpl;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services.ArpResponderService;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services.ClassifierService;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services.EgressAclService;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services.IcmpEchoResponderService;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services.InboundNatService;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services.IngressAclService;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services.L2ForwardingLearnService;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services.L2ForwardingService;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services.L2RewriteService;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services.L3ForwardingService;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services.LoadBalancerService;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services.OutboundNatService;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services.ResubmitAclLearnService;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services.RoutingService;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services.VlanResponderService;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services.arp.GatewayMacResolverService;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronNetworkCRUD;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.SalFlowService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketProcessingService;
-import org.osgi.framework.BundleActivator;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.osgi.framework.ServiceRegistration;
-import org.osgi.util.tracker.ServiceTracker;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ConfigActivator implements BundleActivator {
- private static final Logger LOG = LoggerFactory.getLogger(ConfigActivator.class);
- private List<ServiceRegistration<?>> registrations = new ArrayList<>();
-
- private final DataBroker dataBroker;
- private final NotificationProviderService notificationProviderService;
- private final PacketProcessingService packetProcessingService;
- private final SalFlowService salFlowService;
-
- public ConfigActivator(final DataBroker dataBroker,
- final NotificationProviderService notificationProviderService,
- final PacketProcessingService packetProcessingService,
- final SalFlowService salFlowService) {
- this.dataBroker = dataBroker;
- this.notificationProviderService = notificationProviderService;
- this.packetProcessingService = packetProcessingService;
- this.salFlowService = salFlowService;
- }
-
- @Override
- public void start(BundleContext context) throws Exception {
- LOG.info("ConfigActivator start:");
-
- NetvirtProvidersConfigImpl netvirtProvidersConfig =
- new NetvirtProvidersConfigImpl(dataBroker,
- NetvirtProvidersProvider.getTableOffset());
- registerService(context,
- new String[] {NetvirtProvidersConfigImpl.class.getName()},
- null, netvirtProvidersConfig);
-
- PipelineOrchestratorImpl pipelineOrchestrator = new PipelineOrchestratorImpl();
- registerService(context,
- new String[] {PipelineOrchestrator.class.getName(),NodeCacheListener.class.getName()},
- null, pipelineOrchestrator);
-
- Dictionary<String, Object> of13ProviderProperties = new Hashtable<>();
- of13ProviderProperties.put(Constants.SOUTHBOUND_PROTOCOL_PROPERTY, "ovsdb");
- of13ProviderProperties.put(Constants.OPENFLOW_VERSION_PROPERTY, Constants.OPENFLOW13);
- final OF13Provider of13Provider = new OF13Provider();
- registerService(context,
- new String[] {NetworkingProvider.class.getName()},
- of13ProviderProperties, of13Provider);
-
- ClassifierService classifierService = new ClassifierService();
- registerService(context, ClassifierProvider.class.getName(),
- classifierService, Service.CLASSIFIER);
-
- ArpResponderService arpResponderService = new ArpResponderService();
- registerService(context, ArpProvider.class.getName(),
- arpResponderService, Service.ARP_RESPONDER);
-
- InboundNatService inboundNatService = new InboundNatService();
- registerService(context, InboundNatProvider.class.getName(),
- inboundNatService, Service.INBOUND_NAT);
-
- ResubmitAclLearnService resubmitAclLearnService = new ResubmitAclLearnService();
- registerService(context, ResubmitAclLearnProvider.class.getName(),
- resubmitAclLearnService, Service.RESUBMIT_ACL_SERVICE);
- IngressAclService ingressAclService = new IngressAclService();
- registerService(context, IngressAclProvider.class.getName(),
- ingressAclService, Service.INGRESS_ACL);
-
- LoadBalancerService loadBalancerService = new LoadBalancerService();
- registerService(context, LoadBalancerProvider.class.getName(),
- loadBalancerService, Service.LOAD_BALANCER);
-
- RoutingService routingService = new RoutingService();
- registerService(context, RoutingProvider.class.getName(),
- routingService, Service.ROUTING);
-
- L3ForwardingService l3ForwardingService = new L3ForwardingService();
- registerService(context, L3ForwardingProvider.class.getName(),
- l3ForwardingService, Service.L3_FORWARDING);
-
- L2RewriteService l2RewriteService = new L2RewriteService();
- registerService(context, L2RewriteProvider.class.getName(),
- l2RewriteService, Service.L2_REWRITE);
-
- L2ForwardingLearnService l2ForwardingLearnService = new L2ForwardingLearnService();
- registerService(context, L2ForwardingLearnProvider.class.getName(),
- l2ForwardingLearnService, Service.L2_LEARN);
-
- L2ForwardingService l2ForwardingService = new L2ForwardingService();
- registerService(context, L2ForwardingProvider.class.getName(),
- l2ForwardingService, Service.L2_FORWARDING);
-
- EgressAclService egressAclService = new EgressAclService();
- registerService(context, EgressAclProvider.class.getName(),
- egressAclService, Service.EGRESS_ACL);
-
- OutboundNatService outboundNatService = new OutboundNatService();
- registerService(context, OutboundNatProvider.class.getName(),
- outboundNatService, Service.OUTBOUND_NAT);
-
- VlanResponderService vlanResponderService = new VlanResponderService();
- registerService(context, VlanResponderProvider.class.getName(),
- vlanResponderService, Service.OUTBOUND_NAT);
-
- final GatewayMacResolverService gatewayMacResolverService = new GatewayMacResolverService(packetProcessingService, salFlowService);
- registerService(context, GatewayMacResolver.class.getName(),
- gatewayMacResolverService, Service.GATEWAY_RESOLVER);
- notificationProviderService.registerNotificationListener(gatewayMacResolverService);
-
- IcmpEchoResponderService icmpEchoResponderService = new IcmpEchoResponderService();
- registerService(context, IcmpEchoProvider.class.getName(),
- icmpEchoResponderService, Service.ICMP_ECHO);
-
- netvirtProvidersConfig.setDependencies(context, null);
- pipelineOrchestrator.setDependencies(context, null);
- outboundNatService.setDependencies(context, null);
- egressAclService.setDependencies(context, null);
- l2ForwardingLearnService.setDependencies(context, null);
- l2ForwardingService.setDependencies(context, null);
- l2RewriteService.setDependencies(context, null);
- l3ForwardingService.setDependencies(context, null);
- routingService.setDependencies(context, null);
- loadBalancerService.setDependencies(context, null);
- ingressAclService.setDependencies(context, null);
- inboundNatService.setDependencies(context, null);
- resubmitAclLearnService.setDependencies(context, null);
- arpResponderService.setDependencies(context, null);
- classifierService.setDependencies(context, null);
- of13Provider.setDependencies(context, null);
- gatewayMacResolverService.setDependencies(context, null);
- icmpEchoResponderService.setDependencies(context, null);
- vlanResponderService.setDependencies(context, null);
-
- @SuppressWarnings("unchecked")
- ServiceTracker neutronNetworkCacheTracker = new ServiceTracker(context,
- INeutronNetworkCRUD.class, null) {
- @Override
- public Object addingService(ServiceReference reference) {
- LOG.info("addingService INeutronNetworkCRUD");
- INeutronNetworkCRUD service =
- (INeutronNetworkCRUD) context.getService(reference);
- if (service != null) {
- vlanResponderService.setDependencies(service);
- }
- return service;
- }
- };
- neutronNetworkCacheTracker.open();
-
- @SuppressWarnings("unchecked")
- ServiceTracker networkingProviderManagerTracker = new ServiceTracker(context,
- NetworkingProviderManager.class, null) {
- @Override
- public Object addingService(ServiceReference reference) {
- LOG.info("addingService NetworkingProviderManager");
- NetworkingProviderManager service =
- (NetworkingProviderManager) context.getService(reference);
- if (service != null) {
- of13Provider.setDependencies(service);
- }
- return service;
- }
- };
- networkingProviderManagerTracker.open();
-
- @SuppressWarnings("unchecked")
- ServiceTracker ConfigurationServiceTracker = new ServiceTracker(context,
- ConfigurationService.class, null) {
- @Override
- public Object addingService(ServiceReference reference) {
- LOG.info("addingService ConfigurationService");
- ConfigurationService service =
- (ConfigurationService) context.getService(reference);
- if (service != null) {
- gatewayMacResolverService.setDependencies(service);
- }
- return service;
- }
- };
- ConfigurationServiceTracker.open();
-
- @SuppressWarnings("unchecked")
- ServiceTracker NodeCacheManagerTracker = new ServiceTracker(context,
- NodeCacheManager.class, null) {
- @Override
- public Object addingService(ServiceReference reference) {
- LOG.info("addingService NodeCacheManager");
- NodeCacheManager service =
- (NodeCacheManager) context.getService(reference);
- if (service != null) {
- gatewayMacResolverService.setDependencies(service);
- }
- return service;
- }
- };
- NodeCacheManagerTracker.open();
- }
-
- @Override
- public void stop(BundleContext context) throws Exception {
- LOG.info("ConfigActivator stop");
- // ServiceTrackers and services are already released when bundle stops,
- // so we don't need to close the trackers or unregister the services
- }
-
- private ServiceRegistration<?> registerService(BundleContext bundleContext, String[] interfaces,
- Dictionary<String, Object> properties, Object impl) {
- ServiceRegistration<?> serviceRegistration = bundleContext.registerService(interfaces, impl, properties);
- if (serviceRegistration != null) {
- registrations.add(serviceRegistration);
- }
- return serviceRegistration;
- }
-
- private ServiceRegistration<?> registerService(BundleContext bundleContext, String interfaceClassName,
- Object impl, Object serviceProperty) {
- Dictionary<String, Object> properties = new Hashtable<>();
- properties.put(AbstractServiceInstance.SERVICE_PROPERTY, serviceProperty);
- properties.put(Constants.PROVIDER_NAME_PROPERTY, OF13Provider.NAME);
- return registerService(bundleContext,
- new String[] {AbstractServiceInstance.class.getName(), interfaceClassName},
- properties, impl);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.providers;
-
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-
-public interface ConfigInterface {
- void setDependencies(BundleContext bundleContext, ServiceReference serviceReference);
- void setDependencies(Object impl);
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt.providers;
-
-import java.util.Map;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ThreadFactory;
-
-import com.google.common.util.concurrent.ThreadFactoryBuilder;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.netvirt.utils.mdsal.utils.MdsalUtils;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.providers.config.rev160109.NetvirtProvidersConfig;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.providers.config.rev160109.NetvirtProvidersConfigBuilder;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class NetvirtProvidersConfigImpl implements AutoCloseable, ConfigInterface, DataChangeListener {
- private static final Logger LOG = LoggerFactory.getLogger(NetvirtProvidersConfigImpl.class);
- private final DataBroker dataBroker;
- private final ListenerRegistration<DataChangeListener> registration;
- private static final ThreadFactory threadFactory = new ThreadFactoryBuilder()
- .setNameFormat("NV-ProviderCfg-%d").build();
- private final ExecutorService executorService = Executors.newFixedThreadPool(1, threadFactory);
- private final MdsalUtils mdsalUtils;
-
- public NetvirtProvidersConfigImpl(final DataBroker dataBroker, final short tableOffset) {
- this.dataBroker = dataBroker;
- mdsalUtils = new MdsalUtils(dataBroker);
-
- InstanceIdentifier<NetvirtProvidersConfig> path =
- InstanceIdentifier.builder(NetvirtProvidersConfig.class).build();
- registration = dataBroker.registerDataChangeListener(LogicalDatastoreType.CONFIGURATION, path, this,
- AsyncDataBroker.DataChangeScope.SUBTREE);
-
- NetvirtProvidersConfigBuilder netvirtProvidersConfigBuilder = new NetvirtProvidersConfigBuilder();
- NetvirtProvidersConfig netvirtProvidersConfig =
- mdsalUtils.read(LogicalDatastoreType.CONFIGURATION, path);
- if (netvirtProvidersConfig != null) {
- netvirtProvidersConfigBuilder = new NetvirtProvidersConfigBuilder(netvirtProvidersConfig);
- }
- if (netvirtProvidersConfigBuilder.getTableOffset() == null) {
- netvirtProvidersConfigBuilder.setTableOffset(tableOffset);
- }
- boolean result = mdsalUtils.merge(LogicalDatastoreType.CONFIGURATION, path,
- netvirtProvidersConfigBuilder.build());
-
- LOG.info("NetvirtProvidersConfigImpl: dataBroker= {}, registration= {}, tableOffset= {}, result= {}",
- dataBroker, registration, tableOffset, result);
- }
-
- @Override
- public void close() throws Exception {
- registration.close();
- executorService.shutdown();
- }
-
- @Override
- public void onDataChanged(final AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> asyncDataChangeEvent) {
- executorService.submit(() -> {
- LOG.info("onDataChanged: {}", asyncDataChangeEvent);
- processConfigCreate(asyncDataChangeEvent);
- processConfigUpdate(asyncDataChangeEvent);
- });
- }
-
- private void processConfigCreate(AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes) {
- for (Map.Entry<InstanceIdentifier<?>, DataObject> entry : changes.getCreatedData().entrySet()) {
- if (entry.getValue() instanceof NetvirtProvidersConfig) {
- NetvirtProvidersConfig netvirtProvidersConfig = (NetvirtProvidersConfig) entry.getValue();
- applyConfig(netvirtProvidersConfig);
- }
- }
- }
-
- private void processConfigUpdate(AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes) {
- for (Map.Entry<InstanceIdentifier<?>, DataObject> entry : changes.getUpdatedData().entrySet()) {
- if (entry.getValue() instanceof NetvirtProvidersConfig) {
- LOG.info("processConfigUpdate: {}", entry);
- NetvirtProvidersConfig netvirtProvidersConfig = (NetvirtProvidersConfig) entry.getValue();
- applyConfig(netvirtProvidersConfig);
- }
- }
- }
-
- private void applyConfig(NetvirtProvidersConfig netvirtProvidersConfig) {
- LOG.info("processConfigUpdate: {}", netvirtProvidersConfig);
- if (netvirtProvidersConfig.getTableOffset() != null) {
- NetvirtProvidersProvider.setTableOffset(netvirtProvidersConfig.getTableOffset());
- }
- if (netvirtProvidersConfig.getSecurityGroupTcpIdleTimeout() != null) {
- NetvirtProvidersProvider.setSecurityGroupTcpIdleTimeout(netvirtProvidersConfig.getSecurityGroupTcpIdleTimeout());
- }
- if (netvirtProvidersConfig.getSecurityGroupTcpHardTimeout() != null) {
- NetvirtProvidersProvider.setSecurityGroupTcpHardTimeout(netvirtProvidersConfig.getSecurityGroupTcpHardTimeout());
- }
- if (netvirtProvidersConfig.getSecurityGroupTcpFinIdleTimeout() != null) {
- NetvirtProvidersProvider.setSecurityGroupTcpFinIdleTimeout(netvirtProvidersConfig.getSecurityGroupTcpFinIdleTimeout());
- }
- if (netvirtProvidersConfig.getSecurityGroupTcpFinHardTimeout() != null) {
- NetvirtProvidersProvider.setSecurityGroupTcpFinHardTimeout(netvirtProvidersConfig.getSecurityGroupTcpFinHardTimeout());
- }
- if (netvirtProvidersConfig.getSecurityGroupUdpIdleTimeout() != null) {
- NetvirtProvidersProvider.setSecurityGroupUdpIdleTimeout(netvirtProvidersConfig.getSecurityGroupUdpIdleTimeout());
- }
- if (netvirtProvidersConfig.getSecurityGroupUdpHardTimeout() != null) {
- NetvirtProvidersProvider.setSecurityGroupUdpHardTimeout(netvirtProvidersConfig.getSecurityGroupUdpHardTimeout());
- }
- if (netvirtProvidersConfig.getSecurityGroupDefaultIdleTimeout() != null) {
- NetvirtProvidersProvider.setSecurityGroupDefaultIdleTimeout(netvirtProvidersConfig.getSecurityGroupDefaultIdleTimeout());
- }
- if (netvirtProvidersConfig.getSecurityGroupDefaultHardTimeout() != null) {
- NetvirtProvidersProvider.setSecurityGroupDefaultHardTimeout(netvirtProvidersConfig.getSecurityGroupDefaultHardTimeout());
- }
- }
-
- @Override
- public void setDependencies(BundleContext bundleContext, ServiceReference serviceReference) {
-
- }
-
- @Override
- public void setDependencies(Object impl) {
-
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.providers;
-
-import java.util.concurrent.atomic.AtomicBoolean;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.common.api.clustering.CandidateAlreadyRegisteredException;
-import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
-import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidateRegistration;
-import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipChange;
-import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListener;
-import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListenerRegistration;
-import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
-import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.SalFlowService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketProcessingService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.TableId;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.FrameworkUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * @author Sam Hague (shague@redhat.com)
- */
-public class NetvirtProvidersProvider implements AutoCloseable {
- private static final Logger LOG = LoggerFactory.getLogger(NetvirtProvidersProvider.class);
-
- private final BundleContext bundleContext;
- private static DataBroker dataBroker;
- private ConfigActivator activator;
- private final EntityOwnershipService entityOwnershipService;
- private ProviderEntityListener providerEntityListener = null;
- private static AtomicBoolean hasProviderEntityOwnership = new AtomicBoolean(false);
- private static short tableOffset;
- private final NotificationProviderService notificationProviderService;
- private final PacketProcessingService packetProcessingService;
- private final SalFlowService salFlowService;
- private static long securityGroupTcpIdleTimeout;
- private static long securityGroupTcpHardTimeout;
- private static long securityGroupTcpFinIdleTimeout;
- private static long securityGroupTcpFinHardTimeout;
- private static long securityGroupUdpIdleTimeout;
- private static long securityGroupUdpHardTimeout;
- private static long securityGroupDefaultIdleTimeout;
- private static long securityGroupDefaultHardTimeout;
-
- public NetvirtProvidersProvider(final DataBroker dataBroker,
- final EntityOwnershipService eos,
- final NotificationProviderService notificationProviderService,
- final PacketProcessingService packetProcessingService,
- final SalFlowService salFlowService,
- final short tableOffset) {
- LOG.info("NetvirtProvidersProvider");
- NetvirtProvidersProvider.dataBroker = dataBroker;
- this.notificationProviderService = notificationProviderService;
- this.entityOwnershipService = eos;
- this.bundleContext = FrameworkUtil.getBundle(NetvirtProvidersProvider.class).getBundleContext();
- this.salFlowService = salFlowService;
- this.packetProcessingService = packetProcessingService;
- setTableOffset(tableOffset);
- }
-
- public static boolean isMasterProviderInstance() {
- return hasProviderEntityOwnership.get();
- }
-
- public static void setTableOffset(short tableOffset) {
- try {
- new TableId((short) (tableOffset + Service.L2_FORWARDING.getTable()));
- } catch (IllegalArgumentException e) {
- LOG.warn("Invalid table offset: {}", tableOffset, e);
- return;
- }
-
- LOG.info("setTableOffset: changing from {} to {}",
- NetvirtProvidersProvider.tableOffset, tableOffset);
- NetvirtProvidersProvider.tableOffset = tableOffset;
- }
-
- public static short getTableOffset() {
- return tableOffset;
- }
-
- public static void setSecurityGroupTcpIdleTimeout(long timeout) {
- LOG.info("setSecurityGroupTcpIdleTimeout: changing from {} to {}",
- NetvirtProvidersProvider.securityGroupTcpIdleTimeout, timeout);
- NetvirtProvidersProvider.securityGroupTcpIdleTimeout = timeout;
- }
-
- public static long getSecurityGroupTcpIdleTimeout() {
- return securityGroupTcpIdleTimeout;
- }
-
- public static void setSecurityGroupTcpHardTimeout(long timeout) {
- LOG.info("setSecurityGroupTcpHardTimeout: changing from {} to {}",
- NetvirtProvidersProvider.securityGroupTcpHardTimeout, timeout);
- NetvirtProvidersProvider.securityGroupTcpHardTimeout = timeout;
- }
-
- public static long getSecurityGroupTcpHardTimeout() {
- return securityGroupTcpHardTimeout;
- }
-
- public static void setSecurityGroupTcpFinIdleTimeout(long timeout) {
- LOG.info("setSecurityGroupTcpFinIdleTimeout: changing from {} to {}",
- NetvirtProvidersProvider.securityGroupTcpFinIdleTimeout, timeout);
- NetvirtProvidersProvider.securityGroupTcpFinIdleTimeout = timeout;
- }
-
- public static long getSecurityGroupTcpFinIdleTimeout() {
- return securityGroupTcpFinIdleTimeout;
- }
-
- public static void setSecurityGroupTcpFinHardTimeout(long timeout) {
- LOG.info("setSecurityGroupTcpFinHardTimeout: changing from {} to {}",
- NetvirtProvidersProvider.securityGroupTcpFinHardTimeout, timeout);
- NetvirtProvidersProvider.securityGroupTcpFinHardTimeout = timeout;
- }
-
- public static long getSecurityGroupTcpFinHardTimeout() {
- return securityGroupTcpFinHardTimeout;
- }
-
- public static void setSecurityGroupUdpIdleTimeout(long timeout) {
- LOG.info("setSecurityGroupUdpIdleTimeout: changing from {} to {}",
- NetvirtProvidersProvider.securityGroupUdpIdleTimeout, timeout);
- NetvirtProvidersProvider.securityGroupUdpIdleTimeout = timeout;
- }
-
- public static long getSecurityGroupUdpIdleTimeout() {
- return securityGroupUdpIdleTimeout;
- }
-
- public static void setSecurityGroupUdpHardTimeout(long timeout) {
- LOG.info("setSecurityGroupUdpHardTimeout: changing from {} to {}",
- NetvirtProvidersProvider.securityGroupUdpHardTimeout, timeout);
- NetvirtProvidersProvider.securityGroupUdpHardTimeout = timeout;
- }
-
- public static long getSecurityGroupUdpHardTimeout() {
- return securityGroupUdpHardTimeout;
- }
-
- public static void setSecurityGroupDefaultIdleTimeout(long timeout) {
- LOG.info("setSecurityGroupDefaultIdleTimeout: changing from {} to {}",
- NetvirtProvidersProvider.securityGroupDefaultIdleTimeout, timeout);
- NetvirtProvidersProvider.securityGroupDefaultIdleTimeout = timeout;
- }
-
- public static long getSecurityGroupDefaultIdleTimeout() {
- return securityGroupDefaultIdleTimeout;
- }
-
- public static void setSecurityGroupDefaultHardTimeout(long timeout) {
- LOG.info("setSecurityGroupDefaultHardTimeout: changing from {} to {}",
- NetvirtProvidersProvider.securityGroupDefaultHardTimeout, timeout);
- NetvirtProvidersProvider.securityGroupDefaultHardTimeout = timeout;
- }
-
- public static long getSecurityGroupDefaultHardTimeout() {
- return securityGroupDefaultHardTimeout;
- }
-
- @Override
- public void close() throws Exception {
- LOG.info("NetvirtProvidersProvider closed");
- activator.stop(bundleContext);
- providerEntityListener.close();
- }
-
- public void start() {
- LOG.info("NetvirtProvidersProvider: onSessionInitiated dataBroker: {}", dataBroker);
- providerEntityListener = new ProviderEntityListener(this, entityOwnershipService);
- this.activator = new ConfigActivator(dataBroker, notificationProviderService, packetProcessingService, salFlowService);
- try {
- activator.start(bundleContext);
- } catch (Exception e) {
- LOG.warn("Failed to start Netvirt: ", e);
- }
- }
-
- private void handleOwnershipChange(EntityOwnershipChange ownershipChange) {
- if (ownershipChange.isOwner()) {
- LOG.info("*This* instance of OVSDB netvirt provider is a MASTER instance");
- hasProviderEntityOwnership.set(true);
- } else {
- LOG.info("*This* instance of OVSDB netvirt provider is a SLAVE instance");
- hasProviderEntityOwnership.set(false);
- }
- }
-
- private class ProviderEntityListener implements EntityOwnershipListener {
- private NetvirtProvidersProvider provider;
- private EntityOwnershipListenerRegistration listenerRegistration;
- private EntityOwnershipCandidateRegistration candidateRegistration;
-
- ProviderEntityListener(NetvirtProvidersProvider provider,
- EntityOwnershipService entityOwnershipService) {
- this.provider = provider;
- this.listenerRegistration =
- entityOwnershipService.registerListener(Constants.NETVIRT_OWNER_ENTITY_TYPE, this);
-
- //register instance entity to get the ownership of the netvirt provider
- Entity instanceEntity = new Entity(
- Constants.NETVIRT_OWNER_ENTITY_TYPE, Constants.NETVIRT_OWNER_ENTITY_TYPE);
- try {
- this.candidateRegistration = entityOwnershipService.registerCandidate(instanceEntity);
- } catch (CandidateAlreadyRegisteredException e) {
- LOG.warn("OVSDB Netvirt Provider instance entity {} was already "
- + "registered for ownership", instanceEntity, e);
- }
- }
-
- public void close() {
- this.listenerRegistration.close();
- this.candidateRegistration.close();
- }
-
- @Override
- public void ownershipChanged(EntityOwnershipChange ownershipChange) {
- provider.handleOwnershipChange(ownershipChange);
- }
- }
-
- public static DataBroker getDataBroker() {
- return dataBroker;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.providers.openflow13;
-
-import com.google.common.base.Optional;
-import com.google.common.util.concurrent.CheckedFuture;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.ExecutionException;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
-import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.openstack.netvirt.providers.NetvirtProvidersProvider;
-import org.opendaylight.netvirt.utils.mdsal.openflow.InstructionUtils;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
-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.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.list.Instruction;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
-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.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Any ServiceInstance class that extends AbstractServiceInstance to be a part of the pipeline
- * have 2 basic requirements : <br>
- * 1. Program a default pipeline flow to take any unmatched traffic to the next table in the pipeline. <br>
- * 2. Get Pipeline Instructions from AbstractServiceInstance (using getMutablePipelineInstructionBuilder) and
- * use it in any matching flows that needs to be further processed by next service in the pipeline.
- *
- */
-public abstract class AbstractServiceInstance {
- public static final String SERVICE_PROPERTY ="serviceProperty";
- private static final Logger LOG = LoggerFactory.getLogger(AbstractServiceInstance.class);
- public static final String OPENFLOW = "openflow:";
- protected DataBroker dataBroker = null;
- // OSGi Services that we are dependent on.
- private volatile PipelineOrchestrator orchestrator;
- private volatile Southbound southbound;
-
- // Concrete Service that this AbstractServiceInstance represents
- private Service service;
-
- public AbstractServiceInstance (Service service) {
- this.service = service;
- this.dataBroker = NetvirtProvidersProvider.getDataBroker();
- }
-
- protected void setDependencies(final ServiceReference ref, AbstractServiceInstance serviceInstance) {
- this.orchestrator =
- (PipelineOrchestrator) ServiceHelper.getGlobalInstance(PipelineOrchestrator.class, serviceInstance);
- orchestrator.registerService(ref, serviceInstance);
- this.southbound =
- (Southbound) ServiceHelper.getGlobalInstance(Southbound.class, serviceInstance);
- }
-
- public boolean isBridgeInPipeline (Node node){
- String bridgeName = southbound.getBridgeName(node);
- return bridgeName != null && Constants.INTEGRATION_BRIDGE.equals(bridgeName);
- }
-
- /**
- * Return the offset adjusted table for this {@link Service}
- * @return The table id
- */
- public short getTable() {
- return (short)(orchestrator.getTableOffset() + service.getTable());
- }
-
- /**
- * Return the offset adjusted table for the given {@link Service}
- * @param service Identifies the openflow {@link Service}
- * @return The table id
- */
- public short getTable(Service service) {
- return (short)(orchestrator.getTableOffset() + service.getTable());
- }
-
- public Service getService() {
- return service;
- }
-
- public void setService(Service service) {
- this.service = service;
- }
-
- public NodeBuilder createNodeBuilder(String nodeId) {
- NodeBuilder builder = new NodeBuilder();
- builder.setId(new NodeId(nodeId));
- builder.setKey(new NodeKey(builder.getId()));
- return builder;
- }
-
- protected static InstanceIdentifier<Flow> createFlowPath(FlowBuilder flowBuilder, NodeBuilder nodeBuilder) {
- return InstanceIdentifier.builder(Nodes.class)
- .child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node.class,
- nodeBuilder.getKey())
- .augmentation(FlowCapableNode.class)
- .child(Table.class, new TableKey(flowBuilder.getTableId()))
- .child(Flow.class, flowBuilder.getKey()).build();
- }
-
- private static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node>
- createNodePath(NodeBuilder nodeBuilder) {
- return InstanceIdentifier.builder(Nodes.class)
- .child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node.class,
- nodeBuilder.getKey()).build();
- }
-
- /**
- * This method returns the required Pipeline Instructions to by used by any matching flows that need
- * to be further processed by next service in the pipeline.
- *
- * Important to note that this is a convenience method which returns a mutable instructionBuilder which
- * needs to be further adjusted by the concrete ServiceInstance class such as setting the Instruction Order, etc.
- * @return Newly created InstructionBuilder to be used along with other instructions on the main flow
- */
- protected final InstructionBuilder getMutablePipelineInstructionBuilder() {
- Service nextService = orchestrator.getNextServiceInPipeline(service);
- if (nextService != null) {
- return InstructionUtils.createGotoTableInstructions(new InstructionBuilder(),
- orchestrator.getTable(nextService));
- } else {
- return InstructionUtils.createDropInstructions(new InstructionBuilder());
- }
- }
-
- protected void writeFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder) {
- if (NetvirtProvidersProvider.isMasterProviderInstance()) {
- LOG.debug("writeFlow: flowBuilder: {}, nodeBuilder: {}",
- flowBuilder.build(), nodeBuilder.build());
- WriteTransaction modification = dataBroker.newWriteOnlyTransaction();
- //modification.put(LogicalDatastoreType.CONFIGURATION, createNodePath(nodeBuilder),
- // nodeBuilder.build(), true /*createMissingParents*/);
- modification.put(LogicalDatastoreType.CONFIGURATION, createFlowPath(flowBuilder, nodeBuilder),
- flowBuilder.build(), true /*createMissingParents*/);
- CheckedFuture<Void, TransactionCommitFailedException> commitFuture = modification.submit();
- try {
- commitFuture.checkedGet(); // TODO: Make it async (See bug 1362)
- LOG.debug("Transaction success for write of Flow : {}", flowBuilder.getFlowName());
- } catch (Exception e) {
- LOG.error("Failed to write flow : {}", flowBuilder.getFlowName(), e);
- modification.cancel();
- }
- }
- }
-
- protected void removeFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder) {
- if (NetvirtProvidersProvider.isMasterProviderInstance()) {
- LOG.debug("removeFlow: flowBuilder: {}, nodeBuilder: {}",
- flowBuilder.build(), nodeBuilder.build());
- WriteTransaction modification = dataBroker.newWriteOnlyTransaction();
- modification.delete(LogicalDatastoreType.CONFIGURATION, createFlowPath(flowBuilder, nodeBuilder));
-
- CheckedFuture<Void, TransactionCommitFailedException> commitFuture = modification.submit();
- try {
- commitFuture.get(); // TODO: Make it async (See bug 1362)
- LOG.debug("Transaction success for deletion of Flow : {}", flowBuilder.getFlowName());
- } catch (Exception e) {
- LOG.error("Failed to remove flow : {}", flowBuilder.getFlowName(), e);
- modification.cancel();
- }
- }
- }
-
- public Flow getFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder) {
- ReadOnlyTransaction readTx = dataBroker.newReadOnlyTransaction();
- try {
- Optional<Flow> data =
- readTx.read(LogicalDatastoreType.CONFIGURATION, createFlowPath(flowBuilder, nodeBuilder)).get();
- if (data.isPresent()) {
- return data.get();
- }
- } catch (InterruptedException|ExecutionException e) {
- LOG.error("Failed to get flow : {}", flowBuilder.getFlowName(), e);
- }
-
- LOG.debug("Cannot find data for Flow : {}", flowBuilder.getFlowName());
- return null;
- }
-
- public org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node
- getOpenFlowNode(String nodeId) {
-
- ReadOnlyTransaction readTx = dataBroker.newReadOnlyTransaction();
- try {
- Optional<org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node> data =
- readTx.read(LogicalDatastoreType.OPERATIONAL, createNodePath(createNodeBuilder(nodeId))).get();
- if (data.isPresent()) {
- return data.get();
- }
- } catch (InterruptedException|ExecutionException e) {
- LOG.error("Failed to get openflow node : {}", nodeId, e);
- }
-
- LOG.debug("Cannot find data for Node : {}", nodeId);
- return null;
- }
-
- private long getDpid(Node node) {
- long dpid = southbound.getDataPathId(node);
- if (dpid == 0) {
- LOG.warn("getDpid: dpid not found for the Node: {}", node);
- }
- return dpid;
- }
-
- /**
- * Program Default Pipeline Flow.
- *
- * @param node on which the default pipeline flow is programmed.
- */
- protected void programDefaultPipelineRule(Node node) {
- if (!isBridgeInPipeline(node)) {
- //LOG.trace("Bridge is not in pipeline {} ", node);
- return;
- }
- MatchBuilder matchBuilder = new MatchBuilder();
- FlowBuilder flowBuilder = new FlowBuilder();
- long dpid = getDpid(node);
- if (dpid == 0L) {
- LOG.trace("could not find dpid for the Node: {}", node.getNodeId());
- return;
- }
- String nodeName = OPENFLOW + getDpid(node);
- NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
-
- // Create the OF Actions and Instructions
- InstructionsBuilder isb = new InstructionsBuilder();
-
- // Instructions List Stores Individual Instructions
- List<Instruction> instructions = new ArrayList<>();
-
- // 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);
-
- // Add InstructionsBuilder to FlowBuilder
- flowBuilder.setInstructions(isb.build());
-
- String flowId = "DEFAULT_PIPELINE_FLOW_" + getTable();
- flowBuilder.setId(new FlowId(flowId));
- FlowKey key = new FlowKey(new FlowId(flowId));
- flowBuilder.setMatch(matchBuilder.build());
- flowBuilder.setPriority(0);
- flowBuilder.setBarrier(false);
- flowBuilder.setTableId(getTable());
- flowBuilder.setKey(key);
- flowBuilder.setFlowName(flowId);
- flowBuilder.setHardTimeout(0);
- flowBuilder.setIdleTimeout(0);
- writeFlow(flowBuilder, nodeBuilder);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.providers.openflow13;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.util.concurrent.CheckedFuture;
-import java.net.InetAddress;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ExecutionException;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
-import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
-import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
-import org.opendaylight.netvirt.openstack.netvirt.MdsalHelper;
-import org.opendaylight.netvirt.openstack.netvirt.NetworkHandler;
-import org.opendaylight.netvirt.openstack.netvirt.api.BridgeConfigurationManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.ClassifierProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.ConfigurationService;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-import org.opendaylight.netvirt.openstack.netvirt.api.EgressAclProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.IngressAclProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.L2ForwardingLearnProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.L2ForwardingProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.NetworkingProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.NetworkingProviderManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.ResubmitAclLearnProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.SecurityGroupCacheManger;
-import org.opendaylight.netvirt.openstack.netvirt.api.SecurityServicesManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.openstack.netvirt.api.Status;
-import org.opendaylight.netvirt.openstack.netvirt.api.StatusCode;
-import org.opendaylight.netvirt.openstack.netvirt.api.TenantNetworkManager;
-import org.opendaylight.netvirt.openstack.netvirt.providers.ConfigInterface;
-import org.opendaylight.netvirt.openstack.netvirt.providers.NetvirtProvidersProvider;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityGroup;
-import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs;
-import org.opendaylight.netvirt.utils.mdsal.openflow.FlowUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.InstructionUtils;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.GroupActionCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.GroupActionCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.OutputActionCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.OutputActionCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.group.action._case.GroupActionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.output.action._case.OutputActionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
-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.flow.inventory.rev130819.FlowCapableNode;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
-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.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.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;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.BucketId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupTypes;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.Buckets;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.BucketsBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.buckets.Bucket;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.buckets.BucketBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.buckets.BucketKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
-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.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPoint;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Open vSwitch OpenFlow 1.3 Networking Provider for OpenStack Neutron
- *
- * @author Madhu Venugopal
- * @author Brent Salisbury
- * @author Dave Tucker
- * @author Sam Hague
- */
-// Methods' parameters in this class follow the same pattern to avoid confusion between same-typed parameters
-// The patterns need to be preserved even though not all parameters are used in all methods
-@SuppressWarnings("UnusedParameters")
-public class OF13Provider implements ConfigInterface, NetworkingProvider {
- private static final Logger LOG = LoggerFactory.getLogger(OF13Provider.class);
- private static final short TABLE_0_DEFAULT_INGRESS = 0;
- private static final short TABLE_1_ISOLATE_TENANT = 10;
- private static final short TABLE_2_LOCAL_FORWARD = 20;
- private static Long groupId = 1L;
- private DataBroker dataBroker = null;
-
- private volatile ConfigurationService configurationService;
- private volatile BridgeConfigurationManager bridgeConfigurationManager;
- private volatile TenantNetworkManager tenantNetworkManager;
- private volatile SecurityServicesManager securityServicesManager;
- private volatile ClassifierProvider classifierProvider;
- private volatile IngressAclProvider ingressAclProvider;
- private volatile EgressAclProvider egressAclProvider;
- private volatile NodeCacheManager nodeCacheManager;
- private volatile ResubmitAclLearnProvider resubmitAclLearnProvider;
- private volatile L2ForwardingLearnProvider l2ForwardingLearnProvider;
- private volatile L2ForwardingProvider l2ForwardingProvider;
- private volatile SecurityGroupCacheManger securityGroupCacheManger;
-
- public static final String NAME = "OF13Provider";
- private volatile BundleContext bundleContext;
- private volatile Southbound southbound;
-
- private Set<org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId>
- intBridgesWithoutVmPorts = new HashSet<>();
-
- public OF13Provider() {
- this.dataBroker = NetvirtProvidersProvider.getDataBroker();
- }
-
- @Override
- public String getName() {
- return NAME;
- }
-
- @Override
- public boolean supportsServices() {
- return true;
- }
-
- @Override
- public boolean hasPerTenantTunneling() {
- return false;
- }
-
- // The method is tested for in OF13ProviderTest
- @SuppressWarnings("unused")
- private Status getTunnelReadinessStatus (Node node, String tunnelKey) {
- InetAddress srcTunnelEndPoint = configurationService.getTunnelEndPoint(node);
- if (srcTunnelEndPoint == null) {
- LOG.error("Tunnel Endpoint not configured for Node {}", node);
- return new Status(StatusCode.NOTFOUND, "Tunnel Endpoint not configured for "+ node);
- }
-
- if (!bridgeConfigurationManager.isNodeNeutronReady(node)) {
- LOG.error("{} is not Overlay ready", node);
- return new Status(StatusCode.NOTACCEPTABLE, node+" is not Overlay ready");
- }
-
- if (!tenantNetworkManager.isTenantNetworkPresentInNode(node, tunnelKey)) {
- LOG.debug("{} has no VM corresponding to segment {}", node, tunnelKey);
- return new Status(StatusCode.NOTACCEPTABLE, node+" has no VM corresponding to segment "+ tunnelKey);
- }
- return new Status(StatusCode.SUCCESS);
- }
-
- private String getTunnelName(String tunnelType, InetAddress dst) {
- return tunnelType+"-"+dst.getHostAddress();
- }
-
- private boolean addTunnelPort (Node node, String tunnelType, InetAddress src, InetAddress dst) {
- String tunnelBridgeName = configurationService.getIntegrationBridgeName();
- String portName = getTunnelName(tunnelType, dst);
- LOG.trace("Added TunnelPort : portName: {}", portName);
- if (southbound.extractTerminationPointAugmentation(node, portName) != null
- || southbound.isTunnelTerminationPointExist(node, tunnelBridgeName, portName)) {
- if (LOG.isTraceEnabled()) {
- LOG.trace("Tunnel {} is present in {} of {}", portName, tunnelBridgeName, node.getNodeId().getValue());
- }
- return true;
- }
-
- Map<String, String> options = new HashMap<>();
- options.put("key", "flow");
- options.put("local_ip", src.getHostAddress());
- options.put("remote_ip", dst.getHostAddress());
-
- if (!southbound.addTunnelTerminationPoint(node, tunnelBridgeName, portName, tunnelType, options)) {
- LOG.error("Failed to insert Tunnel port {} in {}", portName, tunnelBridgeName);
- return false;
- }
-
- LOG.info("addTunnelPort exit: portName: {}", portName);
- return true;
- }
-
- /* delete port from ovsdb port table */
- private boolean deletePort(Node node, String bridgeName, String portName) {
- // TODO SB_MIGRATION
- // might need to convert from ovsdb node to bridge node
- return southbound.deleteTerminationPoint(node, portName);
- }
-
- private boolean deleteTunnelPort(Node node, String tunnelType, InetAddress src, InetAddress dst) {
- String tunnelBridgeName = configurationService.getIntegrationBridgeName();
- String portName = getTunnelName(tunnelType, dst);
- return deletePort(node, tunnelBridgeName, portName);
- }
-
- private boolean deletePhysicalPort(Node node, String phyIntfName) {
- String intBridgeName = configurationService.getIntegrationBridgeName();
- return deletePort(node, intBridgeName, phyIntfName);
- }
-
- private void programLocalBridgeRules(Node node, Long dpid, String segmentationId,
- String attachedMac, long localPort) {
- /*
- * Table(0) Rule #3
- * ----------------
- * Match: VM sMac and Local Ingress Port
- * Action:Action: Set Tunnel ID and GOTO Local Table (5)
- */
-
- handleLocalInPort(dpid, TABLE_0_DEFAULT_INGRESS, TABLE_1_ISOLATE_TENANT,
- segmentationId, localPort, attachedMac, true);
-
- /*
- * Table(0) Rule #4
- * ----------------
- * Match: Drop any remaining Ingress Local VM Packets
- * Action: Drop w/ a low priority
- */
-
- handleDropSrcIface(dpid, localPort, true);
-
- /*
- * Table(2) Rule #1
- * ----------------
- * Match: Match TunID and Destination DL/dMAC Addr
- * Action: Output Port
- * table=2,tun_id=0x5,dl_dst=00:00:00:00:00:01 actions=output:2
- */
-
- handleLocalUcastOut(dpid, TABLE_2_LOCAL_FORWARD, segmentationId, localPort, attachedMac, true);
-
- /*
- * Table(2) Rule #2
- * ----------------
- * Match: Tunnel ID and dMAC (::::FF:FF)
- * table=2,priority=16384,tun_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
- * actions=output:2,3,4,5
- */
-
- handleLocalBcastOut(dpid, TABLE_2_LOCAL_FORWARD, segmentationId, localPort, true);
- handleTunnelFloodOut(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD, segmentationId, localPort, true);
-
- /*
- * Table(110) Rule #1
- * ----------------
- * Match: Tunnel ID and unknown unicast
- * table=110,priority=16380,tun_id=0x5,dl_dst=00:00:00:00:00:00/01:00:00:00:00:00 \
- * actions=output:2,3,4,5
- */
-
- handleTunnelUnknownUcastFloodOut(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD, segmentationId, localPort, true);
- }
-
- private void removeLocalBridgeRules(Node node, Long dpid, String segmentationId, String attachedMac, long localPort, boolean isMigratedPort) {
- /*
- * Table(0) Rule #3
- * ----------------
- * Match: VM sMac and Local Ingress Port
- * Action:Action: Set Tunnel ID and GOTO Local Table (5)
- */
-
- handleLocalInPort(dpid, TABLE_0_DEFAULT_INGRESS, TABLE_1_ISOLATE_TENANT, segmentationId, localPort, attachedMac, false);
-
- /*
- * Table(0) Rule #4
- * ----------------
- * Match: Drop any remaining Ingress Local VM Packets
- * Action: Drop w/ a low priority
- */
-
- handleDropSrcIface(dpid, localPort, false);
-
- /*
- * Table(2) Rule #1
- * ----------------
- * Match: Match TunID and Destination DL/dMAC Addr
- * Action: Output Port
- * table=2,tun_id=0x5,dl_dst=00:00:00:00:00:01 actions=output:2
- */
-
- if(!isMigratedPort) {
- handleLocalUcastOut(dpid, TABLE_2_LOCAL_FORWARD, segmentationId, localPort, attachedMac, false);
- }
-
- /*
- * Table(2) Rule #2
- * ----------------
- * Match: Tunnel ID and dMAC (::::FF:FF)
- * table=2,priority=16384,tun_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
- * actions=output:2,3,4,5
- */
-
- handleLocalBcastOut(dpid, TABLE_2_LOCAL_FORWARD, segmentationId, localPort, false);
- handleTunnelFloodOut(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD, segmentationId, localPort, false);
-
- /*
- * Table(110) Rule #1
- * ----------------
- * Match: Tunnel ID and unknown unicast
- * table=110,priority=16380,tun_id=0x5,dl_dst=00:00:00:00:00:00/01:00:00:00:00:00 \
- * actions=output:2,3,4,5
- */
-
- handleTunnelUnknownUcastFloodOut(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD, segmentationId, localPort, false);
- }
-
- private void programLocalIngressTunnelBridgeRules(Node node, Long dpid, String segmentationId, String attachedMac, long tunnelOFPort, long localPort) {
- /*
- * Table(0) Rule #2
- * ----------------
- * Match: Ingress Port, Tunnel ID
- * Action: GOTO Local Table (20)
- */
-
- handleTunnelIn(dpid, TABLE_0_DEFAULT_INGRESS, TABLE_2_LOCAL_FORWARD, segmentationId, tunnelOFPort, true);
-
- /*
- * Table(1) Rule #2
- * ----------------
- * Match: Match Tunnel ID and L2 ::::FF:FF Flooding
- * Action: Flood to selected destination TEPs
- * -------------------------------------------
- * table=1,priority=16384,tun_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
- * actions=output:10,output:11,goto_table:2
- */
-
- handleTunnelFloodOut(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD, segmentationId, tunnelOFPort, true);
-
- /*
- * Table(110) Rule #1
- * ----------------
- * Match: Tunnel ID and unknown unicast
- * table=110,priority=16380,tun_id=0x5,dl_dst=00:00:00:00:00:00/01:00:00:00:00:00 \
- * actions=output:2,3,4,5
- */
- handleTunnelUnknownUcastFloodOut(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD, segmentationId, tunnelOFPort, true);
-
- }
-
- private void programRemoteEgressTunnelBridgeRules(Node node, Long dpid, String segmentationId, String attachedMac, long tunnelOFPort, long localPort) {
- /*
- * Table(1) Rule #1
- * ----------------
- * Match: Drop any remaining Ingress Local VM Packets
- * Action: Drop w/ a low priority
- * -------------------------------------------
- * table=1,tun_id=0x5,dl_dst=00:00:00:00:00:08 \
- * actions=output:11,goto_table:2
- */
-
- handleTunnelOut(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD, segmentationId, tunnelOFPort, attachedMac, true);
- }
-
- private void removeRemoteEgressTunnelBridgeRules(Node node, Long dpid, String segmentationId, String attachedMac, long tunnelOFPort, long localPort) {
- /*
- * Table(1) Rule #1
- * ----------------
- * Match: Drop any remaining Ingress Local VM Packets
- * Action: Drop w/ a low priority
- * -------------------------------------------
- * table=1,tun_id=0x5,dl_dst=00:00:00:00:00:08 \
- * actions=output:11,goto_table:2
- */
-
- handleTunnelOut(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD, segmentationId, tunnelOFPort, attachedMac, false);
- }
-
- /* Remove tunnel rules if last node in this tenant network */
- private void removePerTunnelRules(Node node, Long dpid, String segmentationId, long tunnelOFPort) {
- /*
- * Table(0) Rule #2
- * ----------------
- * Match: Ingress Port, Tunnel ID
- * Action: GOTO Local Table (10)
- */
-
- handleTunnelIn(dpid, TABLE_0_DEFAULT_INGRESS, TABLE_2_LOCAL_FORWARD, segmentationId, tunnelOFPort, false);
-
- /*
- * Table(1) Rule #2
- * ----------------
- * Match: Match Tunnel ID and L2 ::::FF:FF Flooding
- * Action: Flood to selected destination TEPs
- * -------------------------------------------
- * table=1,priority=16384,tun_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
- * actions=output:10,output:11,goto_table:2
- */
-
- handleTunnelFloodOut(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD, segmentationId, tunnelOFPort, false);
-
- /*
- * Table(110) Rule #1
- * ----------------
- * Match: Tunnel ID and unknown unicast
- * table=110,priority=16380,tun_id=0x5,dl_dst=00:00:00:00:00:00/01:00:00:00:00:00 \
- * actions=output:2,3,4,5
- */
-
- handleTunnelUnknownUcastFloodOut(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD, segmentationId, tunnelOFPort, false);
- }
-
- private void programLocalVlanRules(Node node, Long dpid, String segmentationId, String attachedMac, long localPort) {
- /*
- * Table(0) Rule #1
- * ----------------
- * Tag traffic coming from the local port and vm srcmac
- * Match: VM sMac and Local Ingress Port
- * Action: Set VLAN ID and GOTO Local Table 1
- */
-
- handleLocalInPortSetVlan(dpid, TABLE_0_DEFAULT_INGRESS,
- TABLE_1_ISOLATE_TENANT, segmentationId, localPort,
- attachedMac, true);
-
- /*
- * Table(0) Rule #3
- * ----------------
- * Drop all other traffic coming from the local port
- * Match: Drop any remaining Ingress Local VM Packets
- * Action: Drop w/ a low priority
- */
-
- handleDropSrcIface(dpid, localPort, true);
-
- /*
- * Table(2) Rule #1
- * ----------------
- * Forward unicast traffic destined to the local port after stripping tag
- * Match: Match VLAN ID and Destination DL/dMAC Addr
- * Action: strip vlan, output to local port
- * Example: table=2,vlan_id=0x5,dl_dst=00:00:00:00:00:01 actions= strip vlan, output:2
- */
-
- handleLocalVlanUcastOut(dpid, TABLE_2_LOCAL_FORWARD, segmentationId,
- localPort, attachedMac, true);
-
- /*
- * Table(2) Rule #2
- * ----------------
- * Match: VLAN ID and dMAC (::::FF:FF)
- * Action: strip vlan, output to all local ports in this vlan
- * Example: table=2,priority=16384,vlan_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
- * actions= strip_vlan, output:2,3,4,5
- */
-
- //handleLocalVlanBcastOut(dpid, TABLE_2_LOCAL_FORWARD, segmentationId,
- // localPort, ethPort, true);
- //handleVlanFloodOut(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD,
- // segmentationId, localPort, ethport, true);
-
- /*
- * Table(2) Rule #3
- * ----------------
- * Match: Any Remaining Flows w/a VLAN ID
- * Action: Drop w/ a low priority
- * Example: table=2,priority=8192,vlan_id=0x5 actions=drop
- */
-
- //handleLocalVlanTableMiss(dpid, TABLE_2_LOCAL_FORWARD, segmentationId,
- // true);
- }
-
- private void removeLocalVlanRules(Node node, Long dpid,
- String segmentationId, String attachedMac, long localPort) {
- /*
- * Table(0) Rule #1
- * ----------------
- * Match: VM sMac and Local Ingress Port
- * Action: Set VLAN ID and GOTO Local Table 1
- */
-
- handleLocalInPortSetVlan(dpid, TABLE_0_DEFAULT_INGRESS,
- TABLE_1_ISOLATE_TENANT, segmentationId, localPort,
- attachedMac, false);
-
- /*
- * Table(0) Rule #3
- * ----------------
- * Match: Drop any remaining Ingress Local VM Packets
- * Action: Drop w/ a low priority
- */
-
- handleDropSrcIface(dpid, localPort, false);
-
- /*
- * Table(2) Rule #1
- * ----------------
- * Match: Match VLAN ID and Destination DL/dMAC Addr
- * Action: strip vlan, output to local port
- * Example: table=2,vlan_id=0x5,dl_dst=00:00:00:00:00:01 actions= strip vlan, output:2
- */
-
- handleLocalVlanUcastOut(dpid, TABLE_2_LOCAL_FORWARD, segmentationId,
- localPort, attachedMac, false);
-
- /*
- * Table(2) Rule #2
- * ----------------
- * Match: VLAN ID and dMAC (::::FF:FF)
- * Action: strip vlan, output to all local ports in this vlan
- * Example: table=2,priority=16384,vlan_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
- * actions= strip_vlan, output:2,3,4,5
- */
-
- //handleLocalVlanBcastOut(dpid, TABLE_2_LOCAL_FORWARD, segmentationId,
- // localPort, ethPort, false);
- //handleVlanFloodOut(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD,
- // segmentationId, localPort, false);
-
- }
-
- private void programLocalIngressVlanRules(Node node, Long dpid, String segmentationId, String attachedMac,
- long localPort, long ethPort) {
- /*
- * Table(0) Rule #2
- * ----------------
- * Match: Ingress port = physical interface, Vlan ID
- * Action: GOTO Local Table 2
- */
-
- handleVlanIn(dpid, TABLE_0_DEFAULT_INGRESS, TABLE_2_LOCAL_FORWARD,
- segmentationId, ethPort, true);
-
- /*
- * Table(1) Rule #2
- * ----------------
- * Match: Match VLAN ID and L2 ::::FF:FF Flooding
- * Action: Flood to local and remote VLAN members
- * -------------------------------------------
- * Example: table=1,priority=16384,vlan_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
- * actions=output:10 (eth port),goto_table:2
- * table=110, priority=16384,dl_vlan=2001,dl_dst=01:00:00:00:00:00/01:00:00:00:00:00 actions=output:2,pop_vlan,output:1,output:3,output:4
- */
-
- handleLocalVlanBcastOut(dpid, TABLE_2_LOCAL_FORWARD, segmentationId, localPort, ethPort, true);
-
- /*
- * Table(1) Rule #2
- * ----------------
- * Match: Match VLAN ID and L2 ::::FF:FF Flooding
- * Action: Flood to local and remote VLAN members
- * -------------------------------------------
- * Example: table=1,priority=16384,vlan_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
- * actions=output:10 (eth port),goto_table:2
- */
-
- //handleVlanFloodOut(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD,
- // segmentationId, ethPort, true);
- }
-
- private void programRemoteEgressVlanRules(Node node, Long dpid, String segmentationId,
- String attachedMac, long ethPort) {
- /*
- * Table(1) Rule #1
- * ----------------
- * Match: Destination MAC is local VM MAC and vlan id
- * Action: go to table 2
- * -------------------------------------------
- * Example: table=1,vlan_id=0x5,dl_dst=00:00:00:00:00:08 \
- * actions=goto_table:2
- */
-
- //handleVlanOut(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD,
- // segmentationId, ethPort, attachedMac, true);
-
- /*
- * Table(1) Rule #3
- * ----------------
- * Match: VLAN ID
- * Action: Go to table 2
- * -------------------------------------------
- * Example: table=1,priority=8192,vlan_id=0x5 actions=output:1,goto_table:2
- * table=110,priority=8192,dl_vlan=2001 actions=output:2
- */
-
- handleVlanMiss(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD, segmentationId, ethPort, true);
- }
-
- private void removeRemoteEgressVlanRules(Node node, Long dpid, String segmentationId,
- String attachedMac, long localPort, long ethPort) {
- /*
- * Table(1) Rule #1
- * ----------------
- * Match: Destination MAC is local VM MAC and vlan id
- * Action: go to table 2
- * -------------------------------------------
- * Example: table=1,vlan_id=0x5,dl_dst=00:00:00:00:00:08 \
- * actions=goto_table:2
- */
-
- //handleVlanOut(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD,
- // segmentationId, ethPort, attachedMac, false);
-
- /*
- * Table(1) Rule #2
- * ----------------
- * Match: Match VLAN ID and L2 ::::FF:FF Flooding
- * Action: Flood to local and remote VLAN members
- * -------------------------------------------
- * Example: table=1,priority=16384,vlan_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
- * actions=output:10 (eth port),goto_table:2
- * table=110, priority=16384,dl_vlan=2001,dl_dst=01:00:00:00:00:00/01:00:00:00:00:00 actions=output:2,pop_vlan,output:1,output:3,output:4
- */
-
- handleLocalVlanBcastOut(dpid, TABLE_2_LOCAL_FORWARD, segmentationId, localPort, ethPort, false);
- }
-
- private void removePerVlanRules(Node node, Long dpid, String segmentationId, long localPort, long ethPort) {
- /*
- * Table(2) Rule #3
- * ----------------
- * Match: Any Remaining Flows w/a VLAN ID
- * Action: Drop w/ a low priority
- * Example: table=2,priority=8192,vlan_id=0x5 actions=drop
- */
-
- //handleLocalVlanTableMiss(dpid, TABLE_2_LOCAL_FORWARD, segmentationId, false);
-
- /*
- * Table(0) Rule #2
- * ----------------
- * Match: Ingress port = physical interface, Vlan ID
- * Action: GOTO Local Table 2
- */
-
- handleVlanIn(dpid, TABLE_0_DEFAULT_INGRESS, TABLE_2_LOCAL_FORWARD, segmentationId, ethPort, false);
-
- /*
- * Table(1) Rule #2
- * ----------------
- * Match: Match VLAN ID and L2 ::::FF:FF Flooding
- * Action: Flood to local and remote VLAN members
- * -------------------------------------------
- * Example: table=1,priority=16384,vlan_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
- * actions=output:10 (eth port),goto_table:2
- * table=110, priority=16384,dl_vlan=2001,dl_dst=01:00:00:00:00:00/01:00:00:00:00:00 actions=output:2,pop_vlan,output:1,output:3,output:4
- */
-
- //handleLocalVlanBcastOut(dpid, TABLE_2_LOCAL_FORWARD, segmentationId, localPort, ethPort, false);
-
- /*
- * Table(1) Rule #2
- * ----------------
- * Match: Match VLAN ID and L2 ::::FF:FF Flooding
- * Action: Flood to local and remote VLAN members
- * -------------------------------------------
- * Example: table=1,priority=16384,vlan_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
- * actions=output:10 (eth port),goto_table:2
- */
-
- //handleVlanFloodOut(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD,
- // segmentationId, ethPort, false);
-
- /*
- * Table(1) Rule #3
- * ----------------
- * Match: VLAN ID
- * Action: Go to table 2
- * -------------------------------------------
- * Example: table=1,priority=8192,vlan_id=0x5 actions=output:1,goto_table:2
- * table=110,priority=8192,dl_vlan=2001 actions=output:2
- */
-
- handleVlanMiss(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD, segmentationId, ethPort, false);
- }
-
- private long getDpid(Node node) {
- long dpid = southbound.getDataPathId(node);
- if (dpid == 0) {
- LOG.warn("getDpid: dpid not found: {}", node);
- }
- return dpid;
- }
-
- private long getIntegrationBridgeOFDPID(Node node) {
- long dpid = 0L;
- if (southbound.getBridgeName(node).equals(configurationService.getIntegrationBridgeName())) {
- dpid = getDpid(node);
- }
- return dpid;
- }
-
- /**
- * Returns true is the network if of type GRE or VXLAN
- *
- * @param networkType The type of the network
- * @return returns true if the network is a tunnel
- */
- private boolean isTunnel(String networkType)
- {
- return (networkType.equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_GRE) || networkType.equalsIgnoreCase
- (NetworkHandler.NETWORK_TYPE_VXLAN));
- }
-
- /**
- * Returns true if the network is of type vlan.
- *
- * @param networkType The type of the network
- * @return returns true if the network is a vlan
- */
- private boolean isVlan(String networkType)
- {
- return networkType.equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VLAN);
- }
-
- private void programLocalRules(String networkType, String segmentationId, Node node,
- OvsdbTerminationPointAugmentation intf) {
- LOG.debug("programLocalRules: node: {}, intf: {}, networkType: {}, segmentationId: {}",
- node.getNodeId(), intf.getName(), networkType, segmentationId);
- try {
- long dpid = getIntegrationBridgeOFDPID(node);
- if (dpid == 0L) {
- LOG.debug("programLocalRules: Openflow Datapath-ID not set for the integration bridge in {}",
- node);
- return;
- }
-
- long localPort = southbound.getOFPort(intf);
- if (localPort == 0) {
- LOG.info("programLocalRules: could not find ofPort for Port {} on Node {}",
- intf.getName(), node.getNodeId());
- return;
- }
-
- String attachedMac = southbound.getInterfaceExternalIdsValue(intf, Constants.EXTERNAL_ID_VM_MAC);
- if (attachedMac == null) {
- LOG.warn("No AttachedMac seen in {}", intf);
- return;
- }
-
- /* Program local rules based on network type */
- if (isVlan(networkType)) {
- LOG.debug("Program local vlan rules for interface {}", intf.getName());
- programLocalVlanRules(node, dpid, segmentationId, attachedMac, localPort);
- }
- if ((isTunnel(networkType) || isVlan(networkType))) {
- programLocalSecurityGroupRules(attachedMac, node, intf, dpid, localPort, segmentationId, false, true);
- }
- if (isTunnel(networkType)) {
- LOG.debug("Program local bridge rules for interface {}, "
- + "dpid: {}, segmentationId: {}, attachedMac: {}, localPort: {}",
- intf.getName(), dpid, segmentationId, attachedMac, localPort);
- programLocalBridgeRules(node, dpid, segmentationId, attachedMac, localPort);
- }
- } catch (Exception e) {
- LOG.error("Exception in programming Local Rules for {} on {}", intf, node, e);
- }
- }
-
- private void removeLocalRules(String networkType, String segmentationId, Node node,
- OvsdbTerminationPointAugmentation intf, boolean isMigratedPort) {
- LOG.debug("removeLocalRules: node: {}, intf: {}, networkType: {}, segmentationId: {}",
- node.getNodeId(), intf.getName(), networkType, segmentationId);
- try {
- long dpid = getIntegrationBridgeOFDPID(node);
- if (dpid == 0L) {
- LOG.debug("removeLocalRules: Openflow Datapath-ID not set for the integration bridge in {}", node);
- return;
- }
-
- long localPort = southbound.getOFPort(intf);
- if (localPort == 0) {
- LOG.info("removeLocalRules: could not find ofPort");
- return;
- }
-
- String attachedMac = southbound.getInterfaceExternalIdsValue(intf, Constants.EXTERNAL_ID_VM_MAC);
- if (attachedMac == null) {
- LOG.warn("No AttachedMac seen in {}", intf);
- return;
- }
-
- /* Program local rules based on network type */
- if (isVlan(networkType)) {
- LOG.debug("Remove local vlan rules for interface {}", intf.getName());
- removeLocalVlanRules(node, dpid, segmentationId, attachedMac, localPort);
- } else if (isTunnel(networkType)) {
- LOG.debug("Remove local bridge rules for interface {}", intf.getName());
- removeLocalBridgeRules(node, dpid, segmentationId, attachedMac, localPort, isMigratedPort);
- }
- if (isTunnel(networkType) || isVlan(networkType)) {
- programLocalSecurityGroupRules(attachedMac, node, intf, dpid, localPort, segmentationId, isMigratedPort, false);
- }
- } catch (Exception e) {
- LOG.error("Exception in removing Local Rules for {} on {}", intf, node, e);
- }
- }
-
- private void programTunnelRules (String tunnelType, String segmentationId, InetAddress dst, Node node,
- OvsdbTerminationPointAugmentation intf, boolean local) {
- LOG.debug("programTunnelRules: node: {}, intf: {}, local: {}, tunnelType: {}, "
- + "segmentationId: {}, dstAddr: {}",
- node.getNodeId(), intf.getName(), local, tunnelType, segmentationId, dst.getHostAddress());
- try {
- long dpid = getIntegrationBridgeOFDPID(node);
- if (dpid == 0L) {
- LOG.debug("programTunnelRules: Openflow Datapath-ID not set for the integration bridge in {}", node);
- return;
- }
-
- long localPort = southbound.getOFPort(intf);
- if (localPort == 0) {
- LOG.info("programTunnelRules: could not find ofPort for Port {} on Node{}", intf.getName(), node.getNodeId());
- return;
- }
-
- String attachedMac = southbound.getInterfaceExternalIdsValue(intf, Constants.EXTERNAL_ID_VM_MAC);
- if (attachedMac == null) {
- LOG.warn("programTunnelRules: No AttachedMac seen in {}", intf);
- return;
- }
-
- OvsdbTerminationPointAugmentation tunnelPort= southbound.getTerminationPointOfBridge(node, getTunnelName(tunnelType, dst));
- if (tunnelPort != null){
- long tunnelOFPort = southbound.getOFPort(tunnelPort);
- if (tunnelOFPort == 0) {
- LOG.error("programTunnelRules: Could not Identify Tunnel port {} -> OF ({}) on {}",
- tunnelPort.getName(), tunnelOFPort, node);
- return;
- }
- LOG.debug("programTunnelRules: Identified Tunnel port {} -> OF ({}) on {}",
- tunnelPort.getName(), tunnelOFPort, node);
-
- if (!local) {
- LOG.trace("programTunnelRules: program remote egress tunnel rules: node {}, intf {}",
- node.getNodeId().getValue(), intf.getName());
- programRemoteEgressTunnelBridgeRules(node, dpid, segmentationId, attachedMac,
- tunnelOFPort, localPort);
- } else {
- LOG.trace("programTunnelRules: program local ingress tunnel rules: node {}, intf {}",
- node.getNodeId().getValue(), intf.getName());
- programLocalIngressTunnelBridgeRules(node, dpid, segmentationId, attachedMac,
- tunnelOFPort, localPort);
- }
- }
- } catch (Exception e) {
- LOG.warn("Failed to program tunnel rules, node {}, intf {}", node, intf, e);
- }
- }
-
- private void removeTunnelRules (String tunnelType, String segmentationId, InetAddress dst, Node node,
- OvsdbTerminationPointAugmentation intf,
- boolean local, boolean isLastInstanceOnNode, boolean isMigratedPort) {
- LOG.debug("removeTunnelRules: node: {}, intf: {}, local: {}, tunnelType: {}, "
- + "segmentationId: {}, dstAddr: {}, isLastinstanceOnNode: {}",
- node.getNodeId(), intf.getName(), local, tunnelType, segmentationId, dst, isLastInstanceOnNode);
- try {
- long dpid = getIntegrationBridgeOFDPID(node);
- if (dpid == 0L) {
- LOG.debug("removeTunnelRules: Openflow Datapath-ID not set for the integration bridge in {}", node);
- return;
- }
-
- long localPort = southbound.getOFPort(intf);
- if (localPort == 0) {
- LOG.info("removeTunnelRules: could not find ofPort");
- return;
- }
-
- String attachedMac = southbound.getInterfaceExternalIdsValue(intf, Constants.EXTERNAL_ID_VM_MAC);
- if (attachedMac == null) {
- LOG.error("removeTunnelRules: No AttachedMac seen in {}", intf);
- return;
- }
-
- List<OvsdbTerminationPointAugmentation> intfs = southbound.getTerminationPointsOfBridge(node);
- for (OvsdbTerminationPointAugmentation tunIntf : intfs) {
- if (tunIntf.getName().equals(getTunnelName(tunnelType, dst))) {
- long tunnelOFPort = southbound.getOFPort(tunIntf);
- if (tunnelOFPort == 0) {
- LOG.error("Could not Identify Tunnel port {} -> OF ({}) on {}",
- tunIntf.getName(), tunnelOFPort, node);
- return;
- }
- LOG.debug("Identified Tunnel port {} -> OF ({}) on {}",
- tunIntf.getName(), tunnelOFPort, node);
-
- if (!local && !isMigratedPort) {
- removeRemoteEgressTunnelBridgeRules(node, dpid, segmentationId, attachedMac,
- tunnelOFPort, localPort);
- }
- if (local && isLastInstanceOnNode) {
- removePerTunnelRules(node, dpid, segmentationId, tunnelOFPort);
- }
- return;
- }
- }
- } catch (Exception e) {
- LOG.error("Failed to remove tunnel rules, node {}, intf {}", node, intf, e);
- }
- }
-
- private void programVlanRules (NeutronNetwork network, Node node, OvsdbTerminationPointAugmentation intf) {
- LOG.debug("programVlanRules: node: {}, network: {}, intf: {}",
- node.getNodeId(), network.getNetworkUUID(), intf.getName());
- long dpid = getIntegrationBridgeOFDPID(node);
- if (dpid == 0L) {
- LOG.debug("programVlanRules: Openflow Datapath-ID not set for the integration bridge in {}", node);
- return;
- }
-
- long localPort = southbound.getOFPort(intf);
- if (localPort == 0) {
- LOG.debug("programVlanRules: could not find ofPort for {}", intf.getName());
- return;
- }
-
- String attachedMac = southbound.getInterfaceExternalIdsValue(intf, Constants.EXTERNAL_ID_VM_MAC);
- if (attachedMac == null) {
- LOG.debug("programVlanRules: No AttachedMac seen in {}", intf);
- return;
- }
-
- String phyIfName =
- bridgeConfigurationManager.getPhysicalInterfaceName(node, network.getProviderPhysicalNetwork());
- long ethOFPort = southbound.getOFPort(node, phyIfName);
- if (ethOFPort == 0) {
- LOG.warn("programVlanRules: could not find ofPort for physical port {}", phyIfName);
- return;
- }
- LOG.debug("programVlanRules: Identified eth port {} -> ofPort ({}) on {}",
- phyIfName, ethOFPort, node);
- // TODO: add logic to only add rule on remote nodes
- programRemoteEgressVlanRules(node, dpid, network.getProviderSegmentationID(),
- attachedMac, ethOFPort);
- programLocalIngressVlanRules(node, dpid, network.getProviderSegmentationID(),
- attachedMac, localPort, ethOFPort);
- }
-
- private void removeVlanRules (NeutronNetwork network, Node node, OvsdbTerminationPointAugmentation intf,
- boolean isLastInstanceOnNode) {
- LOG.debug("removeVlanRules: node: {}, network: {}, intf: {}, isLastInstanceOnNode",
- node.getNodeId(), network.getNetworkUUID(), intf.getName(), isLastInstanceOnNode);
- long dpid = getIntegrationBridgeOFDPID(node);
- if (dpid == 0L) {
- LOG.debug("removeVlanRules: Openflow Datapath-ID not set for the integration bridge in {}", node);
- return;
- }
-
- long localPort = southbound.getOFPort(intf);
- if (localPort == 0) {
- LOG.debug("removeVlanRules: programVlanRules: could not find ofPort for {}", intf.getName());
- return;
- }
-
- String attachedMac = southbound.getInterfaceExternalIdsValue(intf, Constants.EXTERNAL_ID_VM_MAC);
- if (attachedMac == null) {
- LOG.debug("removeVlanRules: No AttachedMac seen in {}", intf);
- return;
- }
-
- String phyIfName =
- bridgeConfigurationManager.getPhysicalInterfaceName(node, network.getProviderPhysicalNetwork());
- long ethOFPort = southbound.getOFPort(node, phyIfName);
- if (ethOFPort == 0) {
- LOG.warn("removeVlanRules: could not find ofPort for physical port {}", phyIfName);
- return;
- }
- LOG.debug("removeVlanRules: Identified eth port {} -> ofPort ({}) on {}",
- phyIfName, ethOFPort, node);
-
- removeRemoteEgressVlanRules(node, dpid, network.getProviderSegmentationID(),
- attachedMac, localPort, ethOFPort);
- if (isLastInstanceOnNode) {
- removePerVlanRules(node, dpid, network.getProviderSegmentationID(), localPort, ethOFPort);
- }
- }
-
- private void programLocalSecurityGroupRules(String attachedMac, Node node, OvsdbTerminationPointAugmentation intf,
- Long dpid,long localPort, String segmentationId, boolean isMigratedPort,
- boolean write) {
-
- LOG.debug("programLocalRules: Program fixed security group rules for interface {}", intf.getName());
- boolean isPortSecurityEnabled = securityServicesManager.isPortSecurityEnabled(intf);
- if (!isPortSecurityEnabled) {
- LOG.info("Port security is not enabled" + intf);
- return;
- }
- NeutronPort dhcpPort = securityServicesManager.getDhcpServerPort(intf);
- List<Neutron_IPs> srcAddressList = null;
- if (null != dhcpPort) {
- srcAddressList = securityServicesManager.getIpAddressList(intf);
- if (null == srcAddressList) {
- LOG.warn("programLocalRules: No Ip address assigned {}", intf);
- return;
- }
- ingressAclProvider.programFixedSecurityGroup(dpid, segmentationId, dhcpPort.getMacAddress(), localPort,
- attachedMac, write);
- egressAclProvider.programFixedSecurityGroup(dpid, segmentationId, attachedMac, localPort,
- srcAddressList, write);
- /* If the network type is tunnel based (VXLAN/GRRE/etc) with Neutron Port Security ACLs */
- /* TODO SB_MIGRATION */
-
- LOG.debug("Neutron port has a Port Security Group");
- // Retrieve the security group from the Neutron Port and apply the rules
- List<NeutronSecurityGroup> securityGroupListInPort = securityServicesManager
- .getSecurityGroupInPortList(intf);
- String neutronPortId = southbound.getInterfaceExternalIdsValue(intf,
- Constants.EXTERNAL_ID_INTERFACE_ID);
- org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId nodeId = node.getNodeId();
- for (NeutronSecurityGroup securityGroupInPort:securityGroupListInPort) {
- ingressAclProvider.programPortSecurityGroup(dpid, segmentationId, attachedMac, localPort,
- securityGroupInPort, neutronPortId, nodeId, write);
- egressAclProvider.programPortSecurityGroup(dpid, segmentationId, attachedMac, localPort,
- securityGroupInPort, neutronPortId, nodeId, write);
- if (write) {
- securityGroupCacheManger.portAdded(securityGroupInPort.getSecurityGroupUUID(), neutronPortId);
- } else {
- if(!isMigratedPort) {
- securityGroupCacheManger.portRemoved(securityGroupInPort.getSecurityGroupUUID(), neutronPortId);
- }
- }
- }
- } else {
- LOG.warn("programLocalRules: No DCHP port seen in network of {}", intf);
- }
- }
-
- /*
- * The function is for the new compute node joining the existing network.
- * When a new VM is instantiated in the new compute node, neutron port add
- * event is generated. This event is processed only for that node. So,
- * loop through all the ports of the same network and install unicast mac
- * flow for the VM's created on the TEP of the destination node in src node.
- * This function will be executed even for any new VM creation in an existing
- * network. If a cache is maintained to optimize the below flow addition, it will
- * work only for one unstack and restack. For the next unstack and restack,
- * it will not work since the cache would have been already deleted.
- */
- private void programTunnelRulesInNewNode(NeutronNetwork network,
- String networkType, String segmentationId,
- InetAddress src, InetAddress dst,
- Node srcBridgeNode, Node dstBridgeNode,
- OvsdbTerminationPointAugmentation intf){
- LOG.debug("programTunnelRulesInNewNode: network {} networkType {} segId {} src {} dst {} srcBridgeNode {} dstBridgeNode {} intf {}",
- network.getNetworkName(), networkType, segmentationId, src.getHostAddress(),
- dst.getHostAddress(), srcBridgeNode, dstBridgeNode, intf);
- try {
- long localPort = southbound.getOFPort(intf);
- if (localPort != 0)
- {
- LOG.debug("Interface update details {}", intf);
-
- /*
- * When a network is added and the TEP destination is not present in a
- * node C1, tunnelin and broadcast rules will not be programmed, since
- * OF port is not created. So, when a new node C2 joins and create a new
- * VM, the tunnelin and broadcast rule will not be present in C1.
- * So, handling it in the case below to make ping work.
- */
- if (securityServicesManager.getNeutronPortFromDhcpIntf(intf) == null){
- programTunnelRules(networkType, segmentationId, src, dstBridgeNode, intf, true);
- }
-
- /*
- * FIX for 4208 - loop through all the ports and add the VM's
- * unicast mac rule of the destination node in the source node.
- * When a new node is added, it needs to configure the VM unicast mac
- * flow rules which were created before it was joined to an existing
- * network.
- */
- List<OvsdbTerminationPointAugmentation> ports = southbound.getTerminationPointsOfBridge(dstBridgeNode);
- for (OvsdbTerminationPointAugmentation port : ports) {
-
- NeutronNetwork neutronNetwork = tenantNetworkManager.getTenantNetwork(port);
- if (neutronNetwork != null) {
- String netType = neutronNetwork.getProviderNetworkType();
- String segId = neutronNetwork.getProviderSegmentationID();
- InetAddress dstAddr = configurationService.getTunnelEndPoint(dstBridgeNode);
-
- if (segId != null && netType != null && dstAddr != null) {
- programTunnelRules(netType, segId, dstAddr, srcBridgeNode, port, false);
- }
- }
- }
- }
- } catch (Exception e) {
- LOG.error("Exception during handlingNeutron network add", e);
- }
- }
-
- private boolean bridgeHasVmPort(Node bridgeNode) {
- String intBridgeName = configurationService.getIntegrationBridgeName();
- String extBridgeName = configurationService.getExternalBridgeName();
- List<TerminationPoint> terminationPoints = bridgeNode.getTerminationPoint();
- if (terminationPoints == null) return false;
-
- for (TerminationPoint tp : terminationPoints) {
- String tpName = tp.getTpId().getValue();
- if (tpName != null && !tpName.equals(intBridgeName) && !tpName.equals(extBridgeName)) {
- OvsdbTerminationPointAugmentation tpAug = tp.getAugmentation(OvsdbTerminationPointAugmentation.class);
- if (tpAug != null && southbound.getOFPort(tpAug) != 0) {
- return true;
- }
- }
- }
-
- return false;
- }
-
- @Override
- public boolean handleInterfaceUpdate(NeutronNetwork network, Node srcNode, OvsdbTerminationPointAugmentation intf) {
- LOG.debug("handleInterfaceUpdate: network: {} srcNode: {}, intf: {}",
- network.getProviderSegmentationID(), srcNode.getNodeId(), intf.getName());
- Preconditions.checkNotNull(nodeCacheManager);
-
- org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId srcNodeId =
- srcNode.getNodeId();
- Map<org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId,Node> nodes =
- nodeCacheManager.getOvsdbNodes();
-
- nodes.remove(southbound.extractBridgeOvsdbNodeId(srcNode));
- String networkType = network.getProviderNetworkType();
- String segmentationId = network.getProviderSegmentationID();
- Node srcBridgeNode = southbound.getBridgeNode(srcNode, configurationService.getIntegrationBridgeName());
-
- programLocalRules(networkType, network.getProviderSegmentationID(), srcBridgeNode, intf);
-
- if (isVlan(networkType)) {
- programVlanRules(network, srcNode, intf);
- } else if (isTunnel(networkType)){
-
- boolean sourceTunnelStatus = false;
- boolean destTunnelStatus = false;
- boolean isSrcinNw = tenantNetworkManager.isTenantNetworkPresentInNode(srcBridgeNode, segmentationId);
- for (Node dstNode : nodes.values()) {
- InetAddress src = configurationService.getTunnelEndPoint(srcNode);
- InetAddress dst = configurationService.getTunnelEndPoint(dstNode);
- if ((src != null) && (dst != null)) {
- sourceTunnelStatus = addTunnelPort(srcBridgeNode, networkType, src, dst);
-
- Node dstBridgeNode = southbound.getBridgeNode(dstNode,
- configurationService.getIntegrationBridgeName());
-
- if (dstBridgeNode != null) {
- destTunnelStatus = addTunnelPort(dstBridgeNode, networkType, dst, src);
- }
- if (sourceTunnelStatus && destTunnelStatus) {
- LOG.debug("Created Source and destination TunnelPorts :{}, {}", src, dst);
- } else {
- LOG.debug("Source and destination TunnelPort status :{}, {}", sourceTunnelStatus, destTunnelStatus);
- }
- if (sourceTunnelStatus) {
- boolean isDestinNw = tenantNetworkManager.isTenantNetworkPresentInNode(dstBridgeNode, segmentationId);
- //Check whether the network is present in src & dst node
- //If only present , add vxlan ports in TunnelRules for both nodes (bug# 5614)
- if (isSrcinNw && isDestinNw) {
- programTunnelRules(networkType, segmentationId, dst, srcBridgeNode, intf, true);
- programTunnelRules(networkType, segmentationId, src, dstBridgeNode, intf, true);
- } else if (configurationService.isRemoteMacLearnEnabled()) {
- //Even if to learn remote MAC, a network doesn't exist in a node,
- //a vxlan port is added in TunnelRules for both nodes.(bug# 6474)
- programTunnelRules(networkType, segmentationId, dst, srcBridgeNode, intf, true);
- }
- }
- if (destTunnelStatus) {
- programTunnelRules(networkType, segmentationId, src, dstBridgeNode, intf, false);
-
- if (srcNodeId != null && intBridgesWithoutVmPorts.contains(srcNodeId)) {
- programTunnelRulesInNewNode(network, networkType, segmentationId, src, dst,
- srcBridgeNode, dstBridgeNode, intf);
- intBridgesWithoutVmPorts.remove(srcNodeId);
- }
- }
- } else {
- LOG.warn("Tunnel end-point configuration missing. Please configure it in OpenVSwitch Table. "
- + "Check source {} or destination {}",
- src != null ? src.getHostAddress() : "null",
- dst != null ? dst.getHostAddress() : "null");
- }
- }
- }
-
- if (srcNodeId != null && !bridgeHasVmPort(srcNode)) {
- intBridgesWithoutVmPorts.add(srcNodeId);
- }
-
- return true;
- }
-
- private void triggerInterfaceUpdates(Node node) {
- LOG.debug("enter triggerInterfaceUpdates for : {}", node.getNodeId());
- List<OvsdbTerminationPointAugmentation> ports = southbound.extractTerminationPointAugmentations(node);
- if (ports != null && !ports.isEmpty()) {
- for (OvsdbTerminationPointAugmentation port : ports) {
- NeutronNetwork neutronNetwork = tenantNetworkManager.getTenantNetwork(port);
- if (neutronNetwork != null) {
- LOG.warn("Trigger Interface update for {}", port);
- handleInterfaceUpdate(neutronNetwork, node, port);
- }
- }
- } else {
- LOG.warn("triggerInterfaceUpdates: tps are null");
- }
- LOG.debug("exit triggerInterfaceUpdates for {}", node.getNodeId());
- }
-
- @Override
- public boolean handleInterfaceDelete(String tunnelType, NeutronNetwork network, Node srcNode,
- OvsdbTerminationPointAugmentation intf, boolean isLastInstanceOnNode, boolean isMigratedPort) {
- Map<org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId,Node> nodes =
- nodeCacheManager.getOvsdbNodes();
- nodes.remove(southbound.extractBridgeOvsdbNodeId(srcNode));
-
- LOG.info("Delete intf " + intf.getName() + " isLastInstanceOnNode " + isLastInstanceOnNode);
- String segmentationId = network.getProviderSegmentationID();
- List<String> phyIfName = bridgeConfigurationManager.getAllPhysicalInterfaceNames(srcNode);
- if (southbound.isTunnel(intf)) {
- // Delete tunnel port
- try {
- InetAddress src = InetAddress.getByName(
- southbound.getOptionsValue(intf.getOptions(), "local_ip"));
- InetAddress dst = InetAddress.getByName(
- southbound.getOptionsValue(intf.getOptions(), "remote_ip"));
- deleteTunnelPort(srcNode,
- MdsalHelper.createOvsdbInterfaceType(intf.getInterfaceType()),
- src, dst);
- } catch (Exception e) {
- LOG.error("handleInterfaceDelete: failed to delete tunnel port", e);
- }
- } else if (phyIfName.contains(intf.getName())) {
- deletePhysicalPort(srcNode, intf.getName());
- } else {
- // delete all other interfaces
- removeLocalRules(network.getProviderNetworkType(), segmentationId,
- srcNode, intf, isMigratedPort);
-
- if (isVlan(network.getProviderNetworkType())) {
- removeVlanRules(network, srcNode, intf, isLastInstanceOnNode);
- } else if (isTunnel(network.getProviderNetworkType())) {
-
- Node srcBridgeNode = southbound.getBridgeNode(srcNode, configurationService.getIntegrationBridgeName());
- for (Node dstNode : nodes.values()) {
- InetAddress src = configurationService.getTunnelEndPoint(srcNode);
- InetAddress dst = configurationService.getTunnelEndPoint(dstNode);
- if ((src != null) && (dst != null)) {
- LOG.info("Remove tunnel rules for interface "
- + intf.getName() + " on srcNode " + srcNode.getNodeId().getValue());
- removeTunnelRules(tunnelType, segmentationId,
- dst, srcNode, intf, true, isLastInstanceOnNode, isMigratedPort);
- Node dstBridgeNode = southbound.getBridgeNode(dstNode, Constants.INTEGRATION_BRIDGE);
- //While removing last instance , check whether the network present in src node
- //If network is not present in src node AND REMOTE MAC LEARNING IS not enabled,
- //remove the vxlan port of src from dst node in TunnelRules(Bug# 5614)
- boolean isSrcinNw = tenantNetworkManager.isTenantNetworkPresentInNode(srcBridgeNode, segmentationId);
- if (dstBridgeNode != null) {
- //To learn remote MAC, also to make the flooding the node by which a network
- //doesn't exist in a node, TunnelRules leaves it.
- if (!isSrcinNw && !configurationService.isRemoteMacLearnEnabled()) {
- removeTunnelRules(tunnelType, segmentationId,
- src, dstBridgeNode, intf, true, isLastInstanceOnNode, isMigratedPort);
- }
- LOG.info("Remove tunnel rules for interface "
- + intf.getName() + " on dstNode " + dstNode.getNodeId().getValue());
- removeTunnelRules(tunnelType, segmentationId, src,
- dstBridgeNode, intf, false, isLastInstanceOnNode, isMigratedPort);
- }
- } else {
- LOG.warn("Tunnel end-point configuration missing. Please configure it in "
- + "OpenVSwitch Table. "
- + "Check source {} or destination {}",
- src != null ? src.getHostAddress() : "null",
- dst != null ? dst.getHostAddress() : "null");
- }
- }
- }
- }
- return true;
- }
-
- @Override
- public void initializeFlowRules(Node node) {
- initializeFlowRules(node, configurationService.getIntegrationBridgeName());
- initializeFlowRules(node, configurationService.getExternalBridgeName());
- triggerInterfaceUpdates(node);
- }
-
- private void initializeFlowRules(Node node, String bridgeName) {
- Long dpid = southbound.getDataPathId(node);
- if (bridgeName.equals(configurationService.getIntegrationBridgeName())) {
- resubmitAclLearnProvider.programResubmit(dpid);
- }
- String datapathId = southbound.getDatapathId(node);
- LOG.trace("initializeFlowRules: bridgeName: {}, datapathId: {} ",
- bridgeName, datapathId);
- String brExt = null;
-
- if (dpid == 0L) {
- LOG.debug("Openflow Datapath-ID not set for the integration bridge in {}", node);
- return;
- }
-
- /*
- * Table(0) Rule #1
- * ----------------
- * Match: LLDP (0x88CCL)
- * Action: Packet_In to Controller Reserved Port
- */
-
- writeLLDPRule(dpid);
-
- /*
- * Table(105) Rule #1
- * -------------------
- * Match: reg0=0x2
- * Action: learn and goto next table
- */
-
- writeL2ForwardingLearnRule(dpid);
-
- if (bridgeName.equals(configurationService.getIntegrationBridgeName()) &&
- NetvirtProvidersProvider.getTableOffset() != 0) {
- classifierProvider.programGotoTable(dpid,true);
- }
-
- if (configurationService.isL3MultipleExternalNetworkEnabled()) {
- brExt = bridgeConfigurationManager.getMultipleExternalBridge(node);
- }
- if (bridgeName.equals(configurationService.getExternalBridgeName()) ||
- (bridgeName.equals(brExt))) {
- writeNormalRule(dpid);
- }
- }
-
- /*
- * Create an LLDP Flow Rule to encapsulate into
- * a packet_in that is sent to the controller
- * for topology handling.
- * Match: Ethertype 0x88CCL
- * Action: Punt to Controller in a Packet_In msg
- */
-
- private void writeLLDPRule(Long dpidLong) {
- classifierProvider.programLLDPPuntRule(dpidLong);
- }
-
- /*
- * Create an L2Forwarding mac learn Flow Rule
- * Match: reg0 = ClassifierService.REG_VALUE_FROM_REMOTE
- * Action: learn and goto next table
- */
-
- private void writeL2ForwardingLearnRule(Long dpidLong) {
- if (configurationService.isRemoteMacLearnEnabled()) {
- l2ForwardingLearnProvider.programL2ForwardingLearnRule(dpidLong);
- }
- }
-
- /*
- * Create a NORMAL Table Miss Flow Rule
- * Match: any
- * Action: forward to NORMAL pipeline
- */
-
- private void writeNormalRule(Long dpidLong) {
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = "NORMAL";
- FlowUtils.initFlowBuilder(flowBuilder, flowName, Service.CLASSIFIER.getTable()).setPriority(0);
- MatchBuilder matchBuilder = new MatchBuilder();
- flowBuilder.setMatch(matchBuilder.build());
-
- // Create the OF Actions and Instructions
- InstructionBuilder ib = new InstructionBuilder();
- InstructionsBuilder isb = new InstructionsBuilder();
-
- // Instructions List Stores Individual Instructions
- List<Instruction> instructions = new ArrayList<>();
-
- // Call the InstructionBuilder Methods Containing Actions
- InstructionUtils.createNormalInstructions(FlowUtils.getNodeName(dpidLong), ib);
- ib.setOrder(0);
- ib.setKey(new InstructionKey(0));
- instructions.add(ib.build());
-
- // Add InstructionBuilder to the Instruction(s)Builder List
- isb.setInstruction(instructions);
-
- // Add InstructionsBuilder to FlowBuilder
- flowBuilder.setInstructions(isb.build());
- writeFlow(flowBuilder, nodeBuilder);
- }
-
- /*
- * (Table:0) Ingress Tunnel Traffic
- * Match: OpenFlow InPort and Tunnel ID
- * Action: GOTO Local Table (10)
- * table=0,tun_id=0x5,in_port=10, actions=goto_table:2
- */
-
- private void handleTunnelIn(Long dpidLong, Short writeTable,
- Short goToTableId, String segmentationId,
- Long ofPort, boolean write) {
- classifierProvider.programTunnelIn(dpidLong, segmentationId, ofPort, write);
- }
-
- /*
- * (Table:0) Ingress VLAN Traffic
- * Match: OpenFlow InPort and vlan ID
- * Action: GOTO Local Table (20)
- * table=0,vlan_id=0x5,in_port=10, actions=goto_table:2
- */
-
- private void handleVlanIn(Long dpidLong, Short writeTable, Short goToTableId,
- String segmentationId, Long ethPort, boolean write) {
- classifierProvider.programVlanIn(dpidLong, segmentationId, ethPort, write);
- }
-
- /*
- * (Table:0) Egress VM Traffic Towards TEP
- * Match: Destination Ethernet Addr and OpenFlow InPort
- * Instruction: Set TunnelID and GOTO Table Tunnel Table (n)
- * table=0,in_port=2,dl_src=00:00:00:00:00:01 \
- * actions=set_field:5->tun_id,goto_table=1"
- */
-
- private void handleLocalInPort(Long dpidLong, Short writeTable, Short goToTableId,
- String segmentationId, Long inPort, String attachedMac,
- boolean write) {
- classifierProvider.programLocalInPort(dpidLong, segmentationId, inPort, attachedMac, write);
- }
-
- /*
- * (Table:0) Egress VM Traffic Towards TEP
- * Match: Source Ethernet Addr and OpenFlow InPort
- * Instruction: Set VLANID and GOTO Table Egress (n)
- * table=0,in_port=2,dl_src=00:00:00:00:00:01 \
- * actions=push_vlan, set_field:5->vlan_id,goto_table=1"
- */
-
- private void handleLocalInPortSetVlan(Long dpidLong, Short writeTable,
- Short goToTableId, String segmentationId,
- Long inPort, String attachedMac,
- boolean write) {
- classifierProvider.programLocalInPortSetVlan(dpidLong, segmentationId, inPort, attachedMac, write);
- }
-
- /*
- * (Table:0) Drop frames source from a VM that do not
- * match the associated MAC address of the local VM.
- * Match: Low priority anything not matching the VM SMAC
- * Instruction: Drop
- * table=0,priority=16384,in_port=1 actions=drop"
- */
-
- private void handleDropSrcIface(Long dpidLong, Long inPort, boolean write) {
- classifierProvider.programDropSrcIface(dpidLong, inPort, write);
- }
-
- /*
- * (Table:1) Egress Tunnel Traffic
- * Match: Destination Ethernet Addr and Local InPort
- * Instruction: Set TunnelID and GOTO Table Tunnel Table (n)
- * table=1,tun_id=0x5,dl_dst=00:00:00:00:00:08 \
- * actions=output:10,goto_table:2"
- */
- private void handleTunnelOut(Long dpidLong, Short writeTable,
- Short goToTableId, String segmentationId,
- Long OFPortOut, String attachedMac,
- boolean write) {
- l2ForwardingProvider.programTunnelOut(dpidLong, segmentationId, OFPortOut, attachedMac, write);
- }
-
- /*
- * (Table:1) Egress VLAN Traffic
- * Match: Destination Ethernet Addr and VLAN id
- * Instruction: GOTO Table Table 2
- * table=1,vlan_id=0x5,dl_dst=00:00:00:00:00:08 \
- * actions= goto_table:2"
- */
- // TODO This method is referenced from commented code above (which needs to be checked)
- @SuppressWarnings("unused")
- private void handleVlanOut(Long dpidLong, Short writeTable,
- Short goToTableId, String segmentationId,
- Long ethPort, String attachedMac, boolean write) {
- l2ForwardingProvider.programVlanOut(dpidLong, segmentationId, ethPort, attachedMac, write);
- }
-
- /*
- * (Table:1) Egress Tunnel Traffic
- * Match: Destination Ethernet Addr and Local InPort
- * Instruction: Set TunnelID and GOTO Table Tunnel Table (n)
- * table=1,priority=16384,tun_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
- * actions=output:10,output:11,goto_table:2
- */
-
- private void handleTunnelFloodOut(Long dpidLong, Short writeTable,
- Short localTable, String segmentationId,
- Long OFPortOut, boolean write) {
- l2ForwardingProvider.programTunnelFloodOut(dpidLong, segmentationId, OFPortOut, write);
- }
-
- /*
- * (Table:110) Flooding local unknown unicast Traffic
- * Match: TunnelID and Unknown unicast and Local InPort
- * Instruction: Set TunnelID and GOTO Table Tunnel Table (n)
- * table=110,priority=16380,tun_id=0x5,dl_dst=00:00:00:00:00:00/01:00:00:00:00:00 \
- * actions=output:10,output:11
- */
-
- private void handleTunnelUnknownUcastFloodOut(Long dpidLong, Short writeTable,
- Short localTable, String segmentationId,
- Long OFPortOut, boolean write) {
- if (configurationService.isRemoteMacLearnEnabled()) {
- l2ForwardingProvider.programTunnelUnknownUcastFloodOut(dpidLong, segmentationId, OFPortOut, write);
- }
- }
-
- /*
- * (Table:1) Egress VLAN Traffic
- * Match: Destination Ethernet Addr and VLAN id
- * Instruction: GOTO table 2 and Output port eth interface
- * Example: table=1,priority=16384,vlan_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
- * actions=output:eth1,goto_table:2
- */
- // TODO This method is referenced from commented code above (which needs to be checked)
- @SuppressWarnings("unused")
- private void handleVlanFloodOut(Long dpidLong, Short writeTable,
- Short localTable, String segmentationId,
- Long localPort, Long ethPort, boolean write) {
- //l2ForwardingProvider.programVlanFloodOut(dpidLong, segmentationId, localPort, ethPort, write);
- }
-
- /*
- * (Table:1) Table Drain w/ Catch All
- * Match: Vlan ID
- * Action: Output port eth interface
- * table=1,priority=8192,vlan_id=0x5 actions= output port:eth1
- * table=110,priority=8192,dl_vlan=2001 actions=output:2
- */
-
- private void handleVlanMiss(Long dpidLong, Short writeTable,
- Short goToTableId, String segmentationId,
- Long ethPort, boolean write) {
- l2ForwardingProvider.programVlanMiss(dpidLong, segmentationId, ethPort, write);
- }
-
- /*
- * (Table:1) Local Broadcast Flood
- * Match: Tunnel ID and dMAC
- * Action: Output Port
- * table=2,tun_id=0x5,dl_dst=00:00:00:00:00:01 actions=output:2
- */
-
- private void handleLocalUcastOut(Long dpidLong, Short writeTable,
- String segmentationId, Long localPort,
- String attachedMac, boolean write) {
- l2ForwardingProvider.programLocalUcastOut(dpidLong, segmentationId, localPort, attachedMac, write);
- }
-
- /*
- * (Table:2) Local VLAN unicast
- * Match: VLAN ID and dMAC
- * Action: Output Port
- * table=2,vlan_id=0x5,dl_dst=00:00:00:00:00:01 actions=output:2
- */
-
- private void handleLocalVlanUcastOut(Long dpidLong, Short writeTable,
- String segmentationId, Long localPort,
- String attachedMac, boolean write) {
- l2ForwardingProvider.programLocalVlanUcastOut(dpidLong, segmentationId, localPort, attachedMac, write);
- }
-
- /*
- * (Table:2) Local Broadcast Flood
- * Match: Tunnel ID and dMAC (::::FF:FF)
- * table=2,priority=16384,tun_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
- * actions=output:2,3,4,5
- */
-
- private void handleLocalBcastOut(Long dpidLong, Short writeTable,
- String segmentationId, Long localPort,
- boolean write) {
- l2ForwardingProvider.programLocalBcastOut(dpidLong, segmentationId, localPort, write);
- }
-
- /*
- * (Table:2) Local VLAN Broadcast Flood
- * Match: vlan ID and dMAC (::::FF:FF)
- * table=2,priority=16384,vlan_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
- * actions=strip_vlan, output:2,3,4,5
- * table=110,dl_vlan=2001,dl_dst=01:00:00:00:00:00/01:00:00:00:00:00 actions=output:2,pop_vlan,output:1,output:3,output:4
- */
-
- private void handleLocalVlanBcastOut(Long dpidLong, Short writeTable, String segmentationId,
- Long localPort, Long ethPort, boolean write) {
- l2ForwardingProvider.programLocalVlanBcastOut(dpidLong, segmentationId, localPort, ethPort, write);
- }
-
- /*
- * (Table:1) Local Table Miss
- * Match: Any Remaining Flows w/a VLAN ID
- * Action: Drop w/ a low priority
- * table=2,priority=8192,vlan_id=0x5 actions=drop
- */
- // TODO This method is referenced from commented code above (which needs to be checked)
- @SuppressWarnings("unused")
- private void handleLocalVlanTableMiss(Long dpidLong, Short writeTable,
- String segmentationId, boolean write) {
- l2ForwardingProvider.programLocalVlanTableMiss(dpidLong, segmentationId, write);
- }
-
- private Group getGroup(GroupBuilder groupBuilder, NodeBuilder nodeBuilder) {
- InstanceIdentifier<Group> path1 = InstanceIdentifier.builder(Nodes.class).child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory
- .rev130819.nodes.Node.class, nodeBuilder.getKey()).augmentation(FlowCapableNode.class).child(Group.class,
- new GroupKey(groupBuilder.getGroupId())).build();
- ReadOnlyTransaction readTx = dataBroker.newReadOnlyTransaction();
- try {
- Optional<Group> data = readTx.read(LogicalDatastoreType.CONFIGURATION, path1).get();
- if (data.isPresent()) {
- return data.get();
- }
- } catch (InterruptedException|ExecutionException e) {
- LOG.error("Failed to get group {}", groupBuilder.getGroupName(), e);
- }
-
- LOG.debug("Cannot find data for Group {}", groupBuilder.getGroupName());
- return null;
- }
-
- private void writeGroup(GroupBuilder groupBuilder, NodeBuilder nodeBuilder) {
- if (NetvirtProvidersProvider.isMasterProviderInstance()) {
- ReadWriteTransaction modification = dataBroker.newReadWriteTransaction();
- InstanceIdentifier<Group> path1 = InstanceIdentifier.builder(Nodes.class).child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory
- .rev130819.nodes.Node.class, nodeBuilder.getKey()).augmentation(FlowCapableNode.class).child(Group.class,
- new GroupKey(groupBuilder.getGroupId())).build();
- modification.put(LogicalDatastoreType.CONFIGURATION, path1, groupBuilder.build(), true /*createMissingParents*/);
-
- CheckedFuture<Void, TransactionCommitFailedException> commitFuture = modification.submit();
- try {
- commitFuture.get(); // TODO: Make it async (See bug 1362)
- LOG.debug("Transaction success for write of Group {}", groupBuilder.getGroupName());
- } catch (InterruptedException|ExecutionException e) {
- LOG.error("Failed to write group {}", groupBuilder.getGroupName(), e);
- }
- }
- }
-
- private void removeGroup(GroupBuilder groupBuilder, NodeBuilder nodeBuilder) {
- if (NetvirtProvidersProvider.isMasterProviderInstance()) {
- WriteTransaction modification = dataBroker.newWriteOnlyTransaction();
- InstanceIdentifier<Group> path1 = InstanceIdentifier.builder(Nodes.class).child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory
- .rev130819.nodes.Node.class, nodeBuilder.getKey()).augmentation(FlowCapableNode.class).child(Group.class,
- new GroupKey(groupBuilder.getGroupId())).build();
- modification.delete(LogicalDatastoreType.CONFIGURATION, path1);
- CheckedFuture<Void, TransactionCommitFailedException> commitFuture = modification.submit();
-
- try {
- commitFuture.get(); // TODO: Make it async (See bug 1362)
- LOG.debug("Transaction success for deletion of Group {}", groupBuilder.getGroupName());
- } catch (InterruptedException|ExecutionException e) {
- LOG.error("Failed to remove group {}", groupBuilder.getGroupName(), e);
- }
- }
- }
-
- private void writeFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder) {
- if (NetvirtProvidersProvider.isMasterProviderInstance()){
- ReadWriteTransaction modification = dataBroker.newReadWriteTransaction();
- InstanceIdentifier<Flow> path1 =
- InstanceIdentifier.builder(Nodes.class).child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory
- .rev130819.nodes.Node.class,
- nodeBuilder.getKey()).augmentation(FlowCapableNode.class).child(Table.class,
- new TableKey(flowBuilder.getTableId())).child(Flow.class, flowBuilder.getKey()).build();
-
- //modification.put(LogicalDatastoreType.OPERATIONAL, path1, flowBuilder.build());
- modification.put(LogicalDatastoreType.CONFIGURATION, path1, flowBuilder.build(),
- true);//createMissingParents
-
-
- CheckedFuture<Void, TransactionCommitFailedException> commitFuture = modification.submit();
- try {
- commitFuture.get(); // TODO: Make it async (See bug 1362)
- LOG.debug("Transaction success for write of Flow {}", flowBuilder.getFlowName());
- } catch (InterruptedException|ExecutionException e) {
- LOG.error("Failed to write flows {}", flowBuilder.getFlowName(), e);
- }
- }
- }
-
- /**
- * Create Output Port Group Instruction
- *
- * @param nodeBuilder Node Builder
- * @param ib Map InstructionBuilder without any instructions
- * @param dpidLong Long the datapath ID of a switch/node
- * @param port Long representing a port on a switch/node
- * @param instructions List of instructions
- * @return ib InstructionBuilder Map with instructions
- */
- // TODO This method is referenced from commented code in L2ForwardingService (which needs to be checked)
- @SuppressWarnings("unused")
- protected InstructionBuilder createOutputGroupInstructions(NodeBuilder nodeBuilder,
- InstructionBuilder ib,
- Long dpidLong, Long port ,
- List<Instruction> instructions) {
- NodeConnectorId ncid = new NodeConnectorId(Constants.OPENFLOW_NODE_PREFIX + dpidLong + ":" + port);
- LOG.debug("createOutputGroupInstructions() Node Connector ID is - Type=openflow: DPID={} port={} existingInstructions={}", dpidLong, port, instructions);
-
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab = new ActionBuilder();
-
- List<Action> existingActions;
- if (instructions != null) {
- for (Instruction in : instructions) {
- if (in.getInstruction() instanceof ApplyActionsCase) {
- existingActions = (((ApplyActionsCase) in.getInstruction()).getApplyActions().getAction());
- actionList.addAll(existingActions);
- }
- }
- }
-
- GroupBuilder groupBuilder = new GroupBuilder();
- Group group = null;
-
- /* Create output action for this port*/
- OutputActionBuilder oab = new OutputActionBuilder();
- oab.setOutputNodeConnector(ncid);
- ab.setAction(new OutputActionCaseBuilder().setOutputAction(oab.build()).build());
- LOG.debug("createOutputGroupInstructions(): output action {}", ab.build());
- boolean addNew = true;
- boolean groupActionAdded = false;
-
- /* Find the group action and get the group */
- for (Action action : actionList) {
- if (action.getAction() instanceof GroupActionCase) {
- groupActionAdded = true;
- GroupActionCase groupAction = (GroupActionCase) action.getAction();
- Long id = groupAction.getGroupAction().getGroupId();
- String groupName = groupAction.getGroupAction().getGroup();
- GroupKey key = new GroupKey(new GroupId(id));
-
- groupBuilder.setGroupId(new GroupId(id));
- groupBuilder.setGroupName(groupName);
- groupBuilder.setGroupType(GroupTypes.GroupAll);
- groupBuilder.setKey(key);
- group = getGroup(groupBuilder, nodeBuilder);
- LOG.debug("createOutputGroupInstructions: group {}", group);
- break;
- }
- }
-
- LOG.debug("createOutputGroupInstructions: groupActionAdded {}", groupActionAdded);
- if (groupActionAdded) {
- /* modify the action bucket in group */
- groupBuilder = new GroupBuilder(group);
- Buckets buckets = groupBuilder.getBuckets();
- for (Bucket bucket : buckets.getBucket()) {
- List<Action> bucketActions = bucket.getAction();
- LOG.debug("createOutputGroupInstructions: bucketActions {}", bucketActions);
- for (Action action : bucketActions) {
- if (action.getAction() instanceof OutputActionCase) {
- OutputActionCase opAction = (OutputActionCase)action.getAction();
- /* If output port action already in the action list of one of the buckets, skip */
- if (opAction.getOutputAction().getOutputNodeConnector().equals(new Uri(ncid))) {
- addNew = false;
- break;
- }
- }
- }
- }
- LOG.debug("createOutputGroupInstructions: addNew {}", addNew);
- if (addNew && !buckets.getBucket().isEmpty()) {
- /* the new output action is not in the bucket, add to bucket */
- Bucket bucket = buckets.getBucket().get(0);
- List<Action> bucketActionList = new ArrayList<>();
- bucketActionList.addAll(bucket.getAction());
- /* set order for new action and add to action list */
- ab.setOrder(bucketActionList.size());
- ab.setKey(new ActionKey(bucketActionList.size()));
- bucketActionList.add(ab.build());
-
- /* set bucket and buckets list. Reset groupBuilder with new buckets.*/
- BucketsBuilder bucketsBuilder = new BucketsBuilder();
- List<Bucket> bucketList = new ArrayList<>();
- BucketBuilder bucketBuilder = new BucketBuilder();
- bucketBuilder.setBucketId(new BucketId((long) 1));
- bucketBuilder.setKey(new BucketKey(new BucketId((long) 1)));
- bucketBuilder.setAction(bucketActionList);
- bucketList.add(bucketBuilder.build());
- bucketsBuilder.setBucket(bucketList);
- groupBuilder.setBuckets(bucketsBuilder.build());
- LOG.debug("createOutputGroupInstructions: bucketList {}", bucketList);
- }
- } else {
- /* create group */
- groupBuilder = new GroupBuilder();
- groupBuilder.setGroupType(GroupTypes.GroupAll);
- groupBuilder.setGroupId(new GroupId(groupId));
- groupBuilder.setKey(new GroupKey(new GroupId(groupId)));
- groupBuilder.setGroupName("Output port group " + groupId);
- groupBuilder.setBarrier(false);
-
- BucketsBuilder bucketBuilder = new BucketsBuilder();
- List<Bucket> bucketList = new ArrayList<>();
- BucketBuilder bucket = new BucketBuilder();
- bucket.setBucketId(new BucketId((long) 1));
- bucket.setKey(new BucketKey(new BucketId((long) 1)));
-
- /* put output action to the bucket */
- List<Action> bucketActionList = new ArrayList<>();
- /* set order for new action and add to action list */
- ab.setOrder(bucketActionList.size());
- ab.setKey(new ActionKey(bucketActionList.size()));
- bucketActionList.add(ab.build());
-
- bucket.setAction(bucketActionList);
- bucketList.add(bucket.build());
- bucketBuilder.setBucket(bucketList);
- groupBuilder.setBuckets(bucketBuilder.build());
-
- /* Add new group action */
- GroupActionBuilder groupActionB = new GroupActionBuilder();
- groupActionB.setGroupId(groupId);
- groupActionB.setGroup("Output port group " + groupId);
- ab = new ActionBuilder();
- ab.setAction(new GroupActionCaseBuilder().setGroupAction(groupActionB.build()).build());
- ab.setOrder(actionList.size());
- ab.setKey(new ActionKey(actionList.size()));
- actionList.add(ab.build());
-
- groupId++;
- }
- LOG.debug("createOutputGroupInstructions: group {}", groupBuilder.build());
- LOG.debug("createOutputGroupInstructions: actionList {}", actionList);
-
- if (addNew) {
- /* rewrite the group to group table */
- writeGroup(groupBuilder, nodeBuilder);
- }
-
- // Create an Apply Action
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
-
- return ib;
- }
-
- /**
- * Remove Output Port from action list in group bucket
- *
- * @param nodeBuilder Node Builder
- * @param ib Map InstructionBuilder without any instructions
- * @param dpidLong Long the datapath ID of a switch/node
- * @param port Long representing a port on a switch/node
- * @param instructions List of instructions
- * @return ib InstructionBuilder Map with instructions
- */
- // TODO This method is referenced from commented code in L2ForwardingService (which needs to be checked)
- @SuppressWarnings("unused")
- protected boolean removeOutputPortFromGroup(NodeBuilder nodeBuilder, InstructionBuilder ib,
- Long dpidLong, Long port , List<Instruction> instructions) {
-
- NodeConnectorId ncid = new NodeConnectorId(Constants.OPENFLOW_NODE_PREFIX + dpidLong + ":" + port);
- LOG.debug("removeOutputPortFromGroup() Node Connector ID is - Type=openflow: DPID={} port={} existingInstructions={}", dpidLong, port, instructions);
-
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab;
-
- List<Action> existingActions;
- if (instructions != null) {
- for (Instruction in : instructions) {
- if (in.getInstruction() instanceof ApplyActionsCase) {
- existingActions = (((ApplyActionsCase) in.getInstruction()).getApplyActions().getAction());
- actionList.addAll(existingActions);
- break;
- }
- }
- }
-
- GroupBuilder groupBuilder = new GroupBuilder();
- Group group = null;
- boolean groupActionAdded = false;
- /* Find the group action and get the group */
- for (Action action : actionList) {
- if (action.getAction() instanceof GroupActionCase) {
- groupActionAdded = true;
- GroupActionCase groupAction = (GroupActionCase) action.getAction();
- Long id = groupAction.getGroupAction().getGroupId();
- String groupName = groupAction.getGroupAction().getGroup();
- GroupKey key = new GroupKey(new GroupId(id));
-
- groupBuilder.setGroupId(new GroupId(id));
- groupBuilder.setGroupName(groupName);
- groupBuilder.setGroupType(GroupTypes.GroupAll);
- groupBuilder.setKey(key);
- group = getGroup(groupBuilder, nodeBuilder);
- break;
- }
- }
-
- if (groupActionAdded) {
- /* modify the action bucket in group */
- groupBuilder = new GroupBuilder(group);
- Buckets buckets = groupBuilder.getBuckets();
- List<Action> bucketActions = new ArrayList<>();
- for (Bucket bucket : buckets.getBucket()) {
- int index = 0;
- boolean isPortDeleted = false;
- bucketActions = bucket.getAction();
- for (Action action : bucketActions) {
- if (action.getAction() instanceof OutputActionCase) {
- OutputActionCase opAction = (OutputActionCase)action.getAction();
- if (opAction.getOutputAction().getOutputNodeConnector().equals(new Uri(ncid))) {
- /* Find the output port in action list and remove */
- index = bucketActions.indexOf(action);
- bucketActions.remove(action);
- isPortDeleted = true;
- break;
- }
- }
- }
- if (isPortDeleted && !bucketActions.isEmpty()) {
- for (int i = index; i< bucketActions.size(); i++) {
- Action action = bucketActions.get(i);
- if (action.getOrder() != i) {
- /* Shift the action order */
- ab = new ActionBuilder();
- ab.setAction(action.getAction());
- ab.setOrder(i);
- ab.setKey(new ActionKey(i));
- Action actionNewOrder = ab.build();
- bucketActions.remove(action);
- bucketActions.add(i, actionNewOrder);
- }
- }
-
- } else if (bucketActions.isEmpty()) {
- /* remove bucket with empty action list */
- buckets.getBucket().remove(bucket);
- break;
- }
- }
- if (!buckets.getBucket().isEmpty()) {
- /* rewrite the group to group table */
- /* set bucket and buckets list. Reset groupBuilder with new buckets.*/
- BucketsBuilder bucketsBuilder = new BucketsBuilder();
- List<Bucket> bucketList = new ArrayList<>();
- BucketBuilder bucketBuilder = new BucketBuilder();
- bucketBuilder.setBucketId(new BucketId((long) 1));
- bucketBuilder.setKey(new BucketKey(new BucketId((long) 1)));
- bucketBuilder.setAction(bucketActions);
- bucketList.add(bucketBuilder.build());
- bucketsBuilder.setBucket(bucketList);
- groupBuilder.setBuckets(bucketsBuilder.build());
- LOG.debug("removeOutputPortFromGroup: bucketList {}", bucketList);
-
- writeGroup(groupBuilder, nodeBuilder);
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
- return false;
- } else {
- /* remove group with empty bucket. return true to delete flow */
- removeGroup(groupBuilder, nodeBuilder);
- return true;
- }
- } else {
- /* no group for port list. flow can be removed */
- return true;
- }
- }
-
- @Override
- public void initializeOFFlowRules(Node openflowNode) {
- String bridgeName = southbound.getBridgeName(openflowNode);
- LOG.info("initializeOFFlowRules: bridgeName: {}", bridgeName);
- String brExt = null;
- if (configurationService.isL3MultipleExternalNetworkEnabled()) {
- brExt = bridgeConfigurationManager.getMultipleExternalBridge(openflowNode);
- }
- if (bridgeName.equals(configurationService.getIntegrationBridgeName()) ||
- bridgeName.equals(configurationService.getExternalBridgeName()) || bridgeName.equals(brExt)) {
- initializeFlowRules(openflowNode, bridgeName);
- triggerInterfaceUpdates(openflowNode);
- }
- }
-
- public static NodeBuilder createNodeBuilder(String nodeId) {
- NodeBuilder builder = new NodeBuilder();
- builder.setId(new NodeId(nodeId));
- builder.setKey(new NodeKey(builder.getId()));
- return builder;
- }
-
- @Override
- public void setDependencies(BundleContext bundleContext, ServiceReference serviceReference) {
- this.bundleContext = bundleContext;
- configurationService =
- (ConfigurationService) ServiceHelper.getGlobalInstance(ConfigurationService.class, this);
- tenantNetworkManager =
- (TenantNetworkManager) ServiceHelper.getGlobalInstance(TenantNetworkManager.class, this);
- bridgeConfigurationManager =
- (BridgeConfigurationManager) ServiceHelper.getGlobalInstance(BridgeConfigurationManager.class, this);
- nodeCacheManager =
- (NodeCacheManager) ServiceHelper.getGlobalInstance(NodeCacheManager.class, this);
- resubmitAclLearnProvider =
- (ResubmitAclLearnProvider) ServiceHelper.getGlobalInstance(ResubmitAclLearnProvider.class, this);
- classifierProvider =
- (ClassifierProvider) ServiceHelper.getGlobalInstance(ClassifierProvider.class, this);
- ingressAclProvider =
- (IngressAclProvider) ServiceHelper.getGlobalInstance(IngressAclProvider.class, this);
- egressAclProvider =
- (EgressAclProvider) ServiceHelper.getGlobalInstance(EgressAclProvider.class, this);
- l2ForwardingLearnProvider =
- (L2ForwardingLearnProvider) ServiceHelper.getGlobalInstance(L2ForwardingLearnProvider.class, this);
- l2ForwardingProvider =
- (L2ForwardingProvider) ServiceHelper.getGlobalInstance(L2ForwardingProvider.class, this);
- securityServicesManager =
- (SecurityServicesManager) ServiceHelper.getGlobalInstance(SecurityServicesManager.class, this);
- southbound =
- (Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this);
- securityGroupCacheManger =
- (SecurityGroupCacheManger) ServiceHelper.getGlobalInstance(SecurityGroupCacheManger.class, this);
- }
-
- @Override
- public void setDependencies(Object impl) {
- if (impl instanceof NetworkingProviderManager) {
- NetworkingProviderManager networkingProviderManager = (NetworkingProviderManager) impl;
- networkingProviderManager.providerAdded(
- bundleContext.getServiceReference(NetworkingProvider.class.getName()), this);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.providers.openflow13;
-
-import java.util.List;
-import java.util.Map;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-import org.osgi.framework.ServiceReference;
-
-/**
- * A PipelineOrchestrator provides the necessary orchestration logic to allow multiple network services
- * to share a common OpenFlow 1.3 based multi-table pipeline.
- *
- * @author Dave Tucker
- * @author Madhu Venugopal
- */
-public interface PipelineOrchestrator {
- Service getNextServiceInPipeline(Service service);
- AbstractServiceInstance getServiceInstance(Service service);
- Map<Service, AbstractServiceInstance> getServiceRegistry();
- short getTableOffset();
- short getTable(Service service);
- List<Service> getStaticPipeline();
- void enqueue(Node node);
- void registerService(final ServiceReference ref, AbstractServiceInstance serviceInstance);
- void unregisterService(final ServiceReference ref);
-}
+++ /dev/null
-/*
- * Copyright © 2014, 2017 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.providers.openflow13;
-
-import com.google.common.collect.Lists;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.ThreadFactory;
-
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheManager;
-import org.opendaylight.netvirt.openstack.netvirt.providers.NetvirtProvidersProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheListener;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.openstack.netvirt.providers.ConfigInterface;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.util.concurrent.ThreadFactoryBuilder;
-
-public class PipelineOrchestratorImpl implements ConfigInterface, NodeCacheListener, PipelineOrchestrator {
- private static final Logger LOG = LoggerFactory.getLogger(PipelineOrchestratorImpl.class);
-
- /**
- * Return the current table offset
- * @return The table offset
- */
- @Override
- public short getTableOffset() {
- return NetvirtProvidersProvider.getTableOffset();
- }
-
- /**
- * Return the offset adjusted table for the given {@link Service}
- * @param service Identifies the openflow {@link Service}
- * @return The table id
- */
- @Override
- public short getTable(Service service) {
- return (short)(getTableOffset() + service.getTable());
- }
-
- public List<Service> getStaticPipeline() {
- return staticPipeline;
- }
-
- // This list is modified, it needs to be a proper ArrayList
- private List<Service> staticPipeline = Lists.newArrayList(
- Service.CLASSIFIER,
- Service.ARP_RESPONDER,
- Service.INBOUND_NAT,
- Service.RESUBMIT_ACL_SERVICE,
- Service.ACL_LEARN_SERVICE,
- Service.EGRESS_ACL,
- Service.LOAD_BALANCER,
- Service.ROUTING,
- Service.L3_FORWARDING,
- Service.L2_REWRITE,
- Service.INGRESS_ACL,
- Service.OUTBOUND_NAT,
- Service.L2_LEARN,
- Service.L2_FORWARDING
- );
-
- public Map<Service, AbstractServiceInstance> getServiceRegistry() {
- return serviceRegistry;
- }
-
- Map<Service, AbstractServiceInstance> serviceRegistry = new ConcurrentHashMap<>();
- private volatile BlockingQueue<Node> queue;
- private ExecutorService eventHandler;
- private Southbound southbound;
-
- public PipelineOrchestratorImpl() {
- ThreadFactory threadFactory = new ThreadFactoryBuilder()
- .setNameFormat("NV-PipelineOrch-%d").build();
- eventHandler = Executors.newSingleThreadExecutor(threadFactory);
- this.queue = new LinkedBlockingQueue<>();
- LOG.info("PipelineOrchestratorImpl constructor");
- start();
- }
-
- public void registerService(final ServiceReference ref, AbstractServiceInstance serviceInstance){
- Service service = (Service)ref.getProperty(AbstractServiceInstance.SERVICE_PROPERTY);
- LOG.info("registerService {} - {}", serviceInstance, service);
- serviceRegistry.put(service, serviceInstance);
- // insert the service if not already there. The list is ordered based of table ID.
- if (!staticPipeline.contains(service) && !isTableInPipeline(service.getTable())) {
- staticPipeline.add(service);
- staticPipeline.sort(Service.insertComparator);
- }
- LOG.info("registerService: {}", staticPipeline);
- }
-
- private boolean isTableInPipeline (short tableId) {
- boolean found = false;
- for (Service service : staticPipeline) {
- if (service.getTable() == tableId) {
- found = true;
- break;
- }
- }
- return found;
- }
-
- public void unregisterService(final ServiceReference ref) {
- serviceRegistry.remove(ref.getProperty(AbstractServiceInstance.SERVICE_PROPERTY));
- }
- @Override
- public Service getNextServiceInPipeline(Service service) {
- int index = staticPipeline.indexOf(service);
- if (index >= staticPipeline.size() - 1) {
- return null;
- }
- return staticPipeline.get(index + 1);
- }
-
- @Override
- public AbstractServiceInstance getServiceInstance(Service service) {
- if (service == null) {
- return null;
- }
- return serviceRegistry.get(service);
- }
-
- public final void start() {
- eventHandler.submit(() -> {
- try {
- while (true) {
- Node node = queue.take();
- LOG.debug("dequeue Node : {}", node);
- if (southbound.getBridge(node) != null) {
- for (Service service : staticPipeline) {
- AbstractServiceInstance serviceInstance = getServiceInstance(service);
- if (serviceInstance != null) {
- serviceInstance.programDefaultPipelineRule(node);
- }
- }
- // TODO: might need a flow to go from table 0 to the pipeline
- }
- }
- } catch (Exception e) {
- LOG.warn("Processing interrupted, terminating ", e);
- }
-
- while (!queue.isEmpty()) {
- queue.poll();
- }
- queue = null;
- });
- }
-
- public void stop() {
- queue.clear();
- eventHandler.shutdownNow();
- }
-
- @Override
- public void enqueue(Node node) {
- LOG.debug("enqueue Node : {}", node);
- try {
- queue.put(node);
- } catch (InterruptedException e) {
- LOG.warn("Failed to enqueue operation {}", node, e);
- }
- }
-
- @Override
- public void notifyNode(Node node, Action action) {
- if (action == Action.ADD) {
- enqueue(node);
- } else {
- LOG.trace("update ignored: {}", node);
- }
- }
-
- @Override
- public void setDependencies(BundleContext bundleContext, ServiceReference serviceReference) {
- NodeCacheManager nodeCacheManager =
- (NodeCacheManager) ServiceHelper.getGlobalInstance(NodeCacheManager.class, this);
- nodeCacheManager.cacheListenerAdded(
- bundleContext.getServiceReference(PipelineOrchestrator.class.getName()), this);
- southbound =
- (Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this);
- }
-
- @Override
- public void setDependencies(Object impl) {}
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 - 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.providers.openflow13;
-
-import java.util.Comparator;
-
-public enum Service {
-
- CLASSIFIER ((short) 0, "Classifier"),
- GATEWAY_RESOLVER((short) 0, "External Network Gateway Resolver"),
- DIRECTOR ((short) 10, "Director"),
- SFC_CLASSIFIER ((short) 10, "SFC Classifier"),
- ARP_RESPONDER ((short) 20, "Distributed ARP Responder"),
- INBOUND_NAT ((short) 30, "DNAT for inbound floating-ip traffic"),
- RESUBMIT_ACL_SERVICE ((short) 31, "Resubmit service for Learn ACL"),
- ACL_LEARN_SERVICE ((short) 39, "ACL Learn Service"),
- EGRESS_ACL ((short) 40, "Egress Acces-control"),
- LOAD_BALANCER ((short) 50, "Distributed LBaaS"),
- ROUTING ((short) 60, "Distributed Virtual Routing (DVR)"),
- ICMP_ECHO ((short) 70, "Distributed ICMP Echo Responder"),
- L3_FORWARDING ((short) 70, "Layer 3 forwarding/lookup service"),
- L2_REWRITE ((short) 80, "Layer2 rewrite service"),
- INGRESS_ACL ((short) 90, "Ingress Acces-control"),
- OUTBOUND_NAT ((short) 100, "DNAT for outbound floating-ip traffic"),
- L2_LEARN ((short) 105, "Layer2 mac remote tep learning"),
- L2_FORWARDING ((short) 110, "Layer2 mac,vlan based forwarding");
-
- short table;
- String description;
-
- Service(short table, String description) {
- this.table = table;
- this.description = description;
- }
-
- public short getTable() {
- return table;
- }
-
- public String getDescription() {
- return description;
- }
-
- public static Comparator<Service> insertComparator = Comparator.comparingInt(Service::getTable);
-}
+++ /dev/null
-/*
- * Copyright (c) 2017 NEC Corporation 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.netvirt.openstack.netvirt.providers.openflow13.services;
-
-import com.google.common.base.Optional;
-import com.google.common.collect.Lists;
-import com.google.common.util.concurrent.CheckedFuture;
-import com.google.common.util.concurrent.FutureCallback;
-import com.google.common.util.concurrent.Futures;
-import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
-import org.opendaylight.netvirt.openstack.netvirt.api.SecurityGroupCacheManger;
-import org.opendaylight.netvirt.openstack.netvirt.api.SecurityServicesManager;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.AbstractServiceInstance;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityGroup;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityRule;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSecurityRuleCRUD;
-import org.opendaylight.netvirt.utils.mdsal.openflow.ActionUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.InstructionUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.MatchUtils;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action;
-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.FlowCookie;
-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.list.Instruction;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.annotation.Nullable;
-import java.math.BigInteger;
-import java.util.ArrayList;
-
-import java.util.List;
-
-/**
- * Provide functionalities for programing pipeline flows associated with Security rules
- */
-public class AbstractAclService extends AbstractServiceInstance {
- private static final Logger LOG = LoggerFactory.getLogger(AbstractAclService.class);
- protected volatile SecurityServicesManager securityServicesManager;
- protected volatile SecurityGroupCacheManger securityGroupCacheManger;
- protected volatile INeutronSecurityRuleCRUD neutronSecurityRule;
- protected static final int PORT_RANGE_MIN = 1;
- protected static final int PORT_RANGE_MAX = 65535;
- protected static final NeutronSecurityRule TCP_SECURITY_GROUP_RULE_IPv4_ANY = new NeutronSecurityRule();
- protected static final NeutronSecurityRule UDP_SECURITY_GROUP_RULE_IPv4_ANY = new NeutronSecurityRule();
- protected static final NeutronSecurityRule ICMP_SECURITY_GROUP_RULE_IPv4_ANY = new NeutronSecurityRule();
-
- static {
- TCP_SECURITY_GROUP_RULE_IPv4_ANY.setSecurityRuleProtocol(MatchUtils.TCP);
- TCP_SECURITY_GROUP_RULE_IPv4_ANY.setSecurityRuleEthertype(NeutronSecurityRule.ETHERTYPE_IPV4);
- TCP_SECURITY_GROUP_RULE_IPv4_ANY.setSecurityRulePortMin(null);
- TCP_SECURITY_GROUP_RULE_IPv4_ANY.setSecurityRulePortMax(null);
- UDP_SECURITY_GROUP_RULE_IPv4_ANY.setSecurityRuleProtocol(MatchUtils.UDP);
- UDP_SECURITY_GROUP_RULE_IPv4_ANY.setSecurityRuleEthertype(NeutronSecurityRule.ETHERTYPE_IPV4);
- UDP_SECURITY_GROUP_RULE_IPv4_ANY.setSecurityRulePortMin(null);
- UDP_SECURITY_GROUP_RULE_IPv4_ANY.setSecurityRulePortMax(null);
- ICMP_SECURITY_GROUP_RULE_IPv4_ANY.setSecurityRuleProtocol(MatchUtils.ICMP);
- ICMP_SECURITY_GROUP_RULE_IPv4_ANY.setSecurityRuleEthertype(NeutronSecurityRule.ETHERTYPE_IPV4);
- ICMP_SECURITY_GROUP_RULE_IPv4_ANY.setSecurityRulePortMin(null);
- ICMP_SECURITY_GROUP_RULE_IPv4_ANY.setSecurityRulePortMax(null);
- }
-
- protected AbstractAclService(Service service) {
- super(service);
- }
-
- /**
- * Add or remove flow to the node.
- *
- * @param flowBuilder the flow builder
- * @param nodeBuilder the node builder
- * @param write whether it is a write
- */
- protected void syncFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder,
- boolean write) {
- if (write) {
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
- }
-
- /**
- * Add or remove security group related flow to the node.
- *
- * @param flowBuilder the flow builder
- * @param nodeBuilder the node builder
- * @param write whether it is a write
- */
- protected void syncSecurityRuleFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder, boolean write) {
- LOG.trace("syncSecurityRuleFlow {} {}", flowBuilder.build(), write);
- if (securityServicesManager.isConntrackEnabled()) {
- syncFlow(flowBuilder, nodeBuilder, write);
- } else {
- if (write) {
- writeSecurityRuleFlow(flowBuilder, nodeBuilder);
- } else {
- removeSecurityRuleFlow(flowBuilder, nodeBuilder);
- }
- }
- }
-
- /**
- * Add security related flow to the node.
- *
- * The flow cookie contains the counter which keeps track of duplicate security rules in a particular VM.
- * When writing a security related flow, the flow counter is incremented if the flow already exists,
- * otherwise the flow is added to the node with counter value is '1'
- * When removing a security related flow, if the counter value is '1', the flow is removed from the node,
- * otherwise the flow counter is decremented
- *
- * @param flowBuilder the flow builder
- * @param nodeBuilder the node builder
- */
- protected void writeSecurityRuleFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder) {
- ReadOnlyTransaction readTx = dataBroker.newReadOnlyTransaction();
- InstanceIdentifier<Flow> flowInstanceIdentifier = createFlowPath(flowBuilder, nodeBuilder);
- CheckedFuture<Optional<Flow>, ReadFailedException> readFlowFuture =
- readTx.read(LogicalDatastoreType.CONFIGURATION, flowInstanceIdentifier);
- Futures.addCallback(readFlowFuture, new FutureCallback<Optional<Flow>>() {
- @Override
- public void onSuccess(@Nullable Optional<Flow> optionalFlow) {
- if (optionalFlow != null) {
- if (optionalFlow.isPresent()) {
- Flow flow = optionalFlow.get();
- if (flow.getCookie() == null) {
- flowBuilder.setCookie(new FlowCookie(BigInteger.ONE));
- } else {
- flowBuilder.setCookie(new FlowCookie(flow.getCookie().getValue().add(BigInteger.ONE)));
- }
- } else {
- flowBuilder.setCookie(new FlowCookie(BigInteger.ONE));
- }
- writeFlow(flowBuilder, nodeBuilder);
- }
- }
- @Override
- public void onFailure(Throwable throwable) {
- LOG.warn("Read Config/DS for Flow failed! " + flowInstanceIdentifier, throwable);
- }
- });
- }
-
- /**
- * Remove security related flow from the node.
- *
- * The flow cookie contains the counter which keeps track of duplicate security rules in a particular VM.
- * If the flow counter value stored in the flow cookie is '1', which indicates the flow is only associated with
- * single security rule, it is removed from the node.
- * Otherwise the flow counter is decremented.
- *
- * @param flowBuilder the flow builder
- * @param nodeBuilder the node builder
- */
- protected void removeSecurityRuleFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder) {
- ReadOnlyTransaction readTx = dataBroker.newReadOnlyTransaction();
- InstanceIdentifier<Flow> flowInstanceIdentifier = createFlowPath(flowBuilder, nodeBuilder);
- CheckedFuture<Optional<Flow>, ReadFailedException> readFlowFuture =
- readTx.read(LogicalDatastoreType.CONFIGURATION, flowInstanceIdentifier);
- Futures.addCallback(readFlowFuture, new FutureCallback<Optional<Flow>>() {
- @Override
- public void onSuccess(@Nullable Optional<Flow> optionalFlow) {
- if (optionalFlow != null && optionalFlow.isPresent()) {
- Flow flow = optionalFlow.get();
- if (flow.getCookie() != null) {
- FlowCookie flowCookie = flow.getCookie();
- BigInteger cookie = flowCookie.getValue();
- int compareValue = cookie.compareTo(BigInteger.ONE);
- if (compareValue == 0) {
- removeFlow(flowBuilder, nodeBuilder);
- } else if (compareValue == 1) {
- flowBuilder.setCookie(new FlowCookie(cookie.subtract(BigInteger.ONE)));
- writeFlow(flowBuilder, nodeBuilder);
- }
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
- }
- }
- @Override
- public void onFailure(Throwable throwable) {
- LOG.warn("Read Config/DS for Flow failed! " + flowInstanceIdentifier, throwable);
- }
-
- });
- }
-
- protected FlowBuilder addInstructionWithConntrackCommit(FlowBuilder flowBuilder, boolean isDrop) {
- InstructionBuilder instructionBuilder = null;
- if (securityServicesManager.isConntrackEnabled()) {
- Action conntrackAction = ActionUtils.nxConntrackAction(1, 0L, 0, (short) 0xff);
- instructionBuilder = InstructionUtils
- .createInstructionBuilder(ActionUtils.conntrackActionBuilder(conntrackAction), 1, false);
- }
- return addPipelineInstruction(flowBuilder, instructionBuilder, isDrop);
- }
-
- protected FlowBuilder addPipelineInstruction(FlowBuilder flowBuilder, InstructionBuilder instructionBuilder,
- boolean isDrop) {
- InstructionBuilder pipeLineIndstructionBuilder = createPipleLineInstructionBuilder(isDrop);
- List<Instruction> instructionsList = Lists.newArrayList();
- instructionsList.add(pipeLineIndstructionBuilder.build());
- if (null != instructionBuilder) {
- instructionsList.add(instructionBuilder.build());
- }
- InstructionsBuilder isb = new InstructionsBuilder();
- isb.setInstruction(instructionsList);
- flowBuilder.setInstructions(isb.build());
- return flowBuilder;
- }
-
- protected InstructionBuilder createPipleLineInstructionBuilder(boolean drop) {
- InstructionBuilder ib = this.getMutablePipelineInstructionBuilder();
- if (drop) {
- InstructionUtils.createDropInstructions(ib);
- }
- ib.setOrder(0);
- List<Instruction> instructionsList = Lists.newArrayList();
- ib.setKey(new InstructionKey(0));
- instructionsList.add(ib.build());
- return ib;
- }
-
- protected List<NeutronSecurityRule> getSecurityRulesforGroup(NeutronSecurityGroup securityGroup) {
- List<NeutronSecurityRule> securityRules = new ArrayList<>();
- List<NeutronSecurityRule> rules = neutronSecurityRule.getAllNeutronSecurityRules();
- for (NeutronSecurityRule securityRule : rules) {
- if (securityGroup.getID().equals(securityRule.getSecurityRuleGroupID())) {
- securityRules.add(securityRule);
- }
- }
- return securityRules;
- }
-
- protected void addConntrackMatch(MatchBuilder matchBuilder, int state, int mask) {
- if (securityServicesManager.isConntrackEnabled()) {
- MatchUtils.addCtState(matchBuilder, state, mask);
- }
-
- }
-
- protected FlowBuilder addInstructionWithConntrackRecirc(FlowBuilder flowBuilder) {
- InstructionBuilder instructionBuilder = null;
- if (securityServicesManager.isConntrackEnabled()) {
- Action conntrackAction = ActionUtils.nxConntrackAction(0, 0L, 0, (short) 0x0);
- instructionBuilder = InstructionUtils
- .createInstructionBuilder(ActionUtils.conntrackActionBuilder(conntrackAction), 1, false);
- List<Instruction> instructionsList = Lists.newArrayList();
- instructionsList.add(instructionBuilder.build());
- InstructionsBuilder isb = new InstructionsBuilder();
- isb.setInstruction(instructionsList);
- flowBuilder.setInstructions(isb.build());
- }
- return flowBuilder;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services;
-
-import java.math.BigInteger;
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.util.ArrayList;
-import java.util.List;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.ArpProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-import org.opendaylight.netvirt.openstack.netvirt.api.Status;
-import org.opendaylight.netvirt.openstack.netvirt.api.StatusCode;
-import org.opendaylight.netvirt.openstack.netvirt.providers.ConfigInterface;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.AbstractServiceInstance;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.netvirt.utils.mdsal.openflow.ActionUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.FlowUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.MatchUtils;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
-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.flow.inventory.rev130819.tables.table.FlowBuilder;
-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.ApplyActionsCaseBuilder;
-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;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.EtherType;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ArpResponderService extends AbstractServiceInstance implements ArpProvider, ConfigInterface {
- private static final Logger LOG = LoggerFactory.getLogger(ArpResponderService.class);
-
- public ArpResponderService() {
- super(Service.ARP_RESPONDER);
- }
-
- public ArpResponderService(Service service) {
- super(service);
- }
-
- @Override
- public Status programStaticArpEntry(Long dpid, String segmentationId, String macAddressStr,
- InetAddress ipAddress, Action action) {
- if (ipAddress instanceof Inet6Address) {
- // WORKAROUND: For now ipv6 is not supported
- // TODO: implement ipv6 case
- LOG.debug("ipv6 address case is not implemented yet. dpid {} segmentationId {} macAddressStr, "
- + "ipAddress {} action {}",
- dpid, segmentationId, macAddressStr, ipAddress, action);
- return new Status(StatusCode.NOTIMPLEMENTED);
- }
-
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpid);
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = "ArpResponder_" + segmentationId + "_" + ipAddress.getHostAddress();
- FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable()).setPriority(1024);
-
- MatchBuilder matchBuilder = new MatchBuilder();
- MatchUtils.createEtherTypeMatch(matchBuilder, new EtherType(Constants.ARP_ETHERTYPE));
- MatchUtils.createArpDstIpv4Match(matchBuilder, MatchUtils.iPv4PrefixFromIPv4Address(ipAddress.getHostAddress()));
-
- if (segmentationId != null) {
- final Long inPort = MatchUtils.parseExplicitOFPort(segmentationId);
- if (inPort != null) {
- MatchUtils.createInPortMatch(matchBuilder, dpid, inPort);
- } else {
- MatchUtils.createTunnelIDMatch(matchBuilder, new BigInteger(segmentationId));
- }
- }
-
- flowBuilder.setMatch(matchBuilder.build());
-
- if (action.equals(Action.ADD)) {
- // Instructions List Stores Individual Instructions
- InstructionsBuilder isb = new InstructionsBuilder();
- List<Instruction> instructions = new ArrayList<>();
- InstructionBuilder ib = new InstructionBuilder();
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- ActionBuilder ab = new ActionBuilder();
- List<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action> actionList = new ArrayList<>();
-
- // Move Eth Src to Eth Dst
- ab.setAction(ActionUtils.nxMoveEthSrcToEthDstAction());
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
- actionList.add(ab.build());
-
- // Set Eth Src
- MacAddress macAddress = new MacAddress(macAddressStr);
- ab.setAction(ActionUtils.setDlSrcAction(macAddress));
- ab.setOrder(1);
- ab.setKey(new ActionKey(1));
- actionList.add(ab.build());
-
- // Set ARP OP
- ab.setAction(ActionUtils.nxLoadArpOpAction(BigInteger.valueOf(0x02L)));
- ab.setOrder(2);
- ab.setKey(new ActionKey(2));
- actionList.add(ab.build());
-
- // Move ARP SHA to ARP THA
- ab.setAction(ActionUtils.nxMoveArpShaToArpThaAction());
- ab.setOrder(3);
- ab.setKey(new ActionKey(3));
- actionList.add(ab.build());
-
- // Move ARP SPA to ARP TPA
- ab.setAction(ActionUtils.nxMoveArpSpaToArpTpaAction());
- ab.setOrder(4);
- ab.setKey(new ActionKey(4));
- actionList.add(ab.build());
-
- // Load Mac to ARP SHA
- ab.setAction(ActionUtils.nxLoadArpShaAction(macAddress));
- ab.setOrder(5);
- ab.setKey(new ActionKey(5));
- actionList.add(ab.build());
-
- // Load IP to ARP SPA
- ab.setAction(ActionUtils.nxLoadArpSpaAction(ipAddress.getHostAddress()));
- ab.setOrder(6);
- ab.setKey(new ActionKey(6));
- actionList.add(ab.build());
-
- // Output of InPort
- ab.setAction(ActionUtils.outputAction(FlowUtils.getSpecialNodeConnectorId(dpid, "INPORT")));
- ab.setOrder(7);
- ab.setKey(new ActionKey(7));
- actionList.add(ab.build());
-
- // Create Apply Actions Instruction
- aab.setAction(actionList);
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
- ib.setOrder(0);
- ib.setKey(new InstructionKey(0));
- instructions.add(ib.build());
-
- flowBuilder.setInstructions(isb.setInstruction(instructions).build());
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
-
- // ToDo: WriteFlow/RemoveFlow should return something we can use to check success
- return new Status(StatusCode.SUCCESS);
- }
-
- @Override
- public void setDependencies(BundleContext bundleContext, ServiceReference serviceReference) {
- super.setDependencies(bundleContext.getServiceReference(ArpProvider.class.getName()), this);
- }
-
- @Override
- public void setDependencies(Object impl) {}
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services;
-
-import java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.List;
-import org.opendaylight.netvirt.openstack.netvirt.api.ClassifierProvider;
-import org.opendaylight.netvirt.openstack.netvirt.providers.ConfigInterface;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.AbstractServiceInstance;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.netvirt.utils.mdsal.openflow.ActionUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.FlowUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.InstructionUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.MatchUtils;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
-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.flow.inventory.rev130819.tables.table.FlowBuilder;
-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.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;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.EtherType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.VlanId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg0;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg6;
-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;
-
-public class ClassifierService extends AbstractServiceInstance implements ClassifierProvider, ConfigInterface {
- public final static long REG_VALUE_FROM_LOCAL_0 = 0x0L;
- public final static long REG_VALUE_FROM_LOCAL = 0x1L;
- public final static long REG_VALUE_FROM_REMOTE = 0x2L;
- public static final Class<? extends NxmNxReg> REG_FIELD = NxmNxReg0.class;
- public static final Class<? extends NxmNxReg> REG_FIELD_6 = NxmNxReg6.class;
-
- public ClassifierService() {
- super(Service.CLASSIFIER);
- }
-
- public ClassifierService(Service service) {
- super(service);
- }
-
- /*
- * (Table:Classifier) Egress VM Traffic Towards TEP
- * Match: Destination Ethernet Addr and OpenFlow InPort
- * Instruction: Set TunnelID and GOTO Table Tunnel Table (n)
- * table=0,in_port=2,dl_src=00:00:00:00:00:01 \
- * actions=set_field:5->tun_id,goto_table=<next-table>"
- */
- @Override
- public void programLocalInPort(Long dpidLong, String segmentationId, Long inPort, String attachedMac,
- boolean write) {
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = "LocalMac_" + segmentationId + "_" + inPort + "_" + attachedMac;
- FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable());
-
- MatchBuilder matchBuilder = new MatchBuilder();
- MatchUtils.createEthSrcMatch(matchBuilder, new MacAddress(attachedMac));
- MatchUtils.createInPortMatch(matchBuilder, dpidLong, inPort);
- flowBuilder.setMatch(matchBuilder.build());
-
- 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 = new ArrayList<>();
-
- InstructionUtils.createSetTunnelIdInstructions(ib, new BigInteger(segmentationId));
- ApplyActionsCase aac = (ApplyActionsCase) ib.getInstruction();
- List<Action> actionList = aac.getApplyActions().getAction();
-
- ActionBuilder ab = new ActionBuilder();
- ab.setAction(ActionUtils.nxLoadRegAction(new DstNxRegCaseBuilder().setNxReg(REG_FIELD).build(),
- BigInteger.valueOf(REG_VALUE_FROM_LOCAL)));
- ab.setOrder(1);
- ab.setKey(new ActionKey(1));
-
- actionList.add(ab.build());
-
- ib.setOrder(0);
- ib.setKey(new InstructionKey(0));
- instructions.add(ib.build());
-
- // Next service GOTO Instructions Need to be appended to the List
- ib = this.getMutablePipelineInstructionBuilder();
- ib.setOrder(1);
- ib.setKey(new InstructionKey(1));
- instructions.add(ib.build());
-
- // Add InstructionBuilder to the Instruction(s)Builder List
- isb.setInstruction(instructions);
-
- // Add InstructionsBuilder to FlowBuilder
- flowBuilder.setInstructions(isb.build());
-
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
- }
-
- /*
- * (Table:Classifier) Egress VM Traffic Towards TEP
- * Match: Source Ethernet Addr and OpenFlow InPort
- * Instruction: Set VLANID and GOTO Table Egress (n)
- * table=0,in_port=2,dl_src=00:00:00:00:00:01 \
- * actions=push_vlan, set_field:5->vlan_id,goto_table=<Next-Table>"
- * table=0,in_port=1,vlan_tci=0x0000/0x1fff,dl_src=fa:16:3e:70:2f:c2 actions=push_vlan:0x8100,set_field:6097->vlan_vid,goto_table:20
- */
- @Override
- public void programLocalInPortSetVlan(Long dpidLong, String segmentationId, Long inPort, String attachedMac,
- boolean write) {
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = "LocalMac_" + segmentationId + "_" + inPort + "_" + attachedMac;
- FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable());
-
- MatchBuilder matchBuilder = new MatchBuilder();
- MatchUtils.createEthSrcMatch(matchBuilder, new MacAddress(attachedMac));
- MatchUtils.createInPortMatch(matchBuilder, dpidLong, inPort);
- // openflowplugin requires a vlan match to add a vlan
- MatchUtils.createVlanIdMatch(matchBuilder, new VlanId(0), false);
- flowBuilder.setMatch(matchBuilder.build());
-
- 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 = new ArrayList<>();
-
- // Set VLAN ID Instruction
- InstructionUtils.createSetVlanInstructions(ib, new VlanId(Integer.valueOf(segmentationId)));
- ib.setOrder(0);
- ib.setKey(new InstructionKey(0));
- instructions.add(ib.build());
-
- // Next service GOTO Instructions Need to be appended to the List
- ib = this.getMutablePipelineInstructionBuilder();
- ib.setOrder(1);
- ib.setKey(new InstructionKey(1));
- instructions.add(ib.build());
-
- // Add InstructionBuilder to the Instruction(s)Builder List
- isb.setInstruction(instructions);
-
- // Add InstructionsBuilder to FlowBuilder
- flowBuilder.setInstructions(isb.build());
-
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
- }
-
- /*
- * (Table:Classifier) Drop frames source from a VM that do not
- * match the associated MAC address of the local VM.
- * Match: Low priority anything not matching the VM SMAC
- * Instruction: Drop
- * table=0,priority=16384,in_port=1 actions=drop"
- */
- @Override
- public void programDropSrcIface(Long dpidLong, Long inPort, boolean write) {
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = "DropFilter_" + inPort;
- FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable()).setPriority(8192);
-
- MatchBuilder matchBuilder = new MatchBuilder();
- MatchUtils.createInPortMatch(matchBuilder, dpidLong, inPort);
- flowBuilder.setMatch(matchBuilder.build());
-
- 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 = new ArrayList<>();
-
- // 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);
-
- // Add InstructionsBuilder to FlowBuilder
- flowBuilder.setInstructions(isb.build());
-
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
- }
-
- /*
- * (Table:0) Ingress Tunnel Traffic
- * Match: OpenFlow InPort and Tunnel ID
- * Action: GOTO Local Table (10)
- * table=0,tun_id=0x5,in_port=10, actions=goto_table:2
- */
- @Override
- public void programTunnelIn(Long dpidLong, String segmentationId, Long ofPort, boolean write) {
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = "TunnelIn_" + segmentationId + "_" + ofPort;
- FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable());
-
- MatchBuilder matchBuilder = new MatchBuilder();
- MatchUtils.createTunnelIDMatch(matchBuilder, new BigInteger(segmentationId));
- MatchUtils.createInPortMatch(matchBuilder, dpidLong, ofPort);
- flowBuilder.setMatch(matchBuilder.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 = new ArrayList<>();
-
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab = new ActionBuilder();
- ab.setAction(ActionUtils.nxLoadRegAction(new DstNxRegCaseBuilder().setNxReg(REG_FIELD).build(),
- BigInteger.valueOf(REG_VALUE_FROM_REMOTE)));
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
- actionList.add(ab.build());
-
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
-
- // Call the InstructionBuilder Methods Containing Actions
- ib.setOrder(0);
- ib.setKey(new InstructionKey(0));
- instructions.add(ib.build());
-
- // Append the default pipeline after the first classification
- ib = this.getMutablePipelineInstructionBuilder();
- ib.setOrder(1);
- ib.setKey(new InstructionKey(1));
- instructions.add(ib.build());
-
- // Add InstructionBuilder to the Instruction(s)Builder List
- isb.setInstruction(instructions);
-
- // Add InstructionsBuilder to FlowBuilder
- flowBuilder.setInstructions(isb.build());
-
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
- }
-
- /*
- * (Table:0) Ingress VLAN Traffic
- * Match: OpenFlow InPort and vlan ID
- * Action: GOTO Local Table (20)
- * table=0,vlan_id=0x5,in_port=10, actions=goto_table:2
- * table=0,in_port=2,dl_vlan=2001 actions=goto_table:20
- */
- @Override
- public void programVlanIn(Long dpidLong, String segmentationId, Long ethPort, boolean write) {
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = "VlanIn_" + segmentationId + "_" + ethPort;
- FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable());
-
- MatchBuilder matchBuilder = new MatchBuilder();
- MatchUtils.createVlanIdMatch(matchBuilder, new VlanId(Integer.valueOf(segmentationId)), true);
- MatchUtils.createInPortMatch(matchBuilder, dpidLong, ethPort);
- flowBuilder.setMatch(matchBuilder.build());
-
- if (write) {
- // Create the OF Actions and Instructions
- InstructionsBuilder isb = new InstructionsBuilder();
-
- // Instructions List Stores Individual Instructions
- List<Instruction> instructions = new ArrayList<>();
-
- // Append the default pipeline after the first classification
- 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);
-
- // Add InstructionsBuilder to FlowBuilder
- flowBuilder.setInstructions(isb.build());
-
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
- }
-
- /*
- * Create an LLDP Flow Rule to encapsulate into
- * a packet_in that is sent to the controller
- * for topology handling.
- * Match: Ethertype 0x88CCL
- * Action: Punt to Controller in a Packet_In msg
- */
- @Override
- public void programLLDPPuntRule(Long dpidLong) {
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = "LLDP";
- FlowUtils.initFlowBuilder(flowBuilder, flowName, Service.CLASSIFIER.getTable());
-
- MatchBuilder matchBuilder = new MatchBuilder();
- MatchUtils.createEtherTypeMatch(matchBuilder, new EtherType(0x88CCL));
- flowBuilder.setMatch(matchBuilder.build());
-
- // Create the OF Actions and Instructions
- InstructionBuilder ib = new InstructionBuilder();
- InstructionsBuilder isb = new InstructionsBuilder();
-
- // Instructions List Stores Individual Instructions
- List<Instruction> instructions = new ArrayList<>();
-
- // Call the InstructionBuilder Methods Containing Actions
- InstructionUtils.createSendToControllerInstructions(FlowUtils.getNodeName(dpidLong), ib);
- ib.setOrder(0);
- ib.setKey(new InstructionKey(0));
- instructions.add(ib.build());
-
- // Add InstructionBuilder to the Instruction(s)Builder List
- isb.setInstruction(instructions);
-
- // Add InstructionsBuilder to FlowBuilder
- flowBuilder.setInstructions(isb.build());
-
- writeFlow(flowBuilder, nodeBuilder);
- }
-
- @Override
- public void programGotoTable(Long dpidLong, boolean write) {
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = "TableOffset_" + getTable();
- FlowUtils.initFlowBuilder(flowBuilder, flowName, Service.CLASSIFIER.getTable())
- .setPriority(6);
-
- MatchBuilder matchBuilder = new MatchBuilder();
- flowBuilder.setMatch(matchBuilder.build());
-
- if (write) {
- InstructionsBuilder isb = new InstructionsBuilder();
- List<Instruction> instructions = new ArrayList<>();
- InstructionBuilder ib =
- InstructionUtils.createGotoTableInstructions(new InstructionBuilder(), getTable());
- ib.setOrder(0);
- ib.setKey(new InstructionKey(0));
- instructions.add(ib.build());
-
- isb.setInstruction(instructions);
- flowBuilder.setInstructions(isb.build());
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
- }
-
- @Override
- public void setDependencies(BundleContext bundleContext, ServiceReference serviceReference) {
- super.setDependencies(bundleContext.getServiceReference(ClassifierProvider.class.getName()), this);
- }
-
- @Override
- public void setDependencies(Object impl) {}
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 NEC Corporation 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.netvirt.openstack.netvirt.providers.openflow13.services;
-
-import java.math.BigInteger;
-import java.util.List;
-import java.util.ArrayList;
-
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.netvirt.openstack.netvirt.api.LearnConstants;
-import org.opendaylight.netvirt.openstack.netvirt.api.LearnConstants.LearnFlowModsType;
-import org.opendaylight.netvirt.openstack.netvirt.providers.NetvirtProvidersProvider;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
-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.flow.inventory.rev130819.tables.table.FlowBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.InstructionsBuilder;
-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.InstructionKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.add.group.input.buckets.bucket.action.action.NxActionResubmitRpcAddGroupCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.resubmit.grouping.NxResubmitBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.flow.mod.spec.flow.mod.spec.FlowModAddMatchFromFieldCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.flow.mod.spec.flow.mod.spec.FlowModAddMatchFromValueCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.flow.mod.spec.flow.mod.spec.FlowModCopyFieldIntoFieldCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.flow.mod.spec.flow.mod.spec.FlowModCopyValueIntoFieldCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.flow.mod.spec.flow.mod.spec.FlowModOutputToPortCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.flow.mod.spec.flow.mod.spec.flow.mod.add.match.from.field._case.FlowModAddMatchFromFieldBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.flow.mod.spec.flow.mod.spec.flow.mod.add.match.from.value._case.FlowModAddMatchFromValueBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.flow.mod.spec.flow.mod.spec.flow.mod.copy.field.into.field._case.FlowModCopyFieldIntoFieldBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.flow.mod.spec.flow.mod.spec.flow.mod.copy.value.into.field._case.FlowModCopyValueIntoFieldBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.flow.mod.spec.flow.mod.spec.flow.mod.output.to.port._case.FlowModOutputToPortBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nodes.node.table.flow.instructions.instruction.instruction.apply.actions._case.apply.actions.action.action.NxActionLearnNodesNodeTableFlowApplyActionsCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.learn.grouping.NxLearnBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.learn.grouping.nx.learn.FlowMods;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.learn.grouping.nx.learn.FlowModsBuilder;
-
-public class EgressAclLearnServiceUtil {
- private static final short LEARN_TABLE_ID = Service.ACL_LEARN_SERVICE.getTable();
- private static final short RESUBMIT_TABLE_ID = Service.LOAD_BALANCER.getTable();
-
- /*
- * (Table:EgressAclLearnService) EgressACL Learning
- * Match: reg6 = LearnConstants.NxmOfFieldType.NXM_NX_REG6
- * Action: learn and resubmit to next table
- * "table=40,dl_src=fa:16:3e:d3:bb:8a,tcp,priority=61002,tcp_dst=22,actions=learn(table=39,idle_timeout=18000,fin_idle_timeout=300,
- * fin_hard_timeout=0,priority=61010, cookie=0x6900000,eth_type=0x800,nw_proto=6, NXM_OF_IP_SRC[]=NXM_OF_IP_DST[],NXM_OF_IP_DST[]=NXM_OF_IP_SRC[],
- * NXM_OF_TCP_SRC[]=NXM_OF_TCP_DST[],NXM_OF_TCP_DST[]=NXM_OF_TCP_SRC[],load:0x1->NXM_NX_REG6[0..7]),resubmit(,50)"
- */
- public static FlowBuilder programEgressAclLearnRuleForTcp(FlowBuilder flowBuilder) {
- List<Action> listAction = new ArrayList<>();
-
- // Create learn action
-
- /*
- * learn header
- * 0 1 2 3 4 5 6 7 idleTO hardTO prio cook flags table finidle finhard
- *
- * learn flowmod
- * 0 1 2 3 learnFlowModType srcField dstField FlowModNumBits
- */
- /*String[] header = new String[] {
- "18000", "0", "61010", "0", "0", "39", "300", "0"
- };*/
- String[] header = new String[] {
- String.valueOf(NetvirtProvidersProvider.getSecurityGroupTcpIdleTimeout()),
- String.valueOf(NetvirtProvidersProvider.getSecurityGroupTcpHardTimeout()),
- LearnConstants.LEARN_PRIORITY,
- "0",
- LearnConstants.DELETE_LEARNED_FLAG_VALUE,
- String.valueOf(LEARN_TABLE_ID),
- String.valueOf(NetvirtProvidersProvider.getSecurityGroupTcpFinIdleTimeout()),
- String.valueOf(NetvirtProvidersProvider.getSecurityGroupTcpFinHardTimeout())
- };
-
- String[][] flowMod = new String[8][];
- //eth_type=0x800
- flowMod[0] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_VALUE.name(),
- Integer.toString(LearnConstants.ETHTYPE_IPV4),
- LearnConstants.NxmOfFieldType.NXM_OF_ETH_TYPE.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_ETH_TYPE.getFlowModHeaderLen() };
- flowMod[1] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_VALUE.name(),
- Integer.toString(LearnConstants.IP_PROT_TCP),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_PROTO.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_PROTO.getFlowModHeaderLen() };
- //nw_proto=6
- //NXM_OF_IP_SRC[]=NXM_OF_IP_DST[]
- flowMod[2] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_FIELD.name(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_DST.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_SRC.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_DST.getFlowModHeaderLen()};
- // NXM_OF_IP_DST[]=NXM_OF_IP_SRC[]
- flowMod[3] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_FIELD.name(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_SRC.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_DST.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_SRC.getFlowModHeaderLen()};
- //NXM_OF_TCP_SRC[]=NXM_OF_TCP_DST[]
- flowMod[4] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_FIELD.name(),
- LearnConstants.NxmOfFieldType.NXM_OF_TCP_DST.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_TCP_SRC.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_TCP_DST.getFlowModHeaderLen()};
- //NXM_OF_TCP_DST[]=NXM_OF_TCP_SRC[]
- flowMod[5] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_FIELD.name(),
- LearnConstants.NxmOfFieldType.NXM_OF_TCP_SRC.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_TCP_DST.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_TCP_SRC.getFlowModHeaderLen()};
- // NXM_NX_TUN_ID[]
- flowMod[6] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_FIELD.name(),
- LearnConstants.NxmOfFieldType.NXM_NX_TUN_ID.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_NX_TUN_ID.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_NX_TUN_ID.getFlowModHeaderLen() };
- flowMod[7] = new String[] {
- LearnConstants.LearnFlowModsType.COPY_FROM_VALUE.name(), "1",
- LearnConstants.NxmOfFieldType.NXM_NX_REG6.getHexType(), "8" };
- listAction.add(buildAction(0, header, flowMod));
- ActionBuilder ab = new ActionBuilder();
- ab = new ActionBuilder();
- ab.setAction(createResubmitActions());
- ab.setKey(new ActionKey(1));
- listAction.add(ab.build());
- ApplyActions applyActions = new ApplyActionsBuilder().setAction(listAction).build();
- ApplyActionsCase applyActionsCase = new ApplyActionsCaseBuilder().setApplyActions(applyActions).build();
- InstructionsBuilder instructionsBuilder = new InstructionsBuilder();
- List<Instruction> instructions = new ArrayList<>();
- InstructionBuilder instructionBuilder = new InstructionBuilder();
- instructionBuilder.setInstruction(applyActionsCase);
- instructionBuilder.setOrder(0);
- instructionBuilder.setKey(new InstructionKey(0));
- instructions.add(instructionBuilder.build());
- // Add InstructionBuilder to the Instruction(s)Builder List
- instructionsBuilder.setInstruction(instructions);
- // Add InstructionsBuilder to FlowBuilder
- flowBuilder.setInstructions(instructionsBuilder.build());
-
- return flowBuilder;
-
- }
-
- /*
- * (Table:EgressAclLearnService) EgressACL Learning
- * Match: reg6 = LearnConstants.NxmOfFieldType.NXM_NX_REG6
- * Action: learn and resubmit to next table
- * "table=40,dl_src=fa:16:3e:d3:bb:8a,tcp,priority=61002,tcp_dst=22,actions=learn(table=39,idle_timeout=300,fin_idle_timeout=0,
- * fin_hard_timeout=0,priority=61010, cookie=0x6900000,eth_type=0x800,nw_proto=6, NXM_OF_IP_SRC[]=NXM_OF_IP_DST[],NXM_OF_IP_DST[]=NXM_OF_IP_SRC[],
- * NXM_OF_UDP_SRC[]=NXM_OF_UDP_DST[],NXM_OF_UDP_DST[]=NXM_OF_UDP_SRC[],load:0x1->NXM_NX_REG6[0..7]),resubmit(,50)"
- */
- public static FlowBuilder programEgressAclLearnRuleForUdp(FlowBuilder flowBuilder) {
- List<Action> listAction = new ArrayList<>();
- // Create learn action
- /*
- * learn header
- * 0 1 2 3 4 5 6 7 idleTO hardTO prio cook flags table finidle finhard
- *
- * learn flowmod
- * 0 1 2 3 learnFlowModType srcField dstField FlowModNumBits
- */
- /*String[] header = new String[] {
- "300", "0", "61010", "0", "0", "39", "0", "0"
- };*/
- String[] header = new String[] {
- String.valueOf(NetvirtProvidersProvider.getSecurityGroupUdpIdleTimeout()),
- String.valueOf(NetvirtProvidersProvider.getSecurityGroupUdpHardTimeout()),
- LearnConstants.LEARN_PRIORITY,
- "0",
- LearnConstants.DELETE_LEARNED_FLAG_VALUE,
- String.valueOf(LEARN_TABLE_ID),
- "0",
- "0"
- };
-
- String[][] flowMod = new String[8][];
- //eth_type=0x800
- flowMod[0] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_VALUE.name(),
- Integer.toString(LearnConstants.ETHTYPE_IPV4),
- LearnConstants.NxmOfFieldType.NXM_OF_ETH_TYPE.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_ETH_TYPE.getFlowModHeaderLen() };
- flowMod[1] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_VALUE.name(),
- Integer.toString(LearnConstants.IP_PROT_UDP),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_PROTO.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_PROTO.getFlowModHeaderLen() };
- //nw_proto=6
- //NXM_OF_IP_SRC[]=NXM_OF_IP_DST[]
- flowMod[2] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_FIELD.name(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_DST.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_SRC.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_DST.getFlowModHeaderLen()};
- // NXM_OF_IP_DST[]=NXM_OF_IP_SRC[]
- flowMod[3] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_FIELD.name(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_SRC.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_DST.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_SRC.getFlowModHeaderLen()};
- //NXM_OF_TCP_SRC[]=NXM_OF_TCP_DST[]
- flowMod[4] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_FIELD.name(),
- LearnConstants.NxmOfFieldType.NXM_OF_UDP_DST.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_UDP_SRC.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_UDP_DST.getFlowModHeaderLen()};
- //NXM_OF_TCP_DST[]=NXM_OF_TCP_SRC[]
- flowMod[5] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_FIELD.name(),
- LearnConstants.NxmOfFieldType.NXM_OF_UDP_SRC.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_UDP_DST.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_UDP_SRC.getFlowModHeaderLen()};
- // NXM_NX_TUN_ID[]
- flowMod[6] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_FIELD.name(),
- LearnConstants.NxmOfFieldType.NXM_NX_TUN_ID.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_NX_TUN_ID.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_NX_TUN_ID.getFlowModHeaderLen() };
- flowMod[7] = new String[] {
- LearnConstants.LearnFlowModsType.COPY_FROM_VALUE.name(), LearnConstants.LEARN_MATCH_REG_VALUE,
- LearnConstants.NxmOfFieldType.NXM_NX_REG6.getHexType(), "8" };
- listAction.add(buildAction(0, header, flowMod));
- ActionBuilder ab = new ActionBuilder();
- ab = new ActionBuilder();
- ab.setAction(createResubmitActions());
- ab.setKey(new ActionKey(1));
- listAction.add(ab.build());
- ApplyActions applyActions = new ApplyActionsBuilder().setAction(listAction).build();
- ApplyActionsCase applyActionsCase = new ApplyActionsCaseBuilder().setApplyActions(applyActions).build();
- InstructionsBuilder instructionsBuilder = new InstructionsBuilder();
- List<Instruction> instructions = new ArrayList<>();
- InstructionBuilder instructionBuilder = new InstructionBuilder();
- instructionBuilder.setInstruction(applyActionsCase);
- instructionBuilder.setOrder(0);
- instructionBuilder.setKey(new InstructionKey(0));
- instructions.add(instructionBuilder.build());
- // Add InstructionBuilder to the Instruction(s)Builder List
- instructionsBuilder.setInstruction(instructions);
- // Add InstructionsBuilder to FlowBuilder
- flowBuilder.setInstructions(instructionsBuilder.build());
-
- return flowBuilder;
-
- }
-
- /*
- * (Table:EgressAclLearnService) EgressACL Learning
- * Match: reg6 = LearnConstants.NxmOfFieldType.NXM_NX_REG6
- * Action: learn and resubmit to next table
- * "table=40,dl_src=fa:16:3e:d3:bb:8a,tcp,priority=61002,tcp_dst=22,actions=learn(table=39,idle_timeout=300,fin_idle_timeout=0,
- * fin_hard_timeout=0,priority=61010, cookie=0x6900000,eth_type=0x800,nw_proto=6, NXM_OF_IP_SRC[]=NXM_OF_IP_DST[],NXM_OF_IP_DST[]=NXM_OF_IP_SRC[],
- * NXM_OF_UDP_SRC[]=NXM_OF_UDP_DST[],NXM_OF_UDP_DST[]=NXM_OF_UDP_SRC[],load:0x1->NXM_NX_REG6[0..7]),resubmit(,50)"
- */
- public static FlowBuilder programEgressAclLearnRuleForIcmp(FlowBuilder flowBuilder,
- String icmpType, String icmpCode) {
- List<Action> listAction = new ArrayList<>();
-
- String[] header = new String[] {
- String.valueOf(NetvirtProvidersProvider.getSecurityGroupDefaultIdleTimeout()),
- String.valueOf(NetvirtProvidersProvider.getSecurityGroupDefaultHardTimeout()),
- LearnConstants.LEARN_PRIORITY,
- "0",
- LearnConstants.DELETE_LEARNED_FLAG_VALUE,
- String.valueOf(LEARN_TABLE_ID),
- "0",
- "0"
- };
-
- String[][] flowMod = new String[7][];
- //eth_type=0x800
- flowMod[0] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_VALUE.name(),
- Integer.toString(LearnConstants.ETHTYPE_IPV4),
- LearnConstants.NxmOfFieldType.NXM_OF_ETH_TYPE.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_ETH_TYPE.getFlowModHeaderLen() };
- //nw_proto=1
- flowMod[1] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_VALUE.name(),
- Integer.toString(LearnConstants.IP_PROT_ICMP),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_PROTO.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_PROTO.getFlowModHeaderLen() };
- //NXM_OF_IP_SRC[]=NXM_OF_IP_DST[]
- flowMod[2] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_FIELD.name(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_DST.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_SRC.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_DST.getFlowModHeaderLen()};
- // NXM_OF_IP_DST[]=NXM_OF_IP_SRC[]
- flowMod[3] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_FIELD.name(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_SRC.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_DST.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_SRC.getFlowModHeaderLen()};
- //icmp_type=0
- flowMod[4] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_VALUE.name(),
- icmpType,
- LearnConstants.NxmOfFieldType.NXM_OF_ICMP_TYPE.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_ICMP_TYPE.getFlowModHeaderLen()};
- //icmp_code=0
- flowMod[5] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_VALUE.name(),
- icmpCode,
- LearnConstants.NxmOfFieldType.NXM_OF_ICMP_CODE.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_ICMP_CODE.getFlowModHeaderLen()};
- flowMod[6] = new String[] {
- LearnConstants.LearnFlowModsType.COPY_FROM_VALUE.name(), LearnConstants.LEARN_MATCH_REG_VALUE,
- LearnConstants.NxmOfFieldType.NXM_NX_REG6.getHexType(), "8" };
- listAction.add(buildAction(0, header, flowMod));
- ActionBuilder ab = new ActionBuilder();
- ab = new ActionBuilder();
- ab.setAction(createResubmitActions());
- ab.setKey(new ActionKey(1));
- listAction.add(ab.build());
- ApplyActions applyActions = new ApplyActionsBuilder().setAction(listAction).build();
- ApplyActionsCase applyActionsCase = new ApplyActionsCaseBuilder().setApplyActions(applyActions).build();
- InstructionsBuilder instructionsBuilder = new InstructionsBuilder();
- List<Instruction> instructions = new ArrayList<>();
- InstructionBuilder instructionBuilder = new InstructionBuilder();
- instructionBuilder.setInstruction(applyActionsCase);
- instructionBuilder.setOrder(0);
- instructionBuilder.setKey(new InstructionKey(0));
- instructions.add(instructionBuilder.build());
- // Add InstructionBuilder to the Instruction(s)Builder List
- instructionsBuilder.setInstruction(instructions);
-
- // Add InstructionsBuilder to FlowBuilder
- flowBuilder.setInstructions(instructionsBuilder.build());
-
- return flowBuilder;
- }
-
- /*
- * build Action
- *
- * copy from org.opendaylight.genius.mdsalutil.ActionType.learn
- */
- private static Action buildAction(int newActionKey, String[] header, String[][] actionValues) {
- NxLearnBuilder learnBuilder = new NxLearnBuilder();
- learnBuilder.setIdleTimeout(Integer.parseInt(header[0]));
- learnBuilder.setHardTimeout(Integer.parseInt(header[1]));
- learnBuilder.setPriority(Integer.parseInt(header[2]));
- learnBuilder.setCookie(BigInteger.valueOf(Long.valueOf(header[3])));
- learnBuilder.setFlags(Integer.parseInt(header[4]));
- learnBuilder.setTableId(Short.parseShort(header[5]));
- learnBuilder.setFinIdleTimeout(Integer.parseInt(header[6]));
- learnBuilder.setFinHardTimeout(Integer.parseInt(header[7]));
-
- List<FlowMods> flowModsList = new ArrayList<>();
- for(String[] values : actionValues) {
- if(LearnFlowModsType.MATCH_FROM_FIELD.name().equals(values[0])) {
- FlowModAddMatchFromFieldBuilder builder = new FlowModAddMatchFromFieldBuilder();
- builder.setSrcField(Long.decode(values[1]));
- builder.setSrcOfs(0);
- builder.setDstField(Long.decode(values[2]));
- builder.setDstOfs(0);
- builder.setFlowModNumBits(Integer.parseInt(values[3]));
-
- FlowModsBuilder flowModsBuilder = new FlowModsBuilder();
- FlowModAddMatchFromFieldCaseBuilder caseBuilder = new FlowModAddMatchFromFieldCaseBuilder();
- caseBuilder.setFlowModAddMatchFromField(builder.build());
- flowModsBuilder.setFlowModSpec(caseBuilder.build());
- flowModsList.add(flowModsBuilder.build());
- } else if (LearnFlowModsType.MATCH_FROM_VALUE.name().equals(values[0])) {
- FlowModAddMatchFromValueBuilder builder = new FlowModAddMatchFromValueBuilder();
- builder.setValue(Integer.parseInt(values[1]));
- builder.setSrcField(Long.decode(values[2]));
- builder.setSrcOfs(0);
- builder.setFlowModNumBits(Integer.parseInt(values[3]));
-
- FlowModsBuilder flowModsBuilder = new FlowModsBuilder();
- FlowModAddMatchFromValueCaseBuilder caseBuilder = new FlowModAddMatchFromValueCaseBuilder();
- caseBuilder.setFlowModAddMatchFromValue(builder.build());
- flowModsBuilder.setFlowModSpec(caseBuilder.build());
- flowModsList.add(flowModsBuilder.build());
- } else if (LearnFlowModsType.COPY_FROM_FIELD.name().equals(values[0])) {
- FlowModCopyFieldIntoFieldBuilder builder = new FlowModCopyFieldIntoFieldBuilder();
- builder.setSrcField(Long.decode(values[1]));
- builder.setSrcOfs(0);
- builder.setDstField(Long.decode(values[2]));
- builder.setDstOfs(0);
- builder.setFlowModNumBits(Integer.parseInt(values[3]));
-
- FlowModsBuilder flowModsBuilder = new FlowModsBuilder();
- FlowModCopyFieldIntoFieldCaseBuilder caseBuilder = new FlowModCopyFieldIntoFieldCaseBuilder();
- caseBuilder.setFlowModCopyFieldIntoField(builder.build());
- flowModsBuilder.setFlowModSpec(caseBuilder.build());
- flowModsList.add(flowModsBuilder.build());
- } else if (LearnFlowModsType.COPY_FROM_VALUE.name().equals(values[0])) {
- FlowModCopyValueIntoFieldBuilder builder = new FlowModCopyValueIntoFieldBuilder();
- builder.setValue(Integer.parseInt(values[1]));
- builder.setDstField(Long.decode(values[2]));
- builder.setDstOfs(0);
- builder.setFlowModNumBits(Integer.parseInt(values[3]));
-
- FlowModsBuilder flowModsBuilder = new FlowModsBuilder();
- FlowModCopyValueIntoFieldCaseBuilder caseBuilder = new FlowModCopyValueIntoFieldCaseBuilder();
- caseBuilder.setFlowModCopyValueIntoField(builder.build());
- flowModsBuilder.setFlowModSpec(caseBuilder.build());
- flowModsList.add(flowModsBuilder.build());
- } else if (LearnFlowModsType.OUTPUT_TO_PORT.name().equals(values[0])) {
- FlowModOutputToPortBuilder builder = new FlowModOutputToPortBuilder();
- builder.setSrcField(Long.decode(values[1]));
- builder.setSrcOfs(0);
- builder.setFlowModNumBits(Integer.parseInt(values[2]));
-
- FlowModsBuilder flowModsBuilder = new FlowModsBuilder();
- FlowModOutputToPortCaseBuilder caseBuilder = new FlowModOutputToPortCaseBuilder();
- caseBuilder.setFlowModOutputToPort(builder.build());
- flowModsBuilder.setFlowModSpec(caseBuilder.build());
- flowModsList.add(flowModsBuilder.build());
- }
- }
- learnBuilder.setFlowMods(flowModsList);
-
- ActionBuilder abExt = new ActionBuilder();
- abExt.setKey(new ActionKey(newActionKey));
-
- abExt.setAction(new NxActionLearnNodesNodeTableFlowApplyActionsCaseBuilder()
- .setNxLearn(learnBuilder.build()).build());
- return abExt.build();
- }
-
- private static org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action createResubmitActions() {
-
- NxResubmitBuilder gttb = new NxResubmitBuilder();
- gttb.setTable(RESUBMIT_TABLE_ID);
-
- // Wrap our Apply Action in an InstructionBuilder
- return (new NxActionResubmitRpcAddGroupCaseBuilder().setNxResubmit(gttb.build())).build();
- }
-}
+++ /dev/null
-/*
- * Copyright © 2014, 2017 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services;
-
-import java.net.Inet4Address;
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.List;
-import java.util.HashMap;
-import java.util.Map;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-import org.opendaylight.netvirt.openstack.netvirt.api.EgressAclProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.LearnConstants;
-import org.opendaylight.netvirt.openstack.netvirt.api.SecurityGroupCacheManger;
-import org.opendaylight.netvirt.openstack.netvirt.api.SecurityServicesManager;
-import org.opendaylight.netvirt.openstack.netvirt.providers.ConfigInterface;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityGroup;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityRule;
-import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSecurityRuleCRUD;
-import org.opendaylight.netvirt.utils.mdsal.openflow.ActionUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.FlowUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.InstructionUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.MatchUtils;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Prefix;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv6Prefix;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class EgressAclService extends AbstractAclService implements EgressAclProvider, ConfigInterface {
- private static final Logger LOG = LoggerFactory.getLogger(EgressAclService.class);
- private static final int DHCP_SOURCE_PORT = 67;
- private static final int DHCP_DESTINATION_PORT = 68;
- private static final int DHCPV6_SOURCE_PORT = 547;
- private static final int DHCPV6_DESTINATION_PORT = 546;
-
- public EgressAclService() {
- super(Service.EGRESS_ACL);
- }
-
- public EgressAclService(Service service) {
- super(service);
- }
-
- @Override
- public void programPortSecurityGroup(Long dpid, String segmentationId, String attachedMac, long localPort,
- NeutronSecurityGroup securityGroup, String portUuid, NodeId nodeId, boolean write) {
-
- LOG.trace("programPortSecurityGroup: neutronSecurityGroup: {} ", securityGroup);
- if (securityGroup == null ) {
- return;
- }
-
- List<NeutronSecurityRule> portSecurityList = getSecurityRulesforGroup(securityGroup);
- if (portSecurityList == null) {
- return;
- }
-
- /* Iterate over the Port Security Rules in the Port Security Group bound to the port*/
- Map <String, List<Neutron_IPs>> secGroupRemoteIPMap = new HashMap <String, List<Neutron_IPs>>();
- for (NeutronSecurityRule portSecurityRule : portSecurityList) {
-
- /**
- * Neutron Port Security Acl "egress" and "IPv4"
- * Check that the base conditions for flow based Port Security are true:
- * Port Security Rule Direction ("egress") and Protocol ("IPv4")
- * Neutron defines the direction "ingress" as the vSwitch to the VM as defined in:
- * http://docs.openstack.org/api/openstack-network/2.0/content/security_groups.html
- *
- */
-
- if (portSecurityRule == null
- || portSecurityRule.getSecurityRuleEthertype() == null
- || portSecurityRule.getSecurityRuleDirection() == null) {
- continue;
- }
-
- if (NeutronSecurityRule.DIRECTION_EGRESS.equals(portSecurityRule.getSecurityRuleDirection())) {
- LOG.debug("programPortSecurityGroup: Acl Rule matching IP and ingress is: {} ", portSecurityRule);
- String remoteSgUuid = portSecurityRule.getSecurityRemoteGroupID();
- if (null != remoteSgUuid) {
- //Remote Security group is selected
- List<Neutron_IPs> remoteSrcAddressList = secGroupRemoteIPMap.get(remoteSgUuid);
- if (remoteSrcAddressList == null) {
- remoteSrcAddressList = securityServicesManager
- .getVmListForSecurityGroup(portUuid, remoteSgUuid);
- secGroupRemoteIPMap.put(remoteSgUuid, remoteSrcAddressList);
- }
- for (Neutron_IPs vmIp :remoteSrcAddressList ) {
- programPortSecurityRule(dpid, segmentationId, attachedMac, portSecurityRule, vmIp, write);
- }
- if (write) {
- securityGroupCacheManger.addToCache(remoteSgUuid, portUuid, nodeId);
- } else {
- securityGroupCacheManger.removeFromCache(remoteSgUuid,
- portUuid, nodeId);
- }
- } else {
- programPortSecurityRule(dpid, segmentationId, attachedMac, portSecurityRule, null, write);
- }
- }
- }
- }
-
- @Override
- public void programPortSecurityRule(Long dpid, String segmentationId, String attachedMac,
- NeutronSecurityRule portSecurityRule, Neutron_IPs vmIp, boolean write) {
- String securityRuleEtherType = portSecurityRule.getSecurityRuleEthertype();
- boolean isIpv6 = NeutronSecurityRule.ETHERTYPE_IPV6.equals(securityRuleEtherType);
- if (!isIpv6 && !NeutronSecurityRule.ETHERTYPE_IPV4.equals(securityRuleEtherType)) {
- LOG.debug("programPortSecurityRule: SecurityRuleEthertype {} does not match IPv4/v6.",
- securityRuleEtherType);
- return;
- }
-
- String ipaddress = null;
- if (null != vmIp) {
- ipaddress = vmIp.getIpAddress();
- try {
- InetAddress address = InetAddress.getByName(ipaddress);
- if (isIpv6 && address instanceof Inet4Address || !isIpv6 && address instanceof Inet6Address) {
- LOG.debug("programPortSecurityRule: Remote vmIP {} does not match with "
- + "SecurityRuleEthertype {}.", ipaddress, securityRuleEtherType);
- return;
- }
- } catch (UnknownHostException e) {
- LOG.warn("Invalid IP address {}", ipaddress, e);
- return;
- }
- }
- if (null == portSecurityRule.getSecurityRuleProtocol()
- || portSecurityRule.getSecurityRuleProtocol().equals(MatchUtils.ANY_PROTOCOL)) {
- egressAclIp(dpid, isIpv6, segmentationId, attachedMac, portSecurityRule, ipaddress, write);
- if (NeutronSecurityRule.ETHERTYPE_IPV4.equals(portSecurityRule.getSecurityRuleEthertype())) {
- egressAclTcp(dpid, segmentationId, attachedMac, TCP_SECURITY_GROUP_RULE_IPv4_ANY, ipaddress, write);
- egressAclUdp(dpid, segmentationId, attachedMac, UDP_SECURITY_GROUP_RULE_IPv4_ANY, ipaddress, write);
- egressAclIcmp(dpid, segmentationId, attachedMac, ICMP_SECURITY_GROUP_RULE_IPv4_ANY, ipaddress, write);
- }
- } else {
- switch (portSecurityRule.getSecurityRuleProtocol()) {
- case MatchUtils.TCP:
- case MatchUtils.TCP_PROTOCOL:
- LOG.debug("programPortSecurityRule: Rule matching TCP", portSecurityRule);
- egressAclTcp(dpid, segmentationId, attachedMac, portSecurityRule, ipaddress, write);
- break;
- case MatchUtils.UDP:
- case MatchUtils.UDP_PROTOCOL:
- LOG.debug("programPortSecurityRule: Rule matching UDP", portSecurityRule);
- egressAclUdp(dpid, segmentationId, attachedMac, portSecurityRule, ipaddress, write);
- break;
- case MatchUtils.ICMP:
- case MatchUtils.ICMPV6:
- case MatchUtils.ICMP_PROTOCOL:
- LOG.debug("programPortSecurityRule: Rule matching ICMP", portSecurityRule);
- egressAclIcmp(dpid, segmentationId, attachedMac, portSecurityRule, ipaddress, write);
- break;
- default:
- LOG.info("programPortSecurityAcl: Protocol is not TCP/UDP/ICMP but other "
- + "protocol = ", portSecurityRule.getSecurityRuleProtocol());
- egressOtherProtocolAclHandler(dpid, segmentationId, attachedMac,
- portSecurityRule, ipaddress, write, isIpv6);
- break;
- }
- }
- }
-
- private void egressOtherProtocolAclHandler(Long dpidLong, String segmentationId, String srcMac,
- NeutronSecurityRule portSecurityRule, String dstAddress,
- boolean write, boolean isIpv6) {
- MatchBuilder matchBuilder = new MatchBuilder();
- String flowId = "Egress_Other_" + segmentationId + "_" + srcMac + "_";
- matchBuilder = MatchUtils.createV4EtherMatchWithType(matchBuilder, srcMac, null, MatchUtils.ETHERTYPE_IPV4);
- short proto = 0;
- try {
- Integer protocol = new Integer(portSecurityRule.getSecurityRuleProtocol());
- proto = protocol.shortValue();
- flowId = flowId + proto;
- } catch (NumberFormatException e) {
- LOG.error("Protocol value conversion failure", e);
- }
- matchBuilder = MatchUtils.createIpProtocolAndEthMatch(matchBuilder, proto, srcMac, null);
- if (null != dstAddress) {
- flowId = flowId + "_" + dstAddress;
- matchBuilder = MatchUtils.addRemoteIpPrefix(matchBuilder, null,
- MatchUtils.iPv4PrefixFromIPv4Address(dstAddress));
- } else if (null != portSecurityRule.getSecurityRuleRemoteIpPrefix()) {
- flowId = flowId + "_" + portSecurityRule.getSecurityRuleRemoteIpPrefix();
- if (isIpv6) {
- matchBuilder = MatchUtils.addRemoteIpv6Prefix(matchBuilder, null,
- new Ipv6Prefix(portSecurityRule.getSecurityRuleRemoteIpPrefix()));
- } else {
- if (!portSecurityRule.getSecurityRuleRemoteIpPrefix().contains("/0")) {
- matchBuilder = MatchUtils.addRemoteIpPrefix(matchBuilder, null,
- new Ipv4Prefix(portSecurityRule.getSecurityRuleRemoteIpPrefix()));
- }
- }
- }
- flowId = flowId + "_Permit";
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(
- flowId, Constants.PROTO_OTHER_MATCH_PRIORITY, matchBuilder, getTable());
- addInstructionWithConntrackCommit(flowBuilder, false);
- syncSecurityRuleFlow(flowBuilder, nodeBuilder, write);
- }
-
- @Override
- public void programFixedSecurityGroup(Long dpid, String segmentationId, String attachedMac,
- long localPort, List<Neutron_IPs> srcAddressList, boolean write) {
-
- egressAclDhcpAllowClientTrafficFromVm(dpid, write, localPort,
- Constants.PROTO_DHCP_CLIENT_TRAFFIC_MATCH_PRIORITY);
- egressAclDhcpv6AllowClientTrafficFromVm(dpid, write, localPort,
- Constants.PROTO_DHCP_CLIENT_TRAFFIC_MATCH_PRIORITY);
- programArpRule(dpid, segmentationId, localPort, attachedMac, write);
- if (securityServicesManager.isConntrackEnabled()) {
- programEgressAclFixedConntrackRule(dpid, segmentationId, localPort, attachedMac, write);
- } else {
- egressVMDrop(dpid, segmentationId, attachedMac, write, Constants.PROTO_PORT_DROP_PRIORITY);
- egressVMRegex(dpid, segmentationId, attachedMac, write, Constants.PROTO_REG6_MATCH_PRIORITY);
- }
- egressAclDhcpDropServerTrafficfromVm(dpid, localPort, write,
- Constants.PROTO_DHCP_CLIENT_SPOOF_MATCH_PRIORITY_DROP);
- egressAclDhcpv6DropServerTrafficfromVm(dpid, localPort, write,
- Constants.PROTO_DHCP_CLIENT_SPOOF_MATCH_PRIORITY_DROP);
- }
-
- private void egressVMRegex(Long dpidLong, String segmentationId, String srcMac,
- boolean write, Integer priority) {
- String flowName = "Egress_Regx_" + segmentationId + "_" + srcMac;
- MatchBuilder matchBuilder = new MatchBuilder();
- matchBuilder = MatchUtils.createV4EtherMatchWithoutType(matchBuilder, srcMac, null);
- MatchUtils.addNxRegMatch(matchBuilder,
- new MatchUtils.RegMatch(ClassifierService.REG_FIELD_6, ClassifierService.REG_VALUE_FROM_LOCAL));
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(flowName, priority, matchBuilder, getTable());
- addPipelineInstruction(flowBuilder, null, false);
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- syncFlow(flowBuilder, nodeBuilder, write);
- }
-
- private void egressVMDrop(Long dpidLong, String segmentationId, String srcMac,
- boolean write, Integer priority) {
- String flowName = "Egress_Drop_" + segmentationId + "_" + srcMac + "_DROP";
- MatchBuilder matchBuilder = new MatchBuilder();
- matchBuilder = MatchUtils.createV4EtherMatchWithoutType(matchBuilder, srcMac, null);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(flowName, priority, matchBuilder, getTable());
- addPipelineInstruction(flowBuilder, null, true);
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- syncFlow(flowBuilder, nodeBuilder, write);
- }
-
- private void programArpRule(Long dpid, String segmentationId, long localPort, String attachedMac, boolean write) {
- MatchBuilder matchBuilder = new MatchBuilder();
- String flowId = "Egress_ARP_" + segmentationId + "_" + localPort + "_";
- MatchUtils.createV4EtherMatchWithType(matchBuilder, null, null, MatchUtils.ETHERTYPE_ARP);
- MatchUtils.addArpMacMatch(matchBuilder, attachedMac, null);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(flowId, Constants.PROTO_MATCH_PRIORITY,
- matchBuilder, getTable());
- addPipelineInstruction(flowBuilder, null, false);
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpid);
- syncFlow(flowBuilder, nodeBuilder, write);
- }
-
- private void programEgressAclFixedConntrackRule(Long dpid,
- String segmentationId, long localPort, String attachMac, boolean write) {
- try {
- programConntrackUntrackRule(dpid, segmentationId, localPort, attachMac,
- Constants.CT_STATE_UNTRACKED_PRIORITY, write );
- programConntrackTrackedPlusEstRule(dpid, segmentationId, localPort,
- Constants.CT_STATE_TRACKED_EXIST_PRIORITY, write );
- programConntrackTrackedPlusRelRule(dpid, segmentationId, localPort,
- Constants.CT_STATE_TRACKED_EXIST_PRIORITY, write );
- programConntrackNewDropRule(dpid, segmentationId, localPort,
- Constants.CT_STATE_NEW_PRIORITY_DROP, write );
- programConntrackInvDropRule(dpid, segmentationId, localPort,
- Constants.CT_STATE_NEW_PRIORITY_DROP, write );
- LOG.info("programEgressAclFixedConntrackRule : default connection tracking rule are added.");
- } catch (Exception e) {
- LOG.error("Failed to add default conntrack rules : " , e);
- }
- }
-
- private void programConntrackUntrackRule(Long dpidLong, String segmentationId,
- long localPort, String attachMac, Integer priority, boolean write) {
- MatchBuilder matchBuilder = new MatchBuilder();
- String flowName = "Egress_Fixed_Conntrk_Untrk_" + segmentationId + "_" + localPort + "_";
- matchBuilder = MatchUtils.createV4EtherMatchWithType(matchBuilder, attachMac, null, MatchUtils.ETHERTYPE_IPV4);
- matchBuilder = MatchUtils.addCtState(matchBuilder, MatchUtils.UNTRACKED_CT_STATE,
- MatchUtils.UNTRACKED_CT_STATE_MASK);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(flowName, priority, matchBuilder, getTable());
- addInstructionWithConntrackRecirc(flowBuilder);
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- syncFlow(flowBuilder, nodeBuilder, write);
- }
-
- private void programConntrackTrackedPlusEstRule(Long dpidLong, String segmentationId,
- long localPort, Integer priority, boolean write) {
- MatchBuilder matchBuilder = new MatchBuilder();
- String flowName = "Egress_Fixed_Conntrk_TrkEst_" + segmentationId + "_" + localPort + "_";
- matchBuilder = MatchUtils.createInPortMatch(matchBuilder, dpidLong, localPort);
- matchBuilder = MatchUtils.addCtState(matchBuilder, MatchUtils.TRACKED_EST_CT_STATE,
- MatchUtils.TRACKED_CT_STATE_MASK);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(flowName, priority, matchBuilder, getTable());
- addPipelineInstruction(flowBuilder, null, false);
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- syncFlow(flowBuilder, nodeBuilder, write);
- }
-
- private void programConntrackTrackedPlusRelRule(Long dpidLong, String segmentationId,
- long localPort, Integer priority, boolean write) {
- MatchBuilder matchBuilder = new MatchBuilder();
- String flowName = "Egress_Fixed_Conntrk_TrkRel_" + segmentationId + "_" + localPort + "_";
- matchBuilder = MatchUtils.createInPortMatch(matchBuilder, dpidLong, localPort);
- matchBuilder = MatchUtils.addCtState(matchBuilder, MatchUtils.TRACKED_REL_CT_STATE,
- MatchUtils.TRACKED_CT_STATE_MASK);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(flowName, priority, matchBuilder, getTable());
- addPipelineInstruction(flowBuilder, null, false);
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- syncFlow(flowBuilder, nodeBuilder, write);
- }
-
- private void programConntrackNewDropRule(Long dpidLong, String segmentationId,
- long localPort, Integer priority, boolean write) {
- MatchBuilder matchBuilder = new MatchBuilder();
-
- String flowName = "Egress_Fixed_Conntrk_NewDrop_" + segmentationId + "_" + localPort + "_";
- matchBuilder = MatchUtils.createInPortMatch(matchBuilder, dpidLong, localPort);
- matchBuilder = MatchUtils.addCtState(matchBuilder, MatchUtils.TRACKED_NEW_CT_STATE,
- MatchUtils.TRACKED_NEW_CT_STATE_MASK);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(flowName, priority, matchBuilder, getTable());
- addPipelineInstruction(flowBuilder, null, true);
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- syncFlow(flowBuilder, nodeBuilder, write);
- }
-
- private void programConntrackInvDropRule(Long dpidLong, String segmentationId,
- long localPort, Integer priority, boolean write) {
- MatchBuilder matchBuilder = new MatchBuilder();
- String flowName = "Egress_Fixed_Conntrk_InvDrop_" + segmentationId + "_" + localPort + "_";
- matchBuilder = MatchUtils.createInPortMatch(matchBuilder, dpidLong, localPort);
- matchBuilder = MatchUtils.addCtState(matchBuilder, MatchUtils.TRACKED_INV_CT_STATE,
- MatchUtils.TRACKED_INV_CT_STATE_MASK);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(flowName, priority, matchBuilder, getTable());
- addPipelineInstruction(flowBuilder, null, true);
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- syncFlow(flowBuilder, nodeBuilder, write);
- }
-
- /**
- * Allows IPv4/v6 packet egress from the src mac address.
- * @param dpidLong the dpid
- * @param isIpv6 whether the rule is for ipv6
- * @param segmentationId the segementation id
- * @param srcMac the src mac address
- * @param write add or remove
- */
- private void egressAclIp(Long dpidLong, boolean isIpv6, String segmentationId, String srcMac,
- NeutronSecurityRule portSecurityRule, String srcAddress, boolean write) {
- MatchBuilder matchBuilder = new MatchBuilder();
- String flowId = "Egress_IP" + segmentationId + "_" + srcMac + "_Permit_";
- if (isIpv6) {
- matchBuilder = MatchUtils.createV6EtherMatchWithType(matchBuilder, srcMac, null);
- } else {
- matchBuilder = MatchUtils.createV4EtherMatchWithType(matchBuilder, srcMac, null, MatchUtils.ETHERTYPE_IPV4);
- }
- if (null != srcAddress) {
- flowId = flowId + srcAddress;
- if (isIpv6) {
- matchBuilder = MatchUtils.addRemoteIpv6Prefix(matchBuilder,
- MatchUtils.iPv6PrefixFromIPv6Address(srcAddress), null);
- } else {
- matchBuilder = MatchUtils.addRemoteIpPrefix(matchBuilder,
- MatchUtils.iPv4PrefixFromIPv4Address(srcAddress), null);
- }
- } else if (null != portSecurityRule.getSecurityRuleRemoteIpPrefix()) {
- flowId = flowId + portSecurityRule.getSecurityRuleRemoteIpPrefix();
- if (isIpv6) {
- matchBuilder = MatchUtils.addRemoteIpv6Prefix(matchBuilder, null,
- new Ipv6Prefix(portSecurityRule.getSecurityRuleRemoteIpPrefix()));
- } else {
- // Fix: Bug 6473
- // IP match removed if CIDR created as 0.0.0.0/0 in openstack security rule
- if (!portSecurityRule.getSecurityRuleRemoteIpPrefix().contains("/0")) {
- matchBuilder = MatchUtils.addRemoteIpPrefix(matchBuilder, null,
- new Ipv4Prefix(portSecurityRule
- .getSecurityRuleRemoteIpPrefix()));
- }
- }
- } else {
- if (isIpv6) {
- flowId = flowId + "Ipv6";
- } else {
- flowId = flowId + "Ipv4";
- }
- }
- addConntrackMatch(matchBuilder, MatchUtils.TRACKED_NEW_CT_STATE, MatchUtils.TRACKED_NEW_CT_STATE_MASK);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(
- flowId, Constants.PROTO_IP_PORT_MATCH_PRIORITY, matchBuilder, getTable());
- addInstructionWithConntrackCommit(flowBuilder, false);
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- syncSecurityRuleFlow(flowBuilder, nodeBuilder, write);
- }
-
- /**
- * Creates a egress match with src macaddress. If dest address is specified
- * destination specific match will be created. Otherwise a match with a
- * CIDR will be created.
- * @param dpidLong the dpid
- * @param segmentationId the segmentation id
- * @param srcMac the source mac address.
- * @param portSecurityRule the security rule in the SG
- * @param dstAddress the destination IP address
- * @param write add or delete
- */
- private void egressAclTcp(Long dpidLong, String segmentationId, String srcMac,
- NeutronSecurityRule portSecurityRule, String dstAddress, boolean write) {
- LOG.debug("egressAclTcp: portSecurityRule {} ", portSecurityRule);
- boolean portRange = false;
- MatchBuilder matchBuilder = new MatchBuilder();
- String flowId = "Egress_TCP_" + segmentationId + "_" + srcMac + "_";
- boolean isIpv6 = NeutronSecurityRule.ETHERTYPE_IPV6.equals(portSecurityRule.getSecurityRuleEthertype());
- if (isIpv6) {
- matchBuilder = MatchUtils.createV6EtherMatchWithType(matchBuilder, srcMac, null);
- } else {
- matchBuilder = MatchUtils.createV4EtherMatchWithType(matchBuilder, srcMac, null, MatchUtils.ETHERTYPE_IPV4);
- }
-
- /* Custom TCP Match */
- if (portSecurityRule.getSecurityRulePortMin() != null && portSecurityRule.getSecurityRulePortMax() != null) {
- if (portSecurityRule.getSecurityRulePortMin().equals(portSecurityRule.getSecurityRulePortMax())) {
- flowId = flowId + portSecurityRule.getSecurityRulePortMin() + "_";
- matchBuilder = MatchUtils.addLayer4Match(matchBuilder, MatchUtils.TCP_SHORT, 0,
- portSecurityRule.getSecurityRulePortMin());
- } else if (portSecurityRule.getSecurityRulePortMin().equals(PORT_RANGE_MIN)
- && portSecurityRule.getSecurityRulePortMax().equals(PORT_RANGE_MAX)) {
- /* All TCP Match */
- flowId = flowId + "ALL" + "_";
- matchBuilder = MatchUtils.addLayer4Match(matchBuilder, MatchUtils.TCP_SHORT, 0, 0);
- } else {
- portRange = true;
- }
- } else if (portSecurityRule.getSecurityRulePortMin() == null
- && portSecurityRule.getSecurityRulePortMax() == null) {
- /* All TCP Match */
- flowId = flowId + "ALL" + "_";
- matchBuilder = MatchUtils.addLayer4Match(matchBuilder, MatchUtils.TCP_SHORT, 0, 0);
- }
- if (null != dstAddress) {
- flowId = flowId + dstAddress;
- if (isIpv6) {
- matchBuilder = MatchUtils.addRemoteIpv6Prefix(matchBuilder, null,
- MatchUtils.iPv6PrefixFromIPv6Address(dstAddress));
- } else {
- matchBuilder = MatchUtils.addRemoteIpPrefix(matchBuilder, null,
- MatchUtils.iPv4PrefixFromIPv4Address(dstAddress));
- }
- } else if (null != portSecurityRule.getSecurityRuleRemoteIpPrefix()) {
- flowId = flowId + portSecurityRule.getSecurityRuleRemoteIpPrefix();
- if (isIpv6) {
- matchBuilder = MatchUtils.addRemoteIpv6Prefix(matchBuilder, null,
- new Ipv6Prefix(portSecurityRule.getSecurityRuleRemoteIpPrefix()));
- } else {
- // Fix: Bug 6473
- // IP match removed if CIDR created as 0.0.0.0/0 in openstack security rule
- if (!portSecurityRule.getSecurityRuleRemoteIpPrefix().contains("/0")) {
- matchBuilder = MatchUtils.addRemoteIpPrefix(matchBuilder, null,
- new Ipv4Prefix(portSecurityRule
- .getSecurityRuleRemoteIpPrefix()));
- }
- }
- }
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- if (portRange) {
- Map<Integer, Integer> portMaskMap = MatchUtils
- .getLayer4MaskForRange(portSecurityRule.getSecurityRulePortMin(),
- portSecurityRule.getSecurityRulePortMax());
- for (Integer port: portMaskMap.keySet()) {
- String rangeflowId = flowId + port + "_" + portMaskMap.get(port);
- rangeflowId = rangeflowId + "_Permit";
- MatchUtils.addLayer4MatchWithMask(matchBuilder, MatchUtils.TCP_SHORT,
- 0, port, portMaskMap.get(port));
- addConntrackMatch(matchBuilder, MatchUtils.TRACKED_NEW_CT_STATE, MatchUtils.TRACKED_NEW_CT_STATE_MASK);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(
- rangeflowId, Constants.PROTO_PORT_MATCH_PRIORITY, matchBuilder, getTable());
- addInstructionWithLearnConntrackCommit(portSecurityRule, flowBuilder, null, null);
- syncSecurityRuleFlow(flowBuilder, nodeBuilder, write);
- }
- } else {
- flowId = flowId + "_Permit";
- addConntrackMatch(matchBuilder, MatchUtils.TRACKED_NEW_CT_STATE, MatchUtils.TRACKED_NEW_CT_STATE_MASK);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(flowId, Constants.PROTO_PORT_MATCH_PRIORITY,
- matchBuilder, getTable());
- addInstructionWithLearnConntrackCommit(portSecurityRule, flowBuilder, null, null);
- syncSecurityRuleFlow(flowBuilder, nodeBuilder, write);
- }
- }
-
- private void egressAclIcmp(Long dpidLong, String segmentationId, String srcMac,
- NeutronSecurityRule portSecurityRule, String dstAddress, boolean write) {
-
- boolean isIpv6 = NeutronSecurityRule.ETHERTYPE_IPV6.equals(portSecurityRule.getSecurityRuleEthertype());
- if (isIpv6) {
- egressAclIcmpV6(dpidLong, segmentationId, srcMac, portSecurityRule, dstAddress, write);
- } else {
- egressAclIcmpV4(dpidLong, segmentationId, srcMac, portSecurityRule, dstAddress, write);
- }
- }
-
- /**
- * Creates a icmp egress match with src macaddress. If dest address is specified
- * destination specific match will be created. Otherwise a match with a
- * CIDR will be created.
- * @param dpidLong the dpid
- * @param segmentationId the segmentation id
- * @param srcMac the source mac address.
- * @param portSecurityRule the security rule in the SG
- * @param dstAddress the source IP address
- * @param write add or delete
- */
- private void egressAclIcmpV4(Long dpidLong, String segmentationId, String srcMac,
- NeutronSecurityRule portSecurityRule, String dstAddress, boolean write) {
-
- MatchBuilder matchBuilder = new MatchBuilder();
- boolean isIcmpAll = false;
- String flowId = "Egress_ICMP_" + segmentationId + "_" + srcMac + "_";
- matchBuilder = MatchUtils.createV4EtherMatchWithType(matchBuilder, srcMac, null, MatchUtils.ETHERTYPE_IPV4);
-
- /*Custom ICMP Match */
- if (portSecurityRule.getSecurityRulePortMin() != null
- && portSecurityRule.getSecurityRulePortMax() != null) {
- flowId = flowId + portSecurityRule.getSecurityRulePortMin().shortValue() + "_"
- + portSecurityRule.getSecurityRulePortMax().shortValue() + "_";
- matchBuilder = MatchUtils.createICMPv4Match(matchBuilder,
- portSecurityRule.getSecurityRulePortMin().shortValue(),
- portSecurityRule.getSecurityRulePortMax().shortValue());
- } else {
- isIcmpAll = true;
- }
-
- if (null != dstAddress) {
- flowId = flowId + dstAddress;
- matchBuilder = MatchUtils.addRemoteIpPrefix(matchBuilder, null,
- MatchUtils.iPv4PrefixFromIPv4Address(dstAddress));
- } else if (null != portSecurityRule.getSecurityRuleRemoteIpPrefix()) {
- flowId = flowId + portSecurityRule.getSecurityRuleRemoteIpPrefix();
- if (!portSecurityRule.getSecurityRuleRemoteIpPrefix().contains("/0")) {
- matchBuilder = MatchUtils.addRemoteIpPrefix(matchBuilder, null,
- new Ipv4Prefix(portSecurityRule.getSecurityRuleRemoteIpPrefix()));
- }
- }
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- if(isIcmpAll)
- {
- Map<Integer, String> map = LearnConstants.ICMP_TYPE_MAP;
- for(Map.Entry<Integer, String> entry : map.entrySet()) {
- matchBuilder = MatchUtils.createICMPv4Match(matchBuilder, entry.getKey().shortValue(), (short)0);
- String rangeflowId = flowId + entry.getKey() + "_" + entry.getValue() + "_";
- rangeflowId = rangeflowId + "_Permit";
- addConntrackMatch(matchBuilder, MatchUtils.TRACKED_NEW_CT_STATE, MatchUtils.TRACKED_NEW_CT_STATE_MASK);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(
- rangeflowId, Constants.PROTO_PORT_MATCH_PRIORITY, matchBuilder, getTable());
- addInstructionWithLearnConntrackCommit(portSecurityRule, flowBuilder, entry.getValue(), "0");
- syncSecurityRuleFlow(flowBuilder, nodeBuilder, write);
- }
- addIcmpFlow(nodeBuilder, portSecurityRule, segmentationId, srcMac, dstAddress, write);
- } else {
- flowId = flowId + "_Permit";
- addConntrackMatch(matchBuilder, MatchUtils.TRACKED_NEW_CT_STATE, MatchUtils.TRACKED_NEW_CT_STATE_MASK);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(
- flowId, Constants.PROTO_PORT_MATCH_PRIORITY, matchBuilder, getTable());
- String icmpType = LearnConstants.ICMP_TYPE_MAP.get(portSecurityRule.getSecurityRulePortMin());
- if (icmpType == null){
- icmpType = Integer.toString(portSecurityRule.getSecurityRulePortMin());
- }
- addInstructionWithLearnConntrackCommit(portSecurityRule, flowBuilder, icmpType,
- Integer.toString(portSecurityRule.getSecurityRulePortMax()));
- syncSecurityRuleFlow(flowBuilder, nodeBuilder, write);
- }
- }
-
- private void addIcmpFlow(NodeBuilder nodeBuilder, NeutronSecurityRule portSecurityRule, String segmentationId,
- String srcMac, String dstAddress, boolean write) {
- MatchBuilder matchBuilder = new MatchBuilder();
- String flowId = "Ingress_ICMP_" + segmentationId + "_" + srcMac + "_";
- matchBuilder = MatchUtils.createV4EtherMatchWithType(matchBuilder, srcMac, null, MatchUtils.ETHERTYPE_IPV4);
- flowId = flowId + "all" + "_" ;
- matchBuilder = MatchUtils.createICMPv4Match(matchBuilder, MatchUtils.ALL_ICMP, MatchUtils.ALL_ICMP);
- if (null != dstAddress) {
- flowId = flowId + dstAddress;
- matchBuilder = MatchUtils.addRemoteIpPrefix(matchBuilder, null,
- MatchUtils.iPv4PrefixFromIPv4Address(dstAddress));
- } else if (null != portSecurityRule.getSecurityRuleRemoteIpPrefix()) {
- flowId = flowId + portSecurityRule.getSecurityRuleRemoteIpPrefix();
- if (!portSecurityRule.getSecurityRuleRemoteIpPrefix().contains("/0")) {
- matchBuilder = MatchUtils.addRemoteIpPrefix(matchBuilder, null,
- new Ipv4Prefix(portSecurityRule.getSecurityRuleRemoteIpPrefix()));
- }
- }
- /* All ICMP Match */
- matchBuilder = MatchUtils.createICMPv4Match(matchBuilder, MatchUtils.ALL_ICMP, MatchUtils.ALL_ICMP);
- String rangeflowId = flowId;
- addConntrackMatch(matchBuilder, MatchUtils.TRACKED_NEW_CT_STATE, MatchUtils.TRACKED_NEW_CT_STATE_MASK);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(
- rangeflowId, Constants.PROTO_PORT_ICMP_MATCH_PRIORITY, matchBuilder, getTable());
- addPipelineInstruction(flowBuilder, null, false);
- syncSecurityRuleFlow(flowBuilder, nodeBuilder, write);
- }
-
- /**
- * Creates a icmpv6 egress match with src macaddress. If dest address is specified
- * destination specific match will be created. Otherwise a match with a
- * CIDR will be created.
- * @param dpidLong the dpid
- * @param segmentationId the segmentation id
- * @param srcMac the source mac address.
- * @param portSecurityRule the security rule in the SG
- * @param dstAddress the source IP address
- * @param write add or delete
- */
- private void egressAclIcmpV6(Long dpidLong, String segmentationId, String srcMac,
- NeutronSecurityRule portSecurityRule, String dstAddress, boolean write) {
-
- MatchBuilder matchBuilder = new MatchBuilder();
- String flowId = "Egress_ICMP_" + segmentationId + "_" + srcMac + "_";
- matchBuilder = MatchUtils.createV6EtherMatchWithType(matchBuilder, srcMac, null);
-
- /*Custom ICMP Match */
- if (portSecurityRule.getSecurityRulePortMin() != null
- && portSecurityRule.getSecurityRulePortMax() != null) {
- flowId = flowId + portSecurityRule.getSecurityRulePortMin().shortValue() + "_"
- + portSecurityRule.getSecurityRulePortMax().shortValue() + "_";
- matchBuilder = MatchUtils.createICMPv6Match(matchBuilder,
- portSecurityRule.getSecurityRulePortMin().shortValue(),
- portSecurityRule.getSecurityRulePortMax().shortValue());
- } else {
- /* All ICMP Match */ // We are getting from neutron NULL for both min and max
- flowId = flowId + "all" + "_" ;
- matchBuilder = MatchUtils.createICMPv6Match(matchBuilder, MatchUtils.ALL_ICMP, MatchUtils.ALL_ICMP);
- }
- if (null != dstAddress) {
- flowId = flowId + dstAddress;
- matchBuilder = MatchUtils.addRemoteIpv6Prefix(matchBuilder, null,
- MatchUtils.iPv6PrefixFromIPv6Address(dstAddress));
- } else if (null != portSecurityRule.getSecurityRuleRemoteIpPrefix()) {
- flowId = flowId + portSecurityRule.getSecurityRuleRemoteIpPrefix();
- matchBuilder = MatchUtils.addRemoteIpv6Prefix(matchBuilder, null,
- new Ipv6Prefix(portSecurityRule.getSecurityRuleRemoteIpPrefix()));
- }
- flowId = flowId + "_Permit";
- addConntrackMatch(matchBuilder, MatchUtils.TRACKED_NEW_CT_STATE, MatchUtils.TRACKED_NEW_CT_STATE_MASK);
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(flowId, Constants.PROTO_PORT_MATCH_PRIORITY, matchBuilder, getTable());
- addInstructionWithConntrackCommit(flowBuilder, false);
- syncFlow(flowBuilder, nodeBuilder, write);
- }
-
- /**
- * Creates a egress match with src macaddress. If dest address is specified
- * destination specific match will be created. Otherwise a match with a
- * CIDR will be created.
- * @param dpidLong the dpid
- * @param segmentationId the segmentation id
- * @param srcMac the source mac address.
- * @param portSecurityRule the security rule in the SG
- * @param dstAddress the source IP address
- * @param write add or delete
- */
- private void egressAclUdp(Long dpidLong, String segmentationId, String srcMac,
- NeutronSecurityRule portSecurityRule, String dstAddress, boolean write) {
- LOG.debug("egressAclTcp: egressAclUdp {} ", portSecurityRule);
- boolean portRange = false;
- MatchBuilder matchBuilder = new MatchBuilder();
- String flowId = "Egress_UDP_" + segmentationId + "_" + srcMac + "_";
- boolean isIpv6 = NeutronSecurityRule.ETHERTYPE_IPV6.equals(portSecurityRule.getSecurityRuleEthertype());
- if (isIpv6) {
- matchBuilder = MatchUtils.createV6EtherMatchWithType(matchBuilder, srcMac, null);
- } else {
- matchBuilder = MatchUtils.createV4EtherMatchWithType(matchBuilder, srcMac, null, MatchUtils.ETHERTYPE_IPV4);
- }
-
- /* Custom UDP Match */
- if (portSecurityRule.getSecurityRulePortMin() != null && portSecurityRule.getSecurityRulePortMax() != null) {
- if (portSecurityRule.getSecurityRulePortMin().equals(portSecurityRule.getSecurityRulePortMax())) {
- flowId = flowId + portSecurityRule.getSecurityRulePortMin() + "_";
- matchBuilder = MatchUtils.addLayer4Match(matchBuilder, MatchUtils.UDP_SHORT, 0,
- portSecurityRule.getSecurityRulePortMin());
- } else if (portSecurityRule.getSecurityRulePortMin().equals(PORT_RANGE_MIN)
- && portSecurityRule.getSecurityRulePortMax().equals(PORT_RANGE_MAX)) {
- /* All UDP Match */
- flowId = flowId + "ALL" + "_";
- matchBuilder = MatchUtils.addLayer4Match(matchBuilder, MatchUtils.UDP_SHORT, 0, 0);
- } else {
- portRange = true;
- }
- } else if (portSecurityRule.getSecurityRulePortMin() == null
- && portSecurityRule.getSecurityRulePortMax() == null) {
- /* All UDP Match */
- flowId = flowId + "ALL" + "_";
- matchBuilder = MatchUtils.addLayer4Match(matchBuilder, MatchUtils.UDP_SHORT, 0, 0);
- }
- if (null != dstAddress) {
- flowId = flowId + dstAddress;
- if (isIpv6) {
- matchBuilder = MatchUtils.addRemoteIpv6Prefix(matchBuilder, null,
- MatchUtils.iPv6PrefixFromIPv6Address(dstAddress));
- } else {
- matchBuilder = MatchUtils.addRemoteIpPrefix(matchBuilder, null,
- MatchUtils.iPv4PrefixFromIPv4Address(dstAddress));
- }
- } else if (null != portSecurityRule.getSecurityRuleRemoteIpPrefix()) {
- flowId = flowId + portSecurityRule.getSecurityRuleRemoteIpPrefix();
- if (isIpv6) {
- matchBuilder = MatchUtils.addRemoteIpv6Prefix(matchBuilder, null,
- new Ipv6Prefix(portSecurityRule
- .getSecurityRuleRemoteIpPrefix()));
- } else {
- if (!portSecurityRule.getSecurityRuleRemoteIpPrefix().contains("/0")) {
- matchBuilder = MatchUtils.addRemoteIpPrefix(matchBuilder, null,
- new Ipv4Prefix(portSecurityRule
- .getSecurityRuleRemoteIpPrefix()));
- }
- }
- }
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- if (portRange) {
- Map<Integer, Integer> portMaskMap = MatchUtils
- .getLayer4MaskForRange(portSecurityRule.getSecurityRulePortMin(),
- portSecurityRule.getSecurityRulePortMax());
- for (Integer port: portMaskMap.keySet()) {
- String rangeflowId = flowId + port + "_" + portMaskMap.get(port) + "_";
- rangeflowId = rangeflowId + "_Permit";
- MatchUtils.addLayer4MatchWithMask(matchBuilder, MatchUtils.UDP_SHORT,
- 0, port, portMaskMap.get(port));
- addConntrackMatch(matchBuilder, MatchUtils.TRACKED_NEW_CT_STATE, MatchUtils.TRACKED_NEW_CT_STATE_MASK);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(rangeflowId, Constants.PROTO_PORT_MATCH_PRIORITY,
- matchBuilder, getTable());
- addInstructionWithLearnConntrackCommit(portSecurityRule, flowBuilder, null, null);
- syncSecurityRuleFlow(flowBuilder, nodeBuilder, write);
- }
- } else {
- flowId = flowId + "_Permit";
- addConntrackMatch(matchBuilder, MatchUtils.TRACKED_NEW_CT_STATE, MatchUtils.TRACKED_NEW_CT_STATE_MASK);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(flowId, Constants.PROTO_PORT_MATCH_PRIORITY,
- matchBuilder, getTable());
- addInstructionWithLearnConntrackCommit(portSecurityRule, flowBuilder, null, null);
- syncSecurityRuleFlow(flowBuilder, nodeBuilder, write);
- }
- }
-
- /**
- * Adds flow to allow any DHCP client traffic.
- *
- * @param dpidLong the dpid
- * @param write whether to write or delete the flow
- * @param localPort the local port.
- * @param priority the priority
- */
- private void egressAclDhcpAllowClientTrafficFromVm(Long dpidLong,
- boolean write, long localPort, Integer priority) {
- String flowName = "Egress_DHCP_Client_" + localPort + "_Permit_";
- MatchBuilder matchBuilder = new MatchBuilder();
- MatchUtils.createInPortMatch(matchBuilder, dpidLong, localPort);
- MatchUtils.createDhcpMatch(matchBuilder, DHCP_DESTINATION_PORT, DHCP_SOURCE_PORT);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(flowName, priority, matchBuilder, getTable());
- addPipelineInstruction(flowBuilder, null, false);
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- syncFlow(flowBuilder, nodeBuilder, write);
- }
-
- /**
- * Adds flow to allow any DHCP IPv6 client traffic.
- *
- * @param dpidLong the dpid
- * @param write whether to write or delete the flow
- * @param localPort the local port
- * @param priority the priority
- */
- private void egressAclDhcpv6AllowClientTrafficFromVm(Long dpidLong,
- boolean write, long localPort, Integer priority) {
- String flowName = "Egress_DHCPv6_Client_" + localPort + "_Permit_";
- MatchBuilder matchBuilder = new MatchBuilder();
- MatchUtils.createInPortMatch(matchBuilder, dpidLong, localPort);
- MatchUtils.createDhcpv6Match(matchBuilder, DHCPV6_DESTINATION_PORT, DHCPV6_SOURCE_PORT);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(flowName, priority, matchBuilder, getTable());
- addPipelineInstruction(flowBuilder, null, false);
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- syncFlow(flowBuilder, nodeBuilder, write);
- }
-
- /**
- * Adds rule to prevent DHCP spoofing by the vm attached to the port.
- *
- * @param dpidLong the dpid
- * @param localPort the local port
- * @param write is write or delete
- * @param priority the priority
- */
- private void egressAclDhcpDropServerTrafficfromVm(Long dpidLong, long localPort,
- boolean write, Integer priority) {
- String flowName = "Egress_DHCP_Server_" + localPort + "_DROP";
- MatchBuilder matchBuilder = new MatchBuilder();
- MatchUtils.createInPortMatch(matchBuilder, dpidLong, localPort);
- MatchUtils.createDhcpMatch(matchBuilder, DHCP_SOURCE_PORT, DHCP_DESTINATION_PORT);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(flowName, priority, matchBuilder, getTable());
- addPipelineInstruction(flowBuilder, null, true);
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- syncFlow(flowBuilder, nodeBuilder, write);
- }
-
- /**
- * Adds rule to prevent DHCPv6 spoofing by the vm attached to the port.
- *
- * @param dpidLong the dpid
- * @param localPort the local port
- * @param write is write or delete
- * @param priority the priority
- */
- private void egressAclDhcpv6DropServerTrafficfromVm(Long dpidLong, long localPort,
- boolean write, Integer priority) {
-
- String flowName = "Egress_DHCPv6_Server_" + "_" + localPort + "_DROP";
- MatchBuilder matchBuilder = new MatchBuilder();
- MatchUtils.createInPortMatch(matchBuilder, dpidLong, localPort);
- MatchUtils.createDhcpv6Match(matchBuilder, DHCPV6_SOURCE_PORT, DHCPV6_DESTINATION_PORT);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(flowName, priority, matchBuilder, getTable());
- addPipelineInstruction(flowBuilder, null, true);
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- syncFlow(flowBuilder, nodeBuilder, write);
- }
-
- /**
- * Adds rule to check legitimate ip/mac pair for each packet from the vm.
- *
- * @param dpidLong the dpid
- * @param localPort the local port
- * @param srcIp the vm ip address
- * @param attachedMac the vm mac address
- * @param priority the priority
- * @param write is write or delete
- */
- private void egressAclAllowTrafficFromVmIpMacPair(Long dpidLong, long localPort,
- String attachedMac, String srcIp,
- Integer priority, boolean write) {
- MatchBuilder matchBuilder = new MatchBuilder();
- MatchUtils.createSrcL3Ipv4MatchWithMac(matchBuilder, new Ipv4Prefix(srcIp), new MacAddress(attachedMac));
- MatchUtils.createInPortMatch(matchBuilder, dpidLong, localPort);
- LOG.debug("egressAclAllowTrafficFromVmIpMacPair: MatchBuilder contains: {}", matchBuilder);
- String flowName = "Egress_Allow_VM_IP_MAC" + "_" + localPort + attachedMac + "_Permit_";
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(flowName, priority, matchBuilder, getTable());
- addPipelineInstruction(flowBuilder, null, false);
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- syncFlow(flowBuilder, nodeBuilder, write);
- }
-
- /**
- * Adds rule to check legitimate ip/mac pair for each packet from the vm.
- *
- * @param dpidLong the dpid
- * @param localPort the local port
- * @param srcIp the vm ip address
- * @param attachedMac the vm mac address
- * @param priority the priority
- * @param write is write or delete
- */
- private void egressAclAllowTrafficFromVmIpV6MacPair(Long dpidLong, long localPort,
- String attachedMac, String srcIp,
- Integer priority, boolean write) {
- MatchBuilder matchBuilder = new MatchBuilder();
- MatchUtils.createSrcL3Ipv6MatchWithMac(matchBuilder, new Ipv6Prefix(srcIp), new MacAddress(attachedMac));
- MatchUtils.createInPortMatch(matchBuilder, dpidLong, localPort);
- LOG.debug("egressAclAllowTrafficFromVmIpMacPair: MatchBuilder contains: {}", matchBuilder);
- String flowName = "Egress_Allow_VM_IPv6_MAC" + "_" + localPort + attachedMac + "_Permit_";
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(flowName, priority, matchBuilder, getTable());
- addPipelineInstruction(flowBuilder, null, false);
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- syncFlow(flowBuilder, nodeBuilder, write);
- }
-
- private FlowBuilder addInstructionWithLearnConntrackCommit(NeutronSecurityRule portSecurityRule, FlowBuilder flowBuilder, String icmpType, String icmpCode) {
- InstructionBuilder instructionBuilder = null;
- if (securityServicesManager.isConntrackEnabled()) {
- Action conntrackAction = ActionUtils.nxConntrackAction(1, 0L, 0, (short)0xff);
- instructionBuilder = InstructionUtils
- .createInstructionBuilder(ActionUtils.conntrackActionBuilder(conntrackAction), 1, false);
- return addPipelineInstruction(flowBuilder, instructionBuilder, false);
- }
- if (portSecurityRule.getSecurityRuleProtocol().equalsIgnoreCase(MatchUtils.TCP)
- || portSecurityRule.getSecurityRuleProtocol().equalsIgnoreCase(MatchUtils.TCP_PROTOCOL)) {
- return EgressAclLearnServiceUtil.programEgressAclLearnRuleForTcp(flowBuilder);
- } else if (portSecurityRule.getSecurityRuleProtocol().equalsIgnoreCase(MatchUtils.UDP)
- || portSecurityRule.getSecurityRuleProtocol().equalsIgnoreCase(MatchUtils.UDP_PROTOCOL)) {
- return EgressAclLearnServiceUtil.programEgressAclLearnRuleForUdp(flowBuilder);
- } else if (portSecurityRule.getSecurityRuleProtocol().equalsIgnoreCase(MatchUtils.ICMP)
- || portSecurityRule.getSecurityRuleProtocol().equalsIgnoreCase(MatchUtils.ICMP_PROTOCOL)) {
- return EgressAclLearnServiceUtil.programEgressAclLearnRuleForIcmp(flowBuilder, icmpType, icmpCode);
- }
- return flowBuilder;
- }
-
- @Override
- public void setDependencies(BundleContext bundleContext, ServiceReference serviceReference) {
- super.setDependencies(bundleContext.getServiceReference(EgressAclProvider.class.getName()), this);
- securityServicesManager =
- (SecurityServicesManager) ServiceHelper.getGlobalInstance(SecurityServicesManager.class, this);
- securityGroupCacheManger =
- (SecurityGroupCacheManger) ServiceHelper.getGlobalInstance(SecurityGroupCacheManger.class, this);
- neutronSecurityRule = (INeutronSecurityRuleCRUD) ServiceHelper.getGlobalInstance(INeutronSecurityRuleCRUD.class, this);
- }
-
- @Override
- public void setDependencies(Object impl) {}
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services;
-
-import java.math.BigInteger;
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.util.ArrayList;
-import java.util.List;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.IcmpEchoProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.Status;
-import org.opendaylight.netvirt.openstack.netvirt.api.StatusCode;
-import org.opendaylight.netvirt.openstack.netvirt.providers.ConfigInterface;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.AbstractServiceInstance;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.netvirt.utils.mdsal.openflow.ActionUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.FlowUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.MatchUtils;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
-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.FlowBuilder;
-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.ApplyActionsCaseBuilder;
-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;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionKey;
-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.openflowjava.nx.match.rev140421.NxmNxReg;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg4;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg5;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.dst.choice.grouping.dst.choice.DstOfEthDstCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.src.choice.grouping.src.choice.SrcNxRegCaseBuilder;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * @author Josh Hershberg (jhershbe@redhat.com)
- */
-public class IcmpEchoResponderService extends AbstractServiceInstance implements IcmpEchoProvider, ConfigInterface {
- private static final Logger LOG = LoggerFactory.getLogger(IcmpEchoResponderService.class);
- public static final Class<? extends NxmNxReg> SRC_MAC_4_HIGH_BYTES_FIELD = NxmNxReg4.class;
- public static final Class<? extends NxmNxReg> SRC_MAC_2_LOW_BYTES_FIELD = NxmNxReg5.class;
-
- public IcmpEchoResponderService() {
- super(Service.ICMP_ECHO);
- }
-
- public IcmpEchoResponderService(Service service) {
- super(service);
- }
-
- @Override
- public Status programIcmpEchoEntry(Long dpid, String segmentationId, String macAddressStr, InetAddress ipAddress, Action action) {
-
- if (segmentationId == null) return new Status(StatusCode.BADREQUEST);
-
- if (ipAddress instanceof Inet6Address) {
- // WORKAROUND: For now ipv6 is not supported
- // TODO: implement ipv6 case
- LOG.debug("ipv6 address case is not implemented yet. dpid {} segmentationId {} macAddressStr, ipAddress {} action {}",
- dpid, segmentationId, macAddressStr, ipAddress, action);
- return new Status(StatusCode.NOTIMPLEMENTED);
- }
-
- MacAddress macAddress = new MacAddress(macAddressStr);
-
- programEntry(dpid, segmentationId, macAddress, ipAddress, true, action);
- programEntry(dpid, segmentationId, macAddress, ipAddress, false, action);
-
- // ToDo: WriteFlow/RemoveFlow should return something we can use to check success
- return new Status(StatusCode.SUCCESS);
- }
-
- private Status programEntry(long dpid, String segmentationId, MacAddress macAddress, InetAddress ipAddress, boolean isRouted, Action action) {
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = (isRouted ? "RoutedIcmpEchoResponder_" : "LanIcmpEchoResponder_")
- + segmentationId + "_" + ipAddress.getHostAddress();
-
- //The non-routed flow has an extra match condition and it must therefor be of a higher
- //prio to make sure we get a "best match" kind of logic between the two
- FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable()).setPriority(isRouted ? 2048 : 2049);
-
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpid);
-
- MatchBuilder matchBuilder = new MatchBuilder();
-
- MatchUtils.createTunnelIDMatch(matchBuilder, new BigInteger(segmentationId));
-
- // Match ICMP echo requests, type=8, code=0
- MatchUtils.createICMPv4Match(matchBuilder, (short) 8, (short) 0);
- MatchUtils.createDstL3IPv4Match(matchBuilder, MatchUtils.iPv4PrefixFromIPv4Address(ipAddress.getHostAddress()));
-
- if (!isRouted) {
- //packets that have been "routed" in table 60 (DVR) will have their src MAC in nxm_nx_reg4 and nxm_nx_reg5
- //here we check that nxm_nx_reg4 is empty to check whether the packet has *not* been router since its
- //destination is on the same LAN
- MatchUtils.addNxRegMatch(matchBuilder, new MatchUtils.RegMatch(SRC_MAC_4_HIGH_BYTES_FIELD, 0x0L));
- }
-
- flowBuilder.setMatch(matchBuilder.build());
-
- if (action.equals(Action.ADD)) {
- // Instructions List Stores Individual Instructions
- InstructionsBuilder isb = new InstructionsBuilder();
- List<Instruction> instructions = new ArrayList<>();
- InstructionBuilder ib = new InstructionBuilder();
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- ActionBuilder ab = new ActionBuilder();
- List<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action> actionList = new ArrayList<>();
-
- if (isRouted) {
- ab.setAction(
- ActionUtils.nxMoveRegAction(
- new SrcNxRegCaseBuilder().setNxReg(SRC_MAC_4_HIGH_BYTES_FIELD).build(),
- new DstOfEthDstCaseBuilder().setOfEthDst(true).build(),
- 0, 0, 31, false));
- ab.setOrder(actionList.size());
- ab.setKey(new ActionKey(actionList.size()));
- actionList.add(ab.build());
-
- ab.setAction(
- ActionUtils.nxMoveRegAction(
- new SrcNxRegCaseBuilder().setNxReg(SRC_MAC_2_LOW_BYTES_FIELD).build(),
- new DstOfEthDstCaseBuilder().setOfEthDst(true).build(),
- 0, 32, 47, false));
- ab.setOrder(actionList.size());
- ab.setKey(new ActionKey(actionList.size()));
- actionList.add(ab.build());
- } else {
- ab.setAction(ActionUtils.nxMoveEthSrcToEthDstAction());
- ab.setOrder(actionList.size());
- ab.setKey(new ActionKey(actionList.size()));
- actionList.add(ab.build());
- }
-
- // Set Eth Src
- ab.setAction(ActionUtils.setDlSrcAction(new MacAddress(macAddress)));
- ab.setOrder(actionList.size());
- ab.setKey(new ActionKey(actionList.size()));
- actionList.add(ab.build());
-
- // Move Ip Src to Ip Dst
- ab.setAction(ActionUtils.nxMoveIpSrcToIpDstAction());
- ab.setOrder(actionList.size());
- ab.setKey(new ActionKey(actionList.size()));
- actionList.add(ab.build());
-
- // Set Ip Src
- ab.setAction(ActionUtils.setNwSrcAction(new Ipv4Builder().setIpv4Address(
- MatchUtils.iPv4PrefixFromIPv4Address(ipAddress.getHostAddress())).build()));
- ab.setOrder(actionList.size());
- ab.setKey(new ActionKey(actionList.size()));
- actionList.add(ab.build());
-
- // Set the ICMP type to 0 (echo reply)
- ab.setAction(ActionUtils.setIcmpTypeAction((byte)0));
- ab.setOrder(actionList.size());
- ab.setKey(new ActionKey(actionList.size()));
- actionList.add(ab.build());
-
- // Output of InPort
- ab.setAction(ActionUtils.outputAction(new NodeConnectorId(
- nodeBuilder.getId().getValue() + ":INPORT")));
- ab.setOrder(actionList.size());
- ab.setKey(new ActionKey(actionList.size()));
- actionList.add(ab.build());
-
- // Create Apply Actions Instruction
- aab.setAction(actionList);
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
- ib.setOrder(0);
- ib.setKey(new InstructionKey(0));
- instructions.add(ib.build());
-
- flowBuilder.setInstructions(isb.setInstruction(instructions).build());
-
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
-
- // ToDo: WriteFlow/RemoveFlow should return something we can use to check success
- return new Status(StatusCode.SUCCESS);
- }
-
- @Override
- public void setDependencies(BundleContext bundleContext, ServiceReference serviceReference) {
- super.setDependencies(bundleContext.getServiceReference(IcmpEchoProvider.class.getName()), this);
- }
-
- @Override
- public void setDependencies(Object impl) {}
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services;
-
-import java.math.BigInteger;
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.ArrayList;
-import java.util.List;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.InboundNatProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.Status;
-import org.opendaylight.netvirt.openstack.netvirt.api.StatusCode;
-import org.opendaylight.netvirt.openstack.netvirt.providers.ConfigInterface;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.AbstractServiceInstance;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.netvirt.utils.mdsal.openflow.ActionUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.FlowUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.InstructionUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.MatchUtils;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Prefix;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.ActionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.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.list.Instruction;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg3;
-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;
-
-public class InboundNatService extends AbstractServiceInstance implements ConfigInterface, InboundNatProvider {
- private static final Logger LOG = LoggerFactory.getLogger(InboundNatService.class);
- public static final Class<? extends NxmNxReg> REG_FIELD = NxmNxReg3.class;
-
- public InboundNatService() {
- super(Service.INBOUND_NAT);
- }
-
- public InboundNatService(Service service) {
- super(service);
- }
-
- @Override
- public Status programIpRewriteRule(Long dpid, Long inPort, String destSegId, InetAddress matchAddress,
- InetAddress rewriteAddress, Action action) {
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpid);
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = "InboundNAT_" + inPort + "_" + destSegId + "_" + matchAddress.getHostAddress();
- FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable()).setPriority(1024);
-
- MatchBuilder matchBuilder = new MatchBuilder();
- MatchUtils.createInPortMatch(matchBuilder, dpid, inPort);
- MatchUtils.createDstL3IPv4Match(matchBuilder,
- MatchUtils.iPv4PrefixFromIPv4Address(matchAddress.getHostAddress()));
- flowBuilder.setMatch(matchBuilder.build());
-
- if (action.equals(Action.ADD)) {
- // Instructions List Stores Individual Instructions
- InstructionsBuilder isb = new InstructionsBuilder();
- List<Instruction> instructions = new ArrayList<>();
- InstructionBuilder ib = new InstructionBuilder();
-
- // Set register to indicate that rewrite took place
- ActionBuilder actionBuilder = new ActionBuilder();
- actionBuilder.setAction(ActionUtils.nxLoadRegAction(new DstNxRegCaseBuilder().setNxReg(REG_FIELD).build(),
- new BigInteger(destSegId)));
-
- // Set Dest IP address and set REG_FIELD
- InstructionUtils.createNwDstInstructions(ib,
- MatchUtils.iPv4PrefixFromIPv4Address(rewriteAddress.getHostAddress()), actionBuilder);
- ib.setOrder(0);
- ib.setKey(new InstructionKey(0));
- instructions.add(ib.build());
-
- // Goto Next Table
- ib = getMutablePipelineInstructionBuilder();
- ib.setOrder(1);
- ib.setKey(new InstructionKey(1));
- instructions.add(ib.build());
-
- flowBuilder.setInstructions(isb.setInstruction(instructions).build());
-
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
-
- // ToDo: WriteFlow/RemoveFlow should return something we can use to check success
- return new Status(StatusCode.SUCCESS);
- }
-
- @Override
- public Status programIpRewriteExclusion(Long dpid, String segmentationId, String excludedCidr,
- Action action) {
- String ipAddress = excludedCidr.substring(0, excludedCidr.indexOf("/"));
- InetAddress inetAddress;
- try {
- inetAddress = InetAddress.getByName(ipAddress);
- } catch (UnknownHostException e) {
- return new Status(StatusCode.BADREQUEST);
- }
- if (inetAddress instanceof Inet6Address) {
- // WORKAROUND: For now ipv6 is not supported
- // TODO: implement ipv6 cidr case
- LOG.debug("ipv6 cidr is not implemented yet. cidr {}",
- excludedCidr);
- return new Status(StatusCode.NOTIMPLEMENTED);
- }
-
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpid);
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = "InboundNATExclusion_" + segmentationId + "_" + excludedCidr;
- FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable()).setPriority(1024);
-
- MatchBuilder matchBuilder = new MatchBuilder();
- MatchUtils.createTunnelIDMatch(matchBuilder, new BigInteger(segmentationId));
-
- MatchUtils.createDstL3IPv4Match(matchBuilder, new Ipv4Prefix(excludedCidr));
- flowBuilder.setMatch(matchBuilder.build());
-
- if (action.equals(Action.ADD)) {
- // Instructions List Stores Individual Instructions
- InstructionsBuilder isb = new InstructionsBuilder();
- List<Instruction> instructions = new ArrayList<>();
- InstructionBuilder ib;
-
- // Goto Next Table
- ib = getMutablePipelineInstructionBuilder();
- ib.setOrder(0);
- ib.setKey(new InstructionKey(0));
- instructions.add(ib.build());
-
- flowBuilder.setInstructions(isb.setInstruction(instructions).build());
-
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
-
- // ToDo: WriteFlow/RemoveFlow should return something we can use to check success
- return new Status(StatusCode.SUCCESS);
- }
-
- @Override
- public void setDependencies(BundleContext bundleContext, ServiceReference serviceReference) {
- super.setDependencies(bundleContext.getServiceReference(InboundNatProvider.class.getName()), this);
- }
-
- @Override
- public void setDependencies(Object impl) {}
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 NEC Corporation 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.netvirt.openstack.netvirt.providers.openflow13.services;
-
-import java.math.BigInteger;
-import java.util.List;
-import java.util.ArrayList;
-
-
-
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.netvirt.openstack.netvirt.api.LearnConstants;
-import org.opendaylight.netvirt.openstack.netvirt.api.LearnConstants.LearnFlowModsType;
-import org.opendaylight.netvirt.openstack.netvirt.providers.NetvirtProvidersProvider;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
-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.flow.inventory.rev130819.tables.table.FlowBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.InstructionsBuilder;
-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.InstructionKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.add.group.input.buckets.bucket.action.action.NxActionResubmitRpcAddGroupCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.resubmit.grouping.NxResubmitBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.flow.mod.spec.flow.mod.spec.FlowModAddMatchFromFieldCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.flow.mod.spec.flow.mod.spec.FlowModAddMatchFromValueCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.flow.mod.spec.flow.mod.spec.FlowModCopyFieldIntoFieldCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.flow.mod.spec.flow.mod.spec.FlowModCopyValueIntoFieldCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.flow.mod.spec.flow.mod.spec.FlowModOutputToPortCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.flow.mod.spec.flow.mod.spec.flow.mod.add.match.from.field._case.FlowModAddMatchFromFieldBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.flow.mod.spec.flow.mod.spec.flow.mod.add.match.from.value._case.FlowModAddMatchFromValueBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.flow.mod.spec.flow.mod.spec.flow.mod.copy.field.into.field._case.FlowModCopyFieldIntoFieldBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.flow.mod.spec.flow.mod.spec.flow.mod.copy.value.into.field._case.FlowModCopyValueIntoFieldBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.flow.mod.spec.flow.mod.spec.flow.mod.output.to.port._case.FlowModOutputToPortBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nodes.node.table.flow.instructions.instruction.instruction.apply.actions._case.apply.actions.action.action.NxActionLearnNodesNodeTableFlowApplyActionsCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.learn.grouping.NxLearnBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.learn.grouping.nx.learn.FlowMods;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.learn.grouping.nx.learn.FlowModsBuilder;
-
-public class IngressAclLearnServiceUtil {
- private static final short LEARN_TABLE_ID = Service.ACL_LEARN_SERVICE.getTable();
- private static final short RESUBMIT_TABLE_ID = Service.OUTBOUND_NAT.getTable();
-
- /*
- * (Table:IngressAclLearnService) IngressAcl Learning
- * Match: reg6 = LearnConstants.NxmOfFieldType.NXM_NX_REG6
- * Action: learn and resubmit to next table
- * "table=90,dl_src=fa:16:3e:d3:bb:8a,tcp,priority=61002,tcp_dst=22,actions=learn(table=39,idle_timeout=18000,fin_idle_timeout=300,
- * fin_hard_timeout=0,priority=61010, cookie=0x6900000,eth_type=0x800,nw_proto=6, NXM_OF_IP_SRC[]=NXM_OF_IP_DST[],NXM_OF_IP_DST[]=NXM_OF_IP_SRC[],
- * NXM_OF_TCP_SRC[]=NXM_OF_TCP_DST[],NXM_OF_TCP_DST[]=NXM_OF_TCP_SRC[],load:0x1->NXM_NX_REG6[0..7]),resubmit(,100)"
- */
- public static FlowBuilder programIngressAclLearnRuleForTcp(FlowBuilder flowBuilder) {
- List<Action> listAction = new ArrayList<>();
-
- // Create learn action
- /*
- * learn header
- * 0 1 2 3 4 5 6 7 idleTO hardTO prio cook flags table finidle finhard
- *
- * learn flowmod
- * 0 1 2 3 learnFlowModType srcField dstField FlowModNumBits
- */
- /*String[] header = new String[] {
- "18000", "0", "61010", "0", "0", "39", "300", "0"
- };*/
- String[] header = new String[] {
- String.valueOf(NetvirtProvidersProvider.getSecurityGroupTcpIdleTimeout()),
- String.valueOf(NetvirtProvidersProvider.getSecurityGroupTcpHardTimeout()),
- LearnConstants.LEARN_PRIORITY,
- "0",
- LearnConstants.DELETE_LEARNED_FLAG_VALUE,
- String.valueOf(LEARN_TABLE_ID),
- String.valueOf(NetvirtProvidersProvider.getSecurityGroupTcpFinIdleTimeout()),
- String.valueOf(NetvirtProvidersProvider.getSecurityGroupTcpFinHardTimeout())
- };
-
- String[][] flowMod = new String[8][];
- //eth_type=0x800
- flowMod[0] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_VALUE.name(),
- Integer.toString(LearnConstants.ETHTYPE_IPV4),
- LearnConstants.NxmOfFieldType.NXM_OF_ETH_TYPE.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_ETH_TYPE.getFlowModHeaderLen() };
- flowMod[1] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_VALUE.name(),
- Integer.toString(LearnConstants.IP_PROT_TCP),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_PROTO.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_PROTO.getFlowModHeaderLen() };
- //nw_proto=6
- //NXM_OF_IP_SRC[]=NXM_OF_IP_DST[]
- flowMod[2] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_FIELD.name(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_DST.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_SRC.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_DST.getFlowModHeaderLen()};
- // NXM_OF_IP_DST[]=NXM_OF_IP_SRC[]
- flowMod[3] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_FIELD.name(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_SRC.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_DST.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_SRC.getFlowModHeaderLen()};
- //NXM_OF_TCP_SRC[]=NXM_OF_TCP_DST[]
- flowMod[4] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_FIELD.name(),
- LearnConstants.NxmOfFieldType.NXM_OF_TCP_DST.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_TCP_SRC.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_TCP_DST.getFlowModHeaderLen()};
- //NXM_OF_TCP_DST[]=NXM_OF_TCP_SRC[]
- flowMod[5] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_FIELD.name(),
- LearnConstants.NxmOfFieldType.NXM_OF_TCP_SRC.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_TCP_DST.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_TCP_SRC.getFlowModHeaderLen()};
- // NXM_NX_TUN_ID[]
- flowMod[6] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_FIELD.name(),
- LearnConstants.NxmOfFieldType.NXM_NX_TUN_ID.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_NX_TUN_ID.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_NX_TUN_ID.getFlowModHeaderLen() };
- flowMod[7] = new String[] {
- LearnConstants.LearnFlowModsType.COPY_FROM_VALUE.name(), "1",
- LearnConstants.NxmOfFieldType.NXM_NX_REG6.getHexType(), "8" };
- listAction.add(buildAction(0, header, flowMod));
- ActionBuilder ab = new ActionBuilder();
- ab = new ActionBuilder();
- ab.setAction(createResubmitActions());
- ab.setKey(new ActionKey(1));
- listAction.add(ab.build());
- ApplyActions applyActions = new ApplyActionsBuilder().setAction(listAction).build();
- ApplyActionsCase applyActionsCase = new ApplyActionsCaseBuilder().setApplyActions(applyActions).build();
- InstructionsBuilder instructionsBuilder = new InstructionsBuilder();
- List<Instruction> instructions = new ArrayList<>();
- InstructionBuilder instructionBuilder = new InstructionBuilder();
- instructionBuilder.setInstruction(applyActionsCase);
- instructionBuilder.setOrder(0);
- instructionBuilder.setKey(new InstructionKey(0));
- instructions.add(instructionBuilder.build());
- // Add InstructionBuilder to the Instruction(s)Builder List
- instructionsBuilder.setInstruction(instructions);
- // Add InstructionsBuilder to FlowBuilder
- flowBuilder.setInstructions(instructionsBuilder.build());
-
- return flowBuilder;
- }
-
- /*
- * (Table:IngressAclLearnService) IngressAcl Learning
- * Match: reg6 = LearnConstants.NxmOfFieldType.NXM_NX_REG6
- * Action: learn and resubmit to next table
- * "table=90,dl_src=fa:16:3e:d3:bb:8a,tcp,priority=61002,tcp_dst=22,actions=learn(table=39,idle_timeout=300,fin_idle_timeout=0,
- * fin_hard_timeout=0,priority=61010, cookie=0x6900000,eth_type=0x800,nw_proto=6, NXM_OF_IP_SRC[]=NXM_OF_IP_DST[],NXM_OF_IP_DST[]=NXM_OF_IP_SRC[],
- * NXM_OF_TCP_SRC[]=NXM_OF_TCP_DST[],NXM_OF_TCP_DST[]=NXM_OF_TCP_SRC[],load:0x1->NXM_NX_REG6[0..7]),resubmit(,100)"
- */
- public static FlowBuilder programIngressAclLearnRuleForUdp(FlowBuilder flowBuilder) {
- List<Action> listAction = new ArrayList<>();
-
- // Create learn action
- /*
- * learn header
- * 0 1 2 3 4 5 6 7 idleTO hardTO prio cook flags table finidle finhard
- *
- * learn flowmod
- * 0 1 2 3 learnFlowModType srcField dstField FlowModNumBits
- */
- /*String[] header = new String[] {
- "300", "0", "61010", "0", "0", "39", "0", "0"
- };*/
- String[] header = new String[] {
- String.valueOf(NetvirtProvidersProvider.getSecurityGroupUdpIdleTimeout()),
- String.valueOf(NetvirtProvidersProvider.getSecurityGroupUdpHardTimeout()),
- LearnConstants.LEARN_PRIORITY,
- "0",
- LearnConstants.DELETE_LEARNED_FLAG_VALUE,
- String.valueOf(LEARN_TABLE_ID),
- "0",
- "0"
- };
-
- String[][] flowMod = new String[8][];
- //eth_type=0x800
- flowMod[0] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_VALUE.name(),
- Integer.toString(LearnConstants.ETHTYPE_IPV4),
- LearnConstants.NxmOfFieldType.NXM_OF_ETH_TYPE.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_ETH_TYPE.getFlowModHeaderLen() };
- flowMod[1] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_VALUE.name(),
- Integer.toString(LearnConstants.IP_PROT_UDP),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_PROTO.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_PROTO.getFlowModHeaderLen() };
- //nw_proto=6
- //NXM_OF_IP_SRC[]=NXM_OF_IP_DST[]
- flowMod[2] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_FIELD.name(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_DST.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_SRC.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_DST.getFlowModHeaderLen()};
- // NXM_OF_IP_DST[]=NXM_OF_IP_SRC[]
- flowMod[3] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_FIELD.name(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_SRC.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_DST.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_SRC.getFlowModHeaderLen()};
- //NXM_OF_TCP_SRC[]=NXM_OF_TCP_DST[]
- flowMod[4] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_FIELD.name(),
- LearnConstants.NxmOfFieldType.NXM_OF_UDP_DST.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_UDP_SRC.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_UDP_DST.getFlowModHeaderLen()};
- //NXM_OF_TCP_DST[]=NXM_OF_TCP_SRC[]
- flowMod[5] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_FIELD.name(),
- LearnConstants.NxmOfFieldType.NXM_OF_UDP_SRC.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_UDP_DST.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_UDP_SRC.getFlowModHeaderLen()};
- // NXM_NX_TUN_ID[]
- flowMod[6] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_FIELD.name(),
- LearnConstants.NxmOfFieldType.NXM_NX_TUN_ID.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_NX_TUN_ID.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_NX_TUN_ID.getFlowModHeaderLen() };
- flowMod[7] = new String[] {
- LearnConstants.LearnFlowModsType.COPY_FROM_VALUE.name(), LearnConstants.LEARN_MATCH_REG_VALUE,
- LearnConstants.NxmOfFieldType.NXM_NX_REG6.getHexType(), "8" };
-
- listAction.add(buildAction(0, header, flowMod));
-
- ActionBuilder ab = new ActionBuilder();
- ab = new ActionBuilder();
- ab.setAction(createResubmitActions());
- ab.setKey(new ActionKey(1));
- listAction.add(ab.build());
-
- ApplyActions applyActions = new ApplyActionsBuilder().setAction(listAction).build();
- ApplyActionsCase applyActionsCase = new ApplyActionsCaseBuilder().setApplyActions(applyActions).build();
- InstructionsBuilder instructionsBuilder = new InstructionsBuilder();
- List<Instruction> instructions = new ArrayList<>();
- InstructionBuilder instructionBuilder = new InstructionBuilder();
- instructionBuilder.setInstruction(applyActionsCase);
- instructionBuilder.setOrder(0);
- instructionBuilder.setKey(new InstructionKey(0));
- instructions.add(instructionBuilder.build());
- // Add InstructionBuilder to the Instruction(s)Builder List
- instructionsBuilder.setInstruction(instructions);
- // Add InstructionsBuilder to FlowBuilder
- flowBuilder.setInstructions(instructionsBuilder.build());
-
- return flowBuilder;
- }
-
- /*
- * (Table:IngressAclLearnService) IngressAcl Learning
- * Match: reg6 = LearnConstants.NxmOfFieldType.NXM_NX_REG6
- * Action: learn and resubmit to next table
- * "table=90,dl_src=fa:16:3e:d3:bb:8a,tcp,priority=61002,tcp_dst=22,actions=learn(table=39,idle_timeout=300,fin_idle_timeout=0,
- * fin_hard_timeout=0,priority=61010, cookie=0x6900000,eth_type=0x800,nw_proto=6, NXM_OF_IP_SRC[]=NXM_OF_IP_DST[],NXM_OF_IP_DST[]=NXM_OF_IP_SRC[],
- * NXM_OF_TCP_SRC[]=NXM_OF_TCP_DST[],NXM_OF_TCP_DST[]=NXM_OF_TCP_SRC[],load:0x1->NXM_NX_REG6[0..7]),resubmit(,100)"
- */
- public static FlowBuilder programIngressAclLearnRuleForIcmp(FlowBuilder flowBuilder, String icmpType, String icmpCode) {
- //, Integer icmpCode,Integer icmpType
- List<Action> listAction = new ArrayList<>();
-
- String[] header = new String[] {
- String.valueOf(NetvirtProvidersProvider.getSecurityGroupDefaultIdleTimeout()),
- String.valueOf(NetvirtProvidersProvider.getSecurityGroupDefaultHardTimeout()),
- LearnConstants.LEARN_PRIORITY,
- "0",
- LearnConstants.DELETE_LEARNED_FLAG_VALUE,
- String.valueOf(LEARN_TABLE_ID),
- "0",
- "0"
- };
-
- String[][] flowMod = new String[7][];
- //eth_type=0x800
- flowMod[0] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_VALUE.name(),
- Integer.toString(LearnConstants.ETHTYPE_IPV4),
- LearnConstants.NxmOfFieldType.NXM_OF_ETH_TYPE.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_ETH_TYPE.getFlowModHeaderLen() };
- //nw_proto=1
- flowMod[1] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_VALUE.name(),
- Integer.toString(LearnConstants.IP_PROT_ICMP),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_PROTO.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_PROTO.getFlowModHeaderLen() };
- //NXM_OF_IP_SRC[]=NXM_OF_IP_DST[]
- flowMod[2] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_FIELD.name(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_DST.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_SRC.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_DST.getFlowModHeaderLen()};
- // NXM_OF_IP_DST[]=NXM_OF_IP_SRC[]
- flowMod[3] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_FIELD.name(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_SRC.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_DST.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_IP_SRC.getFlowModHeaderLen()};
- //icmp_code=0
- flowMod[4] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_VALUE.name(), icmpCode,
- LearnConstants.NxmOfFieldType.NXM_OF_ICMP_CODE.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_ICMP_CODE.getFlowModHeaderLen()};
- //icmp_type=0
- flowMod[5] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_VALUE.name(), icmpType,
- LearnConstants.NxmOfFieldType.NXM_OF_ICMP_TYPE.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_ICMP_TYPE.getFlowModHeaderLen()};
- flowMod[6] = new String[] {
- LearnConstants.LearnFlowModsType.COPY_FROM_VALUE.name(), LearnConstants.LEARN_MATCH_REG_VALUE,
- LearnConstants.NxmOfFieldType.NXM_NX_REG6.getHexType(), "8" };
- listAction.add(buildAction(0, header, flowMod));
- ActionBuilder ab = new ActionBuilder();
- ab = new ActionBuilder();
- ab.setAction(createResubmitActions());
- ab.setKey(new ActionKey(1));
- listAction.add(ab.build());
- ApplyActions applyActions = new ApplyActionsBuilder().setAction(listAction).build();
- ApplyActionsCase applyActionsCase = new ApplyActionsCaseBuilder().setApplyActions(applyActions).build();
- InstructionsBuilder instructionsBuilder = new InstructionsBuilder();
- List<Instruction> instructions = new ArrayList<>();
-
- InstructionBuilder instructionBuilder = new InstructionBuilder();
- instructionBuilder.setInstruction(applyActionsCase);
- instructionBuilder.setOrder(0);
- instructionBuilder.setKey(new InstructionKey(0));
- instructions.add(instructionBuilder.build());
- // Add InstructionBuilder to the Instruction(s)Builder List
- instructionsBuilder.setInstruction(instructions);
-
- // Add InstructionsBuilder to FlowBuilder
- flowBuilder.setInstructions(instructionsBuilder.build());
-
- return flowBuilder;
- }
-
- /*
- * build Action
- *
- * copy from org.opendaylight.genius.mdsalutil.ActionType.learn
- */
- private static Action buildAction(int newActionKey, String[] header, String[][] actionValues) {
- NxLearnBuilder learnBuilder = new NxLearnBuilder();
- learnBuilder.setIdleTimeout(Integer.parseInt(header[0]));
- learnBuilder.setHardTimeout(Integer.parseInt(header[1]));
- learnBuilder.setPriority(Integer.parseInt(header[2]));
- learnBuilder.setCookie(BigInteger.valueOf(Long.valueOf(header[3])));
- learnBuilder.setFlags(Integer.parseInt(header[4]));
- learnBuilder.setTableId(Short.parseShort(header[5]));
- learnBuilder.setFinIdleTimeout(Integer.parseInt(header[6]));
- learnBuilder.setFinHardTimeout(Integer.parseInt(header[7]));
-
- List<FlowMods> flowModsList = new ArrayList<>();
- for(String[] values : actionValues) {
- if(LearnFlowModsType.MATCH_FROM_FIELD.name().equals(values[0])) {
- FlowModAddMatchFromFieldBuilder builder = new FlowModAddMatchFromFieldBuilder();
- builder.setSrcField(Long.decode(values[1]));
- builder.setSrcOfs(0);
- builder.setDstField(Long.decode(values[2]));
- builder.setDstOfs(0);
- builder.setFlowModNumBits(Integer.parseInt(values[3]));
-
- FlowModsBuilder flowModsBuilder = new FlowModsBuilder();
- FlowModAddMatchFromFieldCaseBuilder caseBuilder = new FlowModAddMatchFromFieldCaseBuilder();
- caseBuilder.setFlowModAddMatchFromField(builder.build());
- flowModsBuilder.setFlowModSpec(caseBuilder.build());
- flowModsList.add(flowModsBuilder.build());
- } else if (LearnFlowModsType.MATCH_FROM_VALUE.name().equals(values[0])) {
- FlowModAddMatchFromValueBuilder builder = new FlowModAddMatchFromValueBuilder();
- builder.setValue(Integer.parseInt(values[1]));
- builder.setSrcField(Long.decode(values[2]));
- builder.setSrcOfs(0);
- builder.setFlowModNumBits(Integer.parseInt(values[3]));
-
- FlowModsBuilder flowModsBuilder = new FlowModsBuilder();
- FlowModAddMatchFromValueCaseBuilder caseBuilder = new FlowModAddMatchFromValueCaseBuilder();
- caseBuilder.setFlowModAddMatchFromValue(builder.build());
- flowModsBuilder.setFlowModSpec(caseBuilder.build());
- flowModsList.add(flowModsBuilder.build());
- } else if (LearnFlowModsType.COPY_FROM_FIELD.name().equals(values[0])) {
- FlowModCopyFieldIntoFieldBuilder builder = new FlowModCopyFieldIntoFieldBuilder();
- builder.setSrcField(Long.decode(values[1]));
- builder.setSrcOfs(0);
- builder.setDstField(Long.decode(values[2]));
- builder.setDstOfs(0);
- builder.setFlowModNumBits(Integer.parseInt(values[3]));
-
- FlowModsBuilder flowModsBuilder = new FlowModsBuilder();
- FlowModCopyFieldIntoFieldCaseBuilder caseBuilder = new FlowModCopyFieldIntoFieldCaseBuilder();
- caseBuilder.setFlowModCopyFieldIntoField(builder.build());
- flowModsBuilder.setFlowModSpec(caseBuilder.build());
- flowModsList.add(flowModsBuilder.build());
- } else if (LearnFlowModsType.COPY_FROM_VALUE.name().equals(values[0])) {
- FlowModCopyValueIntoFieldBuilder builder = new FlowModCopyValueIntoFieldBuilder();
- builder.setValue(Integer.parseInt(values[1]));
- builder.setDstField(Long.decode(values[2]));
- builder.setDstOfs(0);
- builder.setFlowModNumBits(Integer.parseInt(values[3]));
-
- FlowModsBuilder flowModsBuilder = new FlowModsBuilder();
- FlowModCopyValueIntoFieldCaseBuilder caseBuilder = new FlowModCopyValueIntoFieldCaseBuilder();
- caseBuilder.setFlowModCopyValueIntoField(builder.build());
- flowModsBuilder.setFlowModSpec(caseBuilder.build());
- flowModsList.add(flowModsBuilder.build());
- } else if (LearnFlowModsType.OUTPUT_TO_PORT.name().equals(values[0])) {
- FlowModOutputToPortBuilder builder = new FlowModOutputToPortBuilder();
- builder.setSrcField(Long.decode(values[1]));
- builder.setSrcOfs(0);
- builder.setFlowModNumBits(Integer.parseInt(values[2]));
-
- FlowModsBuilder flowModsBuilder = new FlowModsBuilder();
- FlowModOutputToPortCaseBuilder caseBuilder = new FlowModOutputToPortCaseBuilder();
- caseBuilder.setFlowModOutputToPort(builder.build());
- flowModsBuilder.setFlowModSpec(caseBuilder.build());
- flowModsList.add(flowModsBuilder.build());
- }
- }
- learnBuilder.setFlowMods(flowModsList);
-
- ActionBuilder abExt = new ActionBuilder();
- abExt.setKey(new ActionKey(newActionKey));
-
- abExt.setAction(new NxActionLearnNodesNodeTableFlowApplyActionsCaseBuilder()
- .setNxLearn(learnBuilder.build()).build());
- return abExt.build();
- }
-
- private static org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action createResubmitActions() {
-
- NxResubmitBuilder gttb = new NxResubmitBuilder();
- gttb.setTable(RESUBMIT_TABLE_ID);
-
- // Wrap our Apply Action in an InstructionBuilder
- return (new NxActionResubmitRpcAddGroupCaseBuilder().setNxResubmit(gttb.build())).build();
- }
-}
+++ /dev/null
-/*
- * Copyright © 2014, 2017 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services;
-
-import java.net.Inet4Address;
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.List;
-import java.util.HashMap;
-import java.util.Map;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-import org.opendaylight.netvirt.openstack.netvirt.api.IngressAclProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.SecurityGroupCacheManger;
-import org.opendaylight.netvirt.openstack.netvirt.api.SecurityServicesManager;
-import org.opendaylight.netvirt.openstack.netvirt.providers.ConfigInterface;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityGroup;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityRule;
-import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSecurityRuleCRUD;
-import org.opendaylight.netvirt.utils.mdsal.openflow.ActionUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.FlowUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.InstructionUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.MatchUtils;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Prefix;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv6Prefix;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionBuilder;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
-import org.opendaylight.netvirt.openstack.netvirt.api.LearnConstants;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class IngressAclService extends AbstractAclService implements IngressAclProvider, ConfigInterface {
- private static final Logger LOG = LoggerFactory.getLogger(IngressAclService.class);
-
- public IngressAclService() {
- super(Service.INGRESS_ACL);
- }
-
- public IngressAclService(Service service) {
- super(service);
- }
-
- @Override
- public void programPortSecurityGroup(Long dpid, String segmentationId, String attachedMac,
- long localPort, NeutronSecurityGroup securityGroup,
- String portUuid, NodeId nodeId, boolean write) {
-
- LOG.trace("programPortSecurityGroup neutronSecurityGroup: {} ", securityGroup);
- if (securityGroup == null) {
- return;
- }
-
- List<NeutronSecurityRule> portSecurityList = getSecurityRulesforGroup(securityGroup);
- if (portSecurityList == null) {
- return;
- }
-
- /* Iterate over the Port Security Rules in the Port Security Group bound to the port*/
- Map <String, List<Neutron_IPs>> secGroupRemoteIPMap = new HashMap <String, List<Neutron_IPs>>();
- for (NeutronSecurityRule portSecurityRule : portSecurityList) {
-
- /**
- * Neutron Port Security Acl "ingress" and "IPv4"
- * Check that the base conditions for flow based Port Security are true:
- * Port Security Rule Direction ("ingress") and Protocol ("IPv4")
- * Neutron defines the direction "ingress" as the vSwitch to the VM as defined in:
- * http://docs.openstack.org/api/openstack-network/2.0/content/security_groups.html
- *
- */
-
- if (portSecurityRule == null
- || portSecurityRule.getSecurityRuleEthertype() == null
- || portSecurityRule.getSecurityRuleDirection() == null) {
- continue;
- }
-
- if (NeutronSecurityRule.DIRECTION_INGRESS.equals(portSecurityRule.getSecurityRuleDirection())) {
- LOG.debug("programPortSecurityGroup: Rule matching IP and ingress is: {} ", portSecurityRule);
- String remoteSgUuid = portSecurityRule.getSecurityRemoteGroupID();
- if (null != remoteSgUuid) {
- //Remote Security group is selected
- List<Neutron_IPs> remoteSrcAddressList = secGroupRemoteIPMap.get(remoteSgUuid);
- if (remoteSrcAddressList == null) {
- remoteSrcAddressList = securityServicesManager
- .getVmListForSecurityGroup(portUuid, remoteSgUuid);
- secGroupRemoteIPMap.put(remoteSgUuid, remoteSrcAddressList);
- }
- for (Neutron_IPs vmIp :remoteSrcAddressList ) {
- programPortSecurityRule(dpid, segmentationId, attachedMac, portSecurityRule, vmIp, write);
- }
- if (write) {
- securityGroupCacheManger.addToCache(remoteSgUuid, portUuid, nodeId);
- } else {
- securityGroupCacheManger.removeFromCache(remoteSgUuid, portUuid, nodeId);
- }
- } else {
- programPortSecurityRule(dpid, segmentationId, attachedMac, portSecurityRule, null, write);
- }
- }
- }
- }
-
- @Override
- public void programPortSecurityRule(Long dpid, String segmentationId, String attachedMac,
- NeutronSecurityRule portSecurityRule, Neutron_IPs vmIp, boolean write) {
- String securityRuleEtherType = portSecurityRule.getSecurityRuleEthertype();
- boolean isIpv6 = NeutronSecurityRule.ETHERTYPE_IPV6.equals(securityRuleEtherType);
- if (!isIpv6 && !NeutronSecurityRule.ETHERTYPE_IPV4.equals(securityRuleEtherType)) {
- LOG.debug("programPortSecurityRule: SecurityRuleEthertype {} does not match IPv4/v6.",
- securityRuleEtherType);
- return;
- }
-
-
- String ipaddress = null;
- if (null != vmIp) {
- ipaddress = vmIp.getIpAddress();
- try {
- InetAddress address = InetAddress.getByName(vmIp.getIpAddress());
- if (isIpv6 && address instanceof Inet4Address || !isIpv6 && address instanceof Inet6Address) {
- LOG.debug("programPortSecurityRule: Remote vmIP {} does not match "
- + "with SecurityRuleEthertype {}.", ipaddress, securityRuleEtherType);
- return;
- }
- } catch (UnknownHostException e) {
- LOG.warn("Invalid IP address {}", ipaddress, e);
- return;
- }
- }
- if (null == portSecurityRule.getSecurityRuleProtocol()
- || portSecurityRule.getSecurityRuleProtocol().equals(MatchUtils.ANY_PROTOCOL)) {
- ingressAclIp(dpid, isIpv6, segmentationId, attachedMac, portSecurityRule, ipaddress, write);
- if (NeutronSecurityRule.ETHERTYPE_IPV4.equals(portSecurityRule.getSecurityRuleEthertype())) {
- ingressAclTcp(dpid, segmentationId, attachedMac, TCP_SECURITY_GROUP_RULE_IPv4_ANY, ipaddress, write);
- ingressAclUdp(dpid, segmentationId, attachedMac, UDP_SECURITY_GROUP_RULE_IPv4_ANY, ipaddress, write);
- ingressAclIcmp(dpid, segmentationId, attachedMac, ICMP_SECURITY_GROUP_RULE_IPv4_ANY, ipaddress, write);
- }
- } else {
- switch (portSecurityRule.getSecurityRuleProtocol()) {
- case MatchUtils.TCP:
- case MatchUtils.TCP_PROTOCOL:
- LOG.debug("programPortSecurityRule: Rule matching TCP", portSecurityRule);
- ingressAclTcp(dpid, segmentationId, attachedMac, portSecurityRule, ipaddress, write);
- break;
- case MatchUtils.UDP:
- case MatchUtils.UDP_PROTOCOL:
- LOG.debug("programPortSecurityRule: Rule matching UDP", portSecurityRule);
- ingressAclUdp(dpid, segmentationId, attachedMac, portSecurityRule, ipaddress, write);
- break;
- case MatchUtils.ICMP:
- case MatchUtils.ICMPV6:
- case MatchUtils.ICMP_PROTOCOL:
- LOG.debug("programPortSecurityRule: Rule matching ICMP", portSecurityRule);
- ingressAclIcmp(dpid, segmentationId, attachedMac, portSecurityRule, ipaddress, write);
- break;
- default:
- LOG.info("programPortSecurityAcl: Protocol is not TCP/UDP/ICMP but other "
- + "protocol = ", portSecurityRule.getSecurityRuleProtocol());
- ingressOtherProtocolAclHandler(dpid, segmentationId, attachedMac, portSecurityRule,
- ipaddress, write, isIpv6);
- break;
- }
- }
- }
-
- private void ingressOtherProtocolAclHandler(Long dpidLong, String segmentationId, String dstMac,
- NeutronSecurityRule portSecurityRule, String srcAddress,
- boolean write, boolean isIpv6) {
-
- MatchBuilder matchBuilder = new MatchBuilder();
- String flowId = "Ingress_Other_" + segmentationId + "_" + dstMac + "_";
- matchBuilder = MatchUtils.createV4EtherMatchWithType(matchBuilder, null, dstMac, MatchUtils.ETHERTYPE_IPV4);
- short proto = 0;
- try {
- Integer protocol = new Integer(portSecurityRule.getSecurityRuleProtocol());
- proto = protocol.shortValue();
- flowId = flowId + proto;
- } catch (NumberFormatException e) {
- LOG.error("Protocol value conversion failure", e);
- }
- matchBuilder = MatchUtils.createIpProtocolAndEthMatch(matchBuilder, proto, null, dstMac);
- if (null != srcAddress) {
- flowId = flowId + srcAddress;
- matchBuilder = MatchUtils.addRemoteIpPrefix(matchBuilder,
- MatchUtils.iPv4PrefixFromIPv4Address(srcAddress), null);
- } else if (null != portSecurityRule.getSecurityRuleRemoteIpPrefix()) {
- flowId = flowId + portSecurityRule.getSecurityRuleRemoteIpPrefix();
- if (isIpv6) {
- matchBuilder = MatchUtils.addRemoteIpv6Prefix(matchBuilder, null,
- new Ipv6Prefix(portSecurityRule.getSecurityRuleRemoteIpPrefix()));
- } else {
- if (!portSecurityRule.getSecurityRuleRemoteIpPrefix().contains("/0")) {
- matchBuilder = MatchUtils.addRemoteIpPrefix(matchBuilder,
- new Ipv4Prefix(portSecurityRule.getSecurityRuleRemoteIpPrefix()), null);
- }
- }
- }
- flowId = flowId + "_Permit";
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(flowId, Constants.PROTO_OTHER_MATCH_PRIORITY,
- matchBuilder, getTable());
- addInstructionWithConntrackCommit(flowBuilder, false);
- syncSecurityRuleFlow(flowBuilder, nodeBuilder, write);
- }
-
- @Override
- public void programFixedSecurityGroup(Long dpid, String segmentationId, String dhcpMacAddress,
- long localPort, String attachMac, boolean write) {
-
- ingressAclDhcpAllowServerTraffic(dpid, segmentationId, dhcpMacAddress, attachMac,
- write, Constants.PROTO_DHCP_SERVER_MATCH_PRIORITY);
- ingressAclDhcpv6AllowServerTraffic(dpid, segmentationId, dhcpMacAddress, attachMac,
- write, Constants.PROTO_DHCP_SERVER_MATCH_PRIORITY);
- if (securityServicesManager.isConntrackEnabled()) {
- programIngressAclFixedConntrackRule(dpid, segmentationId, attachMac, localPort, write);
- } else {
- ingressVMDrop(dpid, segmentationId, attachMac, write, Constants.PROTO_PORT_DROP_PRIORITY);
- ingressVMRegex(dpid, segmentationId, attachMac, write, Constants.PROTO_REG6_MATCH_PRIORITY);
- }
- programArpRule(dpid, segmentationId, localPort, attachMac, write);
- }
-
- private void ingressVMDrop(Long dpidLong, String segmentationId, String srcMac,
- boolean write, Integer priority) {
- String flowName = "Ingress_Drop_" + segmentationId + "_" + srcMac + "_DROP";
- MatchBuilder matchBuilder = new MatchBuilder();
- matchBuilder = MatchUtils.createV4EtherMatchWithoutType(matchBuilder, null, srcMac);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(flowName, priority, matchBuilder, getTable());
- addPipelineInstruction(flowBuilder, null, true);
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- syncFlow(flowBuilder, nodeBuilder, write);
- }
-
- private void ingressVMRegex(Long dpidLong, String segmentationId, String srcMac,
- boolean write, Integer priority) {
- String flowName = "Ingress_Regx_" + segmentationId + "_" + srcMac;
- MatchBuilder matchBuilder = new MatchBuilder();
- matchBuilder = MatchUtils.createV4EtherMatchWithoutType(matchBuilder, null, srcMac);
- MatchUtils.addNxRegMatch(matchBuilder,
- new MatchUtils.RegMatch(ClassifierService.REG_FIELD_6, ClassifierService.REG_VALUE_FROM_LOCAL));
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(flowName, priority, matchBuilder, getTable());
- addPipelineInstruction(flowBuilder, null, false);
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- syncFlow(flowBuilder, nodeBuilder, write);
- }
-
- private void programArpRule(Long dpid, String segmentationId, long localPort, String attachMac, boolean write) {
- MatchBuilder matchBuilder = new MatchBuilder();
- String flowId = "Ingress_ARP_" + segmentationId + "_" + localPort + "_";
- MatchUtils.createV4EtherMatchWithType(matchBuilder, null, null, MatchUtils.ETHERTYPE_ARP);
- MatchUtils.addArpMacMatch(matchBuilder, null, attachMac);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(flowId, Constants.PROTO_MATCH_PRIORITY,
- matchBuilder, getTable());
- addPipelineInstruction(flowBuilder, null, false);
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpid);
- syncFlow(flowBuilder, nodeBuilder, write);
- }
-
- private void programIngressAclFixedConntrackRule(Long dpid,
- String segmentationId, String attachMac, long localPort, boolean write) {
- try {
- String nodeName = Constants.OPENFLOW_NODE_PREFIX + dpid;
- programConntrackUntrackRule(dpid, segmentationId, localPort, attachMac,
- Constants.CT_STATE_UNTRACKED_PRIORITY, write );
- programConntrackTrackedPlusEstRule(dpid, segmentationId, localPort, attachMac,
- Constants.CT_STATE_TRACKED_EXIST_PRIORITY, write );
- programConntrackTrackedPlusRelRule(dpid, segmentationId, localPort, attachMac,
- Constants.CT_STATE_TRACKED_EXIST_PRIORITY, write );
- programConntrackInvDropRule(dpid, segmentationId, localPort, attachMac,
- Constants.CT_STATE_NEW_PRIORITY_DROP, write );
- programConntrackNewDropRule(dpid, segmentationId, localPort, attachMac,
- Constants.CT_STATE_NEW_PRIORITY_DROP, write );
- LOG.info("programIngressAclFixedConntrackRule : default connection tracking rule are added.");
- } catch (Exception e) {
- LOG.error("Failed to add default conntrack rules : " , e);
- }
- }
-
- private void programConntrackUntrackRule(Long dpidLong, String segmentationId,
- long localPort, String attachMac, Integer priority, boolean write) {
- MatchBuilder matchBuilder = new MatchBuilder();
- String flowName = "Ingress_Fixed_Conntrk_Untrk_" + segmentationId + "_" + localPort + "_";
- matchBuilder = MatchUtils.createV4EtherMatchWithType(matchBuilder, null, attachMac, MatchUtils.ETHERTYPE_IPV4);
- matchBuilder = MatchUtils.addCtState(matchBuilder, MatchUtils.UNTRACKED_CT_STATE,
- MatchUtils.UNTRACKED_CT_STATE_MASK);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(flowName, priority, matchBuilder, getTable());
- addInstructionWithConntrackRecirc(flowBuilder);
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- syncFlow(flowBuilder, nodeBuilder, write);
- }
-
- private void programConntrackTrackedPlusEstRule(Long dpidLong, String segmentationId,
- long localPort, String attachMac, Integer priority, boolean write) {
- MatchBuilder matchBuilder = new MatchBuilder();
- String flowName = "Ingress_Fixed_Conntrk_TrkEst_" + segmentationId + "_" + localPort + "_";
- matchBuilder = MatchUtils.createV4EtherMatchWithType(matchBuilder, null, attachMac, MatchUtils.ETHERTYPE_IPV4);
- matchBuilder = MatchUtils.addCtState(matchBuilder, MatchUtils.TRACKED_EST_CT_STATE,
- MatchUtils.TRACKED_CT_STATE_MASK);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(flowName, priority, matchBuilder, getTable());
- addPipelineInstruction(flowBuilder, null, false);
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- syncFlow(flowBuilder, nodeBuilder, write);
- }
-
- private void programConntrackTrackedPlusRelRule(Long dpidLong, String segmentationId,
- long localPort, String attachMac, Integer priority, boolean write) {
- MatchBuilder matchBuilder = new MatchBuilder();
- String flowName = "Ingress_Fixed_Conntrk_TrkRel_" + segmentationId + "_" + localPort + "_";
- matchBuilder = MatchUtils.createV4EtherMatchWithType(matchBuilder, null, attachMac, MatchUtils.ETHERTYPE_IPV4);
- matchBuilder = MatchUtils.addCtState(matchBuilder, MatchUtils.TRACKED_REL_CT_STATE,
- MatchUtils.TRACKED_CT_STATE_MASK);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(flowName, priority, matchBuilder, getTable());
- addPipelineInstruction(flowBuilder, null, false);
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- syncFlow(flowBuilder, nodeBuilder, write);
- }
-
- private void programConntrackNewDropRule(Long dpidLong, String segmentationId,
- long localPort, String attachMac, Integer priority, boolean write) {
- MatchBuilder matchBuilder = new MatchBuilder();
-
- String flowName = "Ingress_Fixed_Conntrk_NewDrop_" + segmentationId + "_" + localPort + "_";
- matchBuilder = MatchUtils.createV4EtherMatchWithType(matchBuilder, null, attachMac, 0x0800L);
- matchBuilder = MatchUtils.addCtState(matchBuilder, MatchUtils.TRACKED_NEW_CT_STATE,
- MatchUtils.TRACKED_NEW_CT_STATE_MASK);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(flowName, priority, matchBuilder, getTable());
- addPipelineInstruction(flowBuilder, null, true);
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- syncFlow(flowBuilder, nodeBuilder, write);
- }
-
- private void programConntrackInvDropRule(Long dpidLong, String segmentationId,
- long localPort, String attachMac, Integer priority, boolean write) {
- MatchBuilder matchBuilder = new MatchBuilder();
- String flowName = "Ingress_Fixed_Conntrk_InvDrop_" + segmentationId + "_" + localPort + "_";
- matchBuilder = MatchUtils.createV4EtherMatchWithType(matchBuilder, null, attachMac, MatchUtils.ETHERTYPE_IPV4);
- matchBuilder = MatchUtils.addCtState(matchBuilder, MatchUtils.TRACKED_INV_CT_STATE,
- MatchUtils.TRACKED_INV_CT_STATE_MASK);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(flowName, priority, matchBuilder, getTable());
- addPipelineInstruction(flowBuilder, null, true);
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- syncFlow(flowBuilder, nodeBuilder, write);
- }
-
- /**
- * Allows an IPv4/v6 packet ingress to the destination mac address.
- * @param dpidLong the dpid
- * @param isIpv6 indicates whether this is an Ipv
- * @param segmentationId the segementation id
- * @param dstMac the destination mac address
- * @param write add or remove
- */
- private void ingressAclIp(Long dpidLong, boolean isIpv6, String segmentationId, String dstMac,
- NeutronSecurityRule portSecurityRule, String srcAddress, boolean write) {
- MatchBuilder matchBuilder = new MatchBuilder();
- String flowId = "Ingress_IP" + segmentationId + "_" + dstMac + "_Permit_";
- if (isIpv6) {
- matchBuilder = MatchUtils.createV6EtherMatchWithType(matchBuilder, null, dstMac);
- } else {
- matchBuilder = MatchUtils.createV4EtherMatchWithType(matchBuilder, null, dstMac, MatchUtils.ETHERTYPE_IPV4);
- }
- if (null != srcAddress) {
- flowId = flowId + srcAddress;
- if (isIpv6) {
- matchBuilder = MatchUtils.addRemoteIpv6Prefix(matchBuilder,
- MatchUtils.iPv6PrefixFromIPv6Address(srcAddress), null);
- } else {
- matchBuilder = MatchUtils.addRemoteIpPrefix(matchBuilder,
- MatchUtils.iPv4PrefixFromIPv4Address(srcAddress), null);
- }
- } else if (null != portSecurityRule.getSecurityRuleRemoteIpPrefix()) {
- flowId = flowId + portSecurityRule.getSecurityRuleRemoteIpPrefix();
- if (isIpv6) {
- matchBuilder = MatchUtils.addRemoteIpv6Prefix(matchBuilder,
- new Ipv6Prefix(portSecurityRule
- .getSecurityRuleRemoteIpPrefix()), null);
- } else {
- // Fix: Bug 6473
- // IP match removed if CIDR created as 0.0.0.0/0 in openstack security rule
- if (!portSecurityRule.getSecurityRuleRemoteIpPrefix().contains("/0")) {
- matchBuilder = MatchUtils.addRemoteIpPrefix(matchBuilder,
- new Ipv4Prefix(portSecurityRule
- .getSecurityRuleRemoteIpPrefix()), null);
- }
- }
- } else {
- if (isIpv6) {
- flowId = flowId + "Ipv6";
- } else {
- flowId = flowId + "Ipv4";
- }
- }
- addConntrackMatch(matchBuilder, MatchUtils.TRACKED_NEW_CT_STATE, MatchUtils.TRACKED_NEW_CT_STATE_MASK);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(
- flowId, Constants.PROTO_IP_PORT_MATCH_PRIORITY, matchBuilder, getTable());
- addInstructionWithConntrackCommit(flowBuilder, false);
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- syncSecurityRuleFlow(flowBuilder, nodeBuilder, write);
- }
-
- /**
- * Creates a ingress match to the dst macaddress. If src address is specified
- * source specific match will be created. Otherwise a match with a CIDR will
- * be created.
- * @param dpidLong the dpid
- * @param segmentationId the segmentation id
- * @param dstMac the destination mac address.
- * @param portSecurityRule the security rule in the SG
- * @param srcAddress the destination IP address
- * @param write add or delete
- */
- private void ingressAclTcp(Long dpidLong, String segmentationId, String dstMac,
- NeutronSecurityRule portSecurityRule, String srcAddress, boolean write) {
- boolean portRange = false;
- MatchBuilder matchBuilder = new MatchBuilder();
- String flowId = "Ingress_TCP_" + segmentationId + "_" + dstMac + "_";
- boolean isIpv6 = NeutronSecurityRule.ETHERTYPE_IPV6.equals(portSecurityRule.getSecurityRuleEthertype());
- if (isIpv6) {
- matchBuilder = MatchUtils.createV6EtherMatchWithType(matchBuilder, null, dstMac);
- } else {
- matchBuilder = MatchUtils.createV4EtherMatchWithType(matchBuilder, null, dstMac, MatchUtils.ETHERTYPE_IPV4);
- }
-
- /* Custom TCP Match*/
- if (portSecurityRule.getSecurityRulePortMin() != null && portSecurityRule.getSecurityRulePortMax() != null) {
- if (portSecurityRule.getSecurityRulePortMin().equals(portSecurityRule.getSecurityRulePortMax())) {
- flowId = flowId + portSecurityRule.getSecurityRulePortMin() + "_";
- matchBuilder = MatchUtils.addLayer4Match(matchBuilder, MatchUtils.TCP_SHORT, 0,
- portSecurityRule.getSecurityRulePortMin());
- } else if (portSecurityRule.getSecurityRulePortMin().equals(PORT_RANGE_MIN)
- && portSecurityRule.getSecurityRulePortMax().equals(PORT_RANGE_MAX)) {
- /* All TCP Match */
- flowId = flowId + "ALL" + "_";
- matchBuilder = MatchUtils.addLayer4Match(matchBuilder, MatchUtils.TCP_SHORT, 0, 0);
- } else {
- portRange = true;
- }
- } else if (portSecurityRule.getSecurityRulePortMin() == null
- && portSecurityRule.getSecurityRulePortMax() == null) {
- /* All TCP Match */
- flowId = flowId + "ALL" + "_";
- matchBuilder = MatchUtils.addLayer4Match(matchBuilder, MatchUtils.TCP_SHORT, 0, 0);
- }
- if (null != srcAddress) {
- flowId = flowId + srcAddress;
- if (isIpv6) {
- matchBuilder = MatchUtils.addRemoteIpv6Prefix(matchBuilder,
- MatchUtils.iPv6PrefixFromIPv6Address(srcAddress), null);
- } else {
- matchBuilder = MatchUtils.addRemoteIpPrefix(matchBuilder,
- MatchUtils.iPv4PrefixFromIPv4Address(srcAddress), null);
- }
- } else if (null != portSecurityRule.getSecurityRuleRemoteIpPrefix()) {
- flowId = flowId + portSecurityRule.getSecurityRuleRemoteIpPrefix();
- if (isIpv6) {
- matchBuilder = MatchUtils.addRemoteIpv6Prefix(matchBuilder,
- new Ipv6Prefix(portSecurityRule
- .getSecurityRuleRemoteIpPrefix()), null);
- } else {
- // Fix: Bug 6473
- // IP match removed if CIDR created as 0.0.0.0/0 in openstack security rule
- if (!portSecurityRule.getSecurityRuleRemoteIpPrefix().contains("/0")) {
- matchBuilder = MatchUtils.addRemoteIpPrefix(matchBuilder,
- new Ipv4Prefix(portSecurityRule
- .getSecurityRuleRemoteIpPrefix()), null);
- }
- }
- }
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- if (portRange) {
- Map<Integer, Integer> portMaskMap = MatchUtils
- .getLayer4MaskForRange(portSecurityRule.getSecurityRulePortMin(),
- portSecurityRule.getSecurityRulePortMax());
- for (Integer port: portMaskMap.keySet()) {
- String rangeflowId = flowId + port + "_" + portMaskMap.get(port) + "_";
- rangeflowId = rangeflowId + "_Permit";
- MatchUtils.addLayer4MatchWithMask(matchBuilder, MatchUtils.TCP_SHORT,
- 0, port, portMaskMap.get(port));
- addConntrackMatch(matchBuilder, MatchUtils.TRACKED_NEW_CT_STATE, MatchUtils.TRACKED_NEW_CT_STATE_MASK);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(rangeflowId, Constants.PROTO_PORT_MATCH_PRIORITY,
- matchBuilder, getTable());
- addInstructionWithLearnConntrackCommit(portSecurityRule, flowBuilder, null, null);
- syncSecurityRuleFlow(flowBuilder, nodeBuilder, write);
- }
- } else {
- flowId = flowId + "_Permit";
- addConntrackMatch(matchBuilder, MatchUtils.TRACKED_NEW_CT_STATE, MatchUtils.TRACKED_NEW_CT_STATE_MASK);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(flowId, Constants.PROTO_PORT_MATCH_PRIORITY,
- matchBuilder, getTable());
- addInstructionWithLearnConntrackCommit(portSecurityRule, flowBuilder, null, null);
- syncSecurityRuleFlow(flowBuilder, nodeBuilder, write);
- }
- }
-
- /**
- * Creates a ingress match to the dst macaddress. If src address is specified
- * source specific match will be created. Otherwise a match with a CIDR will
- * be created.
- * @param dpidLong the dpid
- * @param segmentationId the segmentation id
- * @param dstMac the destination mac address.
- * @param portSecurityRule the security rule in the SG
- * @param srcAddress the destination IP address
- * @param write add or delete
- */
- private void ingressAclUdp(Long dpidLong, String segmentationId, String dstMac,
- NeutronSecurityRule portSecurityRule, String srcAddress,
- boolean write) {
- boolean portRange = false;
- boolean isIpv6 = NeutronSecurityRule.ETHERTYPE_IPV6.equals(portSecurityRule.getSecurityRuleEthertype());
- MatchBuilder matchBuilder = new MatchBuilder();
- String flowId = "Ingress_UDP_" + segmentationId + "_" + dstMac + "_";
- if (isIpv6) {
- matchBuilder = MatchUtils.createV6EtherMatchWithType(matchBuilder, null, dstMac);
- } else {
- matchBuilder = MatchUtils.createV4EtherMatchWithType(matchBuilder, null, dstMac, MatchUtils.ETHERTYPE_IPV4);
- }
-
- /* Custom UDP Match */
- if (portSecurityRule.getSecurityRulePortMin() != null && portSecurityRule.getSecurityRulePortMax() != null) {
- if (portSecurityRule.getSecurityRulePortMin().equals(portSecurityRule.getSecurityRulePortMax())) {
- flowId = flowId + portSecurityRule.getSecurityRulePortMin() + "_";
- matchBuilder = MatchUtils.addLayer4Match(matchBuilder, MatchUtils.UDP_SHORT, 0,
- portSecurityRule.getSecurityRulePortMin());
- } else if (portSecurityRule.getSecurityRulePortMin().equals(PORT_RANGE_MIN)
- && portSecurityRule.getSecurityRulePortMax().equals(PORT_RANGE_MAX)) {
- /* All UDP Match */
- flowId = flowId + "ALL" + "_";
- matchBuilder = MatchUtils.addLayer4Match(matchBuilder, MatchUtils.UDP_SHORT, 0, 0);
- } else {
- portRange = true;
- }
- } else if (portSecurityRule.getSecurityRulePortMin() == null
- && portSecurityRule.getSecurityRulePortMax() == null) {
- flowId = flowId + "ALL" + "_";
- matchBuilder = MatchUtils.addLayer4Match(matchBuilder, MatchUtils.UDP_SHORT, 0, 0);
- }
- if (null != srcAddress) {
- flowId = flowId + srcAddress;
- if (isIpv6) {
- matchBuilder = MatchUtils.addRemoteIpv6Prefix(matchBuilder,
- MatchUtils.iPv6PrefixFromIPv6Address(srcAddress), null);
- } else {
- matchBuilder = MatchUtils.addRemoteIpPrefix(matchBuilder,
- MatchUtils.iPv4PrefixFromIPv4Address(srcAddress), null);
- }
- } else if (null != portSecurityRule.getSecurityRuleRemoteIpPrefix()) {
- flowId = flowId + portSecurityRule.getSecurityRuleRemoteIpPrefix();
- if (isIpv6) {
- matchBuilder = MatchUtils.addRemoteIpv6Prefix(matchBuilder,
- new Ipv6Prefix(portSecurityRule
- .getSecurityRuleRemoteIpPrefix()), null);
- } else {
- if (!portSecurityRule.getSecurityRuleRemoteIpPrefix().contains("/0")) {
- matchBuilder = MatchUtils.addRemoteIpPrefix(matchBuilder,
- new Ipv4Prefix(portSecurityRule
- .getSecurityRuleRemoteIpPrefix()), null);
- }
- }
- }
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- if (portRange) {
- Map<Integer, Integer> portMaskMap = MatchUtils
- .getLayer4MaskForRange(portSecurityRule.getSecurityRulePortMin(),
- portSecurityRule.getSecurityRulePortMax());
- for (Integer port: portMaskMap.keySet()) {
- String rangeflowId = flowId + port + "_" + portMaskMap.get(port) + "_";
- rangeflowId = rangeflowId + "_Permit";
- MatchUtils.addLayer4MatchWithMask(matchBuilder, MatchUtils.UDP_SHORT,
- 0, port, portMaskMap.get(port));
- addConntrackMatch(matchBuilder, MatchUtils.TRACKED_NEW_CT_STATE, MatchUtils.TRACKED_NEW_CT_STATE_MASK);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(
- rangeflowId, Constants.PROTO_PORT_MATCH_PRIORITY, matchBuilder, getTable());
- addInstructionWithLearnConntrackCommit(portSecurityRule, flowBuilder, null, null);
- syncSecurityRuleFlow(flowBuilder, nodeBuilder, write);
- }
- } else {
- flowId = flowId + "_Permit";
- addConntrackMatch(matchBuilder, MatchUtils.TRACKED_NEW_CT_STATE, MatchUtils.TRACKED_NEW_CT_STATE_MASK);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(
- flowId, Constants.PROTO_PORT_MATCH_PRIORITY, matchBuilder, getTable());
- addInstructionWithLearnConntrackCommit(portSecurityRule, flowBuilder, null, null);
- syncSecurityRuleFlow(flowBuilder, nodeBuilder, write);
- }
- }
-
- private void ingressAclIcmp(Long dpidLong, String segmentationId, String dstMac,
- NeutronSecurityRule portSecurityRule, String srcAddress,
- boolean write) {
-
- boolean isIpv6 = NeutronSecurityRule.ETHERTYPE_IPV6.equals(portSecurityRule.getSecurityRuleEthertype());
- if (isIpv6) {
- ingressAclIcmpV6(dpidLong, segmentationId, dstMac, portSecurityRule, srcAddress, write);
- } else {
- ingressAclIcmpV4(dpidLong, segmentationId, dstMac, portSecurityRule, srcAddress, write);
- }
- }
-
- /**
- * Creates a ingress icmp match to the dst macaddress. If src address is specified
- * source specific match will be created. Otherwise a match with a CIDR will
- * be created.
- * @param dpidLong the dpid
- * @param segmentationId the segmentation id
- * @param dstMac the destination mac address.
- * @param portSecurityRule the security rule in the SG
- * @param srcAddress the destination IP address
- * @param write add or delete
- */
- private void ingressAclIcmpV4(Long dpidLong, String segmentationId, String dstMac,
- NeutronSecurityRule portSecurityRule, String srcAddress, boolean write) {
- MatchBuilder matchBuilder = new MatchBuilder();
- boolean isIcmpAll = false;
- String flowId = "Ingress_ICMP_" + segmentationId + "_" + dstMac + "_";
- matchBuilder = MatchUtils.createV4EtherMatchWithType(matchBuilder, null, dstMac, MatchUtils.ETHERTYPE_IPV4);
-
- /* Custom ICMP Match */
- if (portSecurityRule.getSecurityRulePortMin() != null
- && portSecurityRule.getSecurityRulePortMax() != null) {
- flowId = flowId + portSecurityRule.getSecurityRulePortMin().shortValue() + "_"
- + portSecurityRule.getSecurityRulePortMax().shortValue() + "_";
- matchBuilder = MatchUtils.createICMPv4Match(matchBuilder,
- portSecurityRule.getSecurityRulePortMin().shortValue(),
- portSecurityRule.getSecurityRulePortMax().shortValue());
- } else {
- isIcmpAll = true;
- /* All ICMP Match */
- matchBuilder = MatchUtils.createICMPv4Match(matchBuilder, MatchUtils.ALL_ICMP, MatchUtils.ALL_ICMP);
- }
-
- if (null != srcAddress) {
- flowId = flowId + srcAddress;
- matchBuilder = MatchUtils.addRemoteIpPrefix(matchBuilder,
- MatchUtils.iPv4PrefixFromIPv4Address(srcAddress), null);
- } else if (null != portSecurityRule.getSecurityRuleRemoteIpPrefix()) {
- flowId = flowId + portSecurityRule.getSecurityRuleRemoteIpPrefix();
- if (!portSecurityRule.getSecurityRuleRemoteIpPrefix().contains("/0")) {
- matchBuilder = MatchUtils.addRemoteIpPrefix(matchBuilder,
- new Ipv4Prefix(portSecurityRule.getSecurityRuleRemoteIpPrefix()), null);
- }
- }
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- if(isIcmpAll)
- {
- Map<Integer, String> map = LearnConstants.ICMP_TYPE_MAP;
- for(Map.Entry<Integer, String> entry : map.entrySet()) {
- matchBuilder = MatchUtils.createICMPv4Match(matchBuilder, entry.getKey().shortValue(), (short)0);
- String rangeflowId = flowId + entry.getKey() + "_" + entry.getValue() + "_" ;
- rangeflowId = rangeflowId + "_Permit";
- addConntrackMatch(matchBuilder, MatchUtils.TRACKED_NEW_CT_STATE, MatchUtils.TRACKED_NEW_CT_STATE_MASK);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(
- rangeflowId, Constants.PROTO_PORT_MATCH_PRIORITY, matchBuilder, getTable());
- addInstructionWithLearnConntrackCommit(portSecurityRule, flowBuilder, entry.getValue(), "0");
- syncSecurityRuleFlow(flowBuilder, nodeBuilder, write);
- }
- addIcmpFlow(nodeBuilder, portSecurityRule, segmentationId, dstMac, srcAddress, write);
- } else {
- flowId = flowId + "_Permit";
- addConntrackMatch(matchBuilder, MatchUtils.TRACKED_NEW_CT_STATE, MatchUtils.TRACKED_NEW_CT_STATE_MASK);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(
- flowId, Constants.PROTO_PORT_MATCH_PRIORITY, matchBuilder, getTable());
- String icmpType = LearnConstants.ICMP_TYPE_MAP.get(portSecurityRule.getSecurityRulePortMin());
- if (icmpType == null){
- icmpType = Integer.toString(portSecurityRule.getSecurityRulePortMin());
- }
- addInstructionWithLearnConntrackCommit(portSecurityRule, flowBuilder, icmpType,
- Integer.toString(portSecurityRule.getSecurityRulePortMax()));
- syncSecurityRuleFlow(flowBuilder, nodeBuilder, write);
- }
- }
-
-
- private void addIcmpFlow(NodeBuilder nodeBuilder, NeutronSecurityRule portSecurityRule, String segmentationId,
- String dstMac, String srcAddress, boolean write) {
- MatchBuilder matchBuilder = new MatchBuilder();
- String flowId = "Ingress_ICMP_" + segmentationId + "_" + dstMac + "_";
- matchBuilder = MatchUtils.createV4EtherMatchWithType(matchBuilder, null, dstMac, MatchUtils.ETHERTYPE_IPV4);
- if (null != srcAddress) {
- flowId = flowId + srcAddress;
- matchBuilder = MatchUtils.addRemoteIpPrefix(matchBuilder,
- MatchUtils.iPv4PrefixFromIPv4Address(srcAddress), null);
- } else if (null != portSecurityRule.getSecurityRuleRemoteIpPrefix()) {
- flowId = flowId + portSecurityRule.getSecurityRuleRemoteIpPrefix();
- if (!portSecurityRule.getSecurityRuleRemoteIpPrefix().contains("/0")) {
- matchBuilder = MatchUtils.addRemoteIpPrefix(matchBuilder,
- new Ipv4Prefix(portSecurityRule.getSecurityRuleRemoteIpPrefix()), null);
- }
- }
- flowId = flowId + "all" + "_";
- matchBuilder = MatchUtils.createICMPv4Match(matchBuilder, MatchUtils.ALL_ICMP, MatchUtils.ALL_ICMP);
- String rangeflowId = flowId;
- addConntrackMatch(matchBuilder, MatchUtils.TRACKED_NEW_CT_STATE, MatchUtils.TRACKED_NEW_CT_STATE_MASK);
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(
- rangeflowId, Constants.PROTO_PORT_ICMP_MATCH_PRIORITY, matchBuilder, getTable());
- addPipelineInstruction(flowBuilder, null, false);
- syncSecurityRuleFlow(flowBuilder, nodeBuilder, write);
- }
-
- /**
- * Creates a ingress icmpv6 match to the dst macaddress. If src address is specified
- * source specific match will be created. Otherwise a match with a CIDR will
- * be created.
- * @param dpidLong the dpid
- * @param segmentationId the segmentation id
- * @param dstMac the destination mac address.
- * @param portSecurityRule the security rule in the SG
- * @param srcAddress the destination IP address
- * @param write add or delete
- */
- private void ingressAclIcmpV6(Long dpidLong, String segmentationId, String dstMac,
- NeutronSecurityRule portSecurityRule, String srcAddress, boolean write) {
-
- MatchBuilder matchBuilder = new MatchBuilder();
- String flowId = "Ingress_ICMPv6_" + segmentationId + "_" + dstMac + "_";
- matchBuilder = MatchUtils.createV6EtherMatchWithType(matchBuilder, null, dstMac);
-
- /* Custom ICMP Match */
- if (portSecurityRule.getSecurityRulePortMin() != null
- && portSecurityRule.getSecurityRulePortMax() != null) {
- flowId = flowId + portSecurityRule.getSecurityRulePortMin().shortValue() + "_"
- + portSecurityRule.getSecurityRulePortMax().shortValue() + "_";
- matchBuilder = MatchUtils.createICMPv6Match(matchBuilder,
- portSecurityRule.getSecurityRulePortMin().shortValue(),
- portSecurityRule.getSecurityRulePortMax().shortValue());
- } else {
- /* All ICMP Match */
- flowId = flowId + "all" + "_";
- matchBuilder = MatchUtils.createICMPv6Match(matchBuilder, MatchUtils.ALL_ICMP, MatchUtils.ALL_ICMP);
- }
- if (null != srcAddress) {
- flowId = flowId + srcAddress;
- matchBuilder = MatchUtils.addRemoteIpv6Prefix(matchBuilder,
- MatchUtils.iPv6PrefixFromIPv6Address(srcAddress), null);
- } else if (null != portSecurityRule.getSecurityRuleRemoteIpPrefix()) {
- flowId = flowId + portSecurityRule.getSecurityRuleRemoteIpPrefix();
- matchBuilder = MatchUtils.addRemoteIpv6Prefix(matchBuilder,
- new Ipv6Prefix(portSecurityRule
- .getSecurityRuleRemoteIpPrefix()), null);
- }
- addConntrackMatch(matchBuilder, MatchUtils.TRACKED_NEW_CT_STATE, MatchUtils.TRACKED_NEW_CT_STATE_MASK);
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- flowId = flowId + "_Permit";
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(flowId, Constants.PROTO_PORT_MATCH_PRIORITY, matchBuilder, getTable());
- addInstructionWithConntrackCommit(flowBuilder, false);
- syncFlow(flowBuilder, nodeBuilder, write);
- }
-
- /**
- * Add rule to ensure only DHCP server traffic from the specified mac is allowed.
- *
- * @param dpidLong the dpid
- * @param segmentationId the segmentation id
- * @param dhcpMacAddress the DHCP server mac address
- * @param attachMac the mac address of the port
- * @param write is write or delete
- * @param protoPortMatchPriority the priority
- */
- private void ingressAclDhcpAllowServerTraffic(Long dpidLong, String segmentationId, String dhcpMacAddress,
- String attachMac, boolean write, Integer protoPortMatchPriority) {
-
- MatchBuilder matchBuilder = new MatchBuilder();
- matchBuilder = MatchUtils.createV4EtherMatchWithType(matchBuilder, dhcpMacAddress, attachMac,
- MatchUtils.ETHERTYPE_IPV4);
- MatchUtils.addLayer4Match(matchBuilder, MatchUtils.UDP_SHORT, 67, 68);
- String flowId = "Ingress_DHCP_Server_" + segmentationId + "_" + attachMac + "_Permit";
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(flowId, protoPortMatchPriority, matchBuilder, getTable());
- addPipelineInstruction(flowBuilder, null, false);
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- syncFlow(flowBuilder, nodeBuilder, write);
- }
-
- /**
- * Add rule to ensure only DHCPv6 server traffic from the specified mac is allowed.
- *
- * @param dpidLong the dpid
- * @param segmentationId the segmentation id
- * @param dhcpMacAddress the DHCP server mac address
- * @param attachMac the mac address of the port
- * @param write is write or delete
- * @param protoPortMatchPriority the priority
- */
- private void ingressAclDhcpv6AllowServerTraffic(Long dpidLong, String segmentationId, String dhcpMacAddress,
- String attachMac, boolean write, Integer protoPortMatchPriority) {
-
- MatchBuilder matchBuilder = new MatchBuilder();
- matchBuilder = MatchUtils.createV4EtherMatchWithType(matchBuilder, dhcpMacAddress, attachMac,
- MatchUtils.ETHERTYPE_IPV6);
- MatchUtils.addLayer4Match(matchBuilder, MatchUtils.UDP_SHORT, 547, 546);
- String flowId = "Ingress_DHCPv6_Server_" + segmentationId + "_" + attachMac + "_Permit";
- FlowBuilder flowBuilder = FlowUtils.createFlowBuilder(flowId, protoPortMatchPriority, matchBuilder, getTable());
- addPipelineInstruction(flowBuilder, null, false);
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- syncFlow(flowBuilder, nodeBuilder, write);
- }
-
- private FlowBuilder addInstructionWithLearnConntrackCommit(NeutronSecurityRule portSecurityRule, FlowBuilder flowBuilder,
- String icmpType, String icmpCode) {
- if (securityServicesManager.isConntrackEnabled()) {
- Action conntrackAction = ActionUtils.nxConntrackAction(1, 0L, 0, (short)0xff);
- InstructionBuilder instructionBuilder = InstructionUtils
- .createInstructionBuilder(ActionUtils.conntrackActionBuilder(conntrackAction), 1, false);
- return addPipelineInstruction(flowBuilder, instructionBuilder, false);
- }
- if (portSecurityRule.getSecurityRuleProtocol().equalsIgnoreCase(MatchUtils.TCP)
- || portSecurityRule.getSecurityRuleProtocol().equalsIgnoreCase(MatchUtils.TCP_PROTOCOL)) {
- return IngressAclLearnServiceUtil.programIngressAclLearnRuleForTcp(flowBuilder);
- } else if (portSecurityRule.getSecurityRuleProtocol().equalsIgnoreCase(MatchUtils.UDP)
- || portSecurityRule.getSecurityRuleProtocol().equalsIgnoreCase(MatchUtils.UDP_PROTOCOL)) {
- return IngressAclLearnServiceUtil.programIngressAclLearnRuleForUdp(flowBuilder);
- } else if (portSecurityRule.getSecurityRuleProtocol().equalsIgnoreCase(MatchUtils.ICMP)
- || portSecurityRule.getSecurityRuleProtocol().equalsIgnoreCase(MatchUtils.ICMP_PROTOCOL)) {
- return IngressAclLearnServiceUtil.programIngressAclLearnRuleForIcmp(flowBuilder, icmpType, icmpCode);
- }
- return flowBuilder;
- }
-
- @Override
- public void setDependencies(BundleContext bundleContext, ServiceReference serviceReference) {
- super.setDependencies(bundleContext.getServiceReference(IngressAclProvider.class.getName()), this);
- securityServicesManager =
- (SecurityServicesManager) ServiceHelper.getGlobalInstance(SecurityServicesManager.class, this);
- securityGroupCacheManger =
- (SecurityGroupCacheManger) ServiceHelper.getGlobalInstance(SecurityGroupCacheManger.class, this);
- neutronSecurityRule = (INeutronSecurityRuleCRUD) ServiceHelper.getGlobalInstance(INeutronSecurityRuleCRUD.class, this);
- }
-
- @Override
- public void setDependencies(Object impl) {
-
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 NEC Corporation 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.netvirt.openstack.netvirt.providers.openflow13.services;
-
-import java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.List;
-import org.opendaylight.netvirt.openstack.netvirt.api.L2ForwardingLearnProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.LearnConstants;
-import org.opendaylight.netvirt.openstack.netvirt.api.LearnConstants.LearnFlowModsType;
-import org.opendaylight.netvirt.openstack.netvirt.providers.ConfigInterface;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.AbstractServiceInstance;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.netvirt.utils.mdsal.openflow.FlowUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.MatchUtils;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
-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.flow.inventory.rev130819.tables.table.FlowBuilder;
-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;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.flow.mod.spec.flow.mod.spec.FlowModAddMatchFromFieldCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.flow.mod.spec.flow.mod.spec.FlowModAddMatchFromValueCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.flow.mod.spec.flow.mod.spec.FlowModCopyFieldIntoFieldCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.flow.mod.spec.flow.mod.spec.FlowModCopyValueIntoFieldCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.flow.mod.spec.flow.mod.spec.FlowModOutputToPortCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.flow.mod.spec.flow.mod.spec.flow.mod.add.match.from.field._case.FlowModAddMatchFromFieldBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.flow.mod.spec.flow.mod.spec.flow.mod.add.match.from.value._case.FlowModAddMatchFromValueBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.flow.mod.spec.flow.mod.spec.flow.mod.copy.field.into.field._case.FlowModCopyFieldIntoFieldBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.flow.mod.spec.flow.mod.spec.flow.mod.copy.value.into.field._case.FlowModCopyValueIntoFieldBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.flow.mod.spec.flow.mod.spec.flow.mod.output.to.port._case.FlowModOutputToPortBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nodes.node.table.flow.instructions.instruction.instruction.apply.actions._case.apply.actions.action.action.NxActionLearnNodesNodeTableFlowApplyActionsCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.learn.grouping.NxLearnBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.learn.grouping.nx.learn.FlowMods;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.learn.grouping.nx.learn.FlowModsBuilder;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class L2ForwardingLearnService extends AbstractServiceInstance implements ConfigInterface, L2ForwardingLearnProvider {
- private static final Logger LOG = LoggerFactory.getLogger(L2ForwardingLearnService.class);
-
- public L2ForwardingLearnService() {
- super(Service.L2_LEARN);
- }
-
- public L2ForwardingLearnService(Service service) {
- super(service);
- }
-
- /*
- * (Table:L2ForwardingLearn) Remote Tep Learning
- * Match: reg0 = ClassifierService.REG_VALUE_FROM_REMOTE
- * Action: learn and goto next table
- * table=105,reg0=0x2 actions=learn(table=110,hard_timeout=300,priority=16400,NXM_NX_TUN_ID[],NXM_OF_ETH_DST[]=NXM_OF_ETH_SRC[],output:NXM_OF_IN_PORT[]),goto_table:110
- */
- @Override
- public void programL2ForwardingLearnRule(Long dpidLong) {
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = "L2ForwardingLearn";
- FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable());
- List<Action> listAction = new ArrayList<>();
-
- MatchBuilder matchBuilder = new MatchBuilder();
- MatchUtils.addNxRegMatch(matchBuilder, new MatchUtils.RegMatch(ClassifierService.REG_FIELD, ClassifierService.REG_VALUE_FROM_REMOTE));
- flowBuilder.setMatch(matchBuilder.build());
-
- // Create learn action
-
- /*
- * learn header
- * 0 1 2 3 4 5 6 7 idleTO hardTO prio cook flags table finidle finhard
- *
- * learn flowmod
- * 0 1 2 3 learnFlowModType srcField dstField FlowModNumBits
- */
- String[] header = new String[] {
- "0", "300", "16400", "0", "0", "110", "0", "0"
- };
-
- String[][] flowMod = new String[3][];
- // NXM_NX_TUN_ID[]
- flowMod[0] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_FIELD.name(),
- LearnConstants.NxmOfFieldType.NXM_NX_TUN_ID.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_NX_TUN_ID.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_NX_TUN_ID.getFlowModHeaderLen() };
- // NXM_OF_ETH_DST[]=NXM_OF_ETH_SRC[]
- flowMod[1] = new String[] { LearnConstants.LearnFlowModsType.MATCH_FROM_FIELD.name(),
- LearnConstants.NxmOfFieldType.NXM_OF_ETH_SRC.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_ETH_DST.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_ETH_DST.getFlowModHeaderLen()};
- // output:NXM_OF_IN_PORT[]
- flowMod[2] = new String[] { LearnConstants.LearnFlowModsType.OUTPUT_TO_PORT.name(),
- LearnConstants.NxmOfFieldType.NXM_OF_IN_PORT.getHexType(),
- LearnConstants.NxmOfFieldType.NXM_OF_IN_PORT.getFlowModHeaderLen() };
-
- listAction.add(buildAction(0, header, flowMod));
-
- ApplyActions applyActions = new ApplyActionsBuilder().setAction(listAction).build();
- ApplyActionsCase applyActionsCase = new ApplyActionsCaseBuilder().setApplyActions(applyActions).build();
- InstructionsBuilder instructionsBuilder = new InstructionsBuilder();
- InstructionBuilder instructionBuilder = new InstructionBuilder();
- List<Instruction> instructions = new ArrayList<>();
-
- instructionBuilder.setInstruction(applyActionsCase);
- instructionBuilder.setOrder(0);
- instructionBuilder.setKey(new InstructionKey(0));
- instructions.add(instructionBuilder.build());
-
- // Next service GOTO Instructions Need to be appended to the List
- instructionBuilder = this.getMutablePipelineInstructionBuilder();
- instructionBuilder.setOrder(1);
- instructionBuilder.setKey(new InstructionKey(1));
- instructions.add(instructionBuilder.build());
-
- // Add InstructionBuilder to the Instruction(s)Builder List
- instructionsBuilder.setInstruction(instructions);
-
- // Add InstructionsBuilder to FlowBuilder
- flowBuilder.setInstructions(instructionsBuilder.build());
-
- writeFlow(flowBuilder, nodeBuilder);
-
- }
-
- /*
- * build Action
- *
- * copy from org.opendaylight.genius.mdsalutil.ActionType.learn
- */
- private Action buildAction(int newActionKey, String[] header, String[][] actionValues) {
- NxLearnBuilder learnBuilder = new NxLearnBuilder();
- learnBuilder.setIdleTimeout(Integer.parseInt(header[0]));
- learnBuilder.setHardTimeout(Integer.parseInt(header[1]));
- learnBuilder.setPriority(Integer.parseInt(header[2]));
- learnBuilder.setCookie(BigInteger.valueOf(Long.valueOf(header[3])));
- learnBuilder.setFlags(Integer.parseInt(header[4]));
- learnBuilder.setTableId(Short.parseShort(header[5]));
- learnBuilder.setFinIdleTimeout(Integer.parseInt(header[6]));
- learnBuilder.setFinHardTimeout(Integer.parseInt(header[7]));
-
- List<FlowMods> flowModsList = new ArrayList<>();
- for(String[] values : actionValues) {
- if(LearnFlowModsType.MATCH_FROM_FIELD.name().equals(values[0])) {
- FlowModAddMatchFromFieldBuilder builder = new FlowModAddMatchFromFieldBuilder();
- builder.setSrcField(Long.decode(values[1]));
- builder.setSrcOfs(0);
- builder.setDstField(Long.decode(values[2]));
- builder.setDstOfs(0);
- builder.setFlowModNumBits(Integer.parseInt(values[3]));
-
- FlowModsBuilder flowModsBuilder = new FlowModsBuilder();
- FlowModAddMatchFromFieldCaseBuilder caseBuilder = new FlowModAddMatchFromFieldCaseBuilder();
- caseBuilder.setFlowModAddMatchFromField(builder.build());
- flowModsBuilder.setFlowModSpec(caseBuilder.build());
- flowModsList.add(flowModsBuilder.build());
- } else if (LearnFlowModsType.MATCH_FROM_VALUE.name().equals(values[0])) {
- FlowModAddMatchFromValueBuilder builder = new FlowModAddMatchFromValueBuilder();
- builder.setValue(Integer.parseInt(values[1]));
- builder.setSrcField(Long.decode(values[2]));
- builder.setSrcOfs(0);
- builder.setFlowModNumBits(Integer.parseInt(values[3]));
-
- FlowModsBuilder flowModsBuilder = new FlowModsBuilder();
- FlowModAddMatchFromValueCaseBuilder caseBuilder = new FlowModAddMatchFromValueCaseBuilder();
- caseBuilder.setFlowModAddMatchFromValue(builder.build());
- flowModsBuilder.setFlowModSpec(caseBuilder.build());
- flowModsList.add(flowModsBuilder.build());
- } else if (LearnFlowModsType.COPY_FROM_FIELD.name().equals(values[0])) {
- FlowModCopyFieldIntoFieldBuilder builder = new FlowModCopyFieldIntoFieldBuilder();
- builder.setSrcField(Long.decode(values[1]));
- builder.setSrcOfs(0);
- builder.setDstField(Long.decode(values[2]));
- builder.setDstOfs(0);
- builder.setFlowModNumBits(Integer.parseInt(values[3]));
-
- FlowModsBuilder flowModsBuilder = new FlowModsBuilder();
- FlowModCopyFieldIntoFieldCaseBuilder caseBuilder = new FlowModCopyFieldIntoFieldCaseBuilder();
- caseBuilder.setFlowModCopyFieldIntoField(builder.build());
- flowModsBuilder.setFlowModSpec(caseBuilder.build());
- flowModsList.add(flowModsBuilder.build());
- } else if (LearnFlowModsType.COPY_FROM_VALUE.name().equals(values[0])) {
- FlowModCopyValueIntoFieldBuilder builder = new FlowModCopyValueIntoFieldBuilder();
- builder.setValue(Integer.parseInt(values[1]));
- builder.setDstField(Long.decode(values[2]));
- builder.setDstOfs(0);
- builder.setFlowModNumBits(Integer.parseInt(values[3]));
-
- FlowModsBuilder flowModsBuilder = new FlowModsBuilder();
- FlowModCopyValueIntoFieldCaseBuilder caseBuilder = new FlowModCopyValueIntoFieldCaseBuilder();
- caseBuilder.setFlowModCopyValueIntoField(builder.build());
- flowModsBuilder.setFlowModSpec(caseBuilder.build());
- flowModsList.add(flowModsBuilder.build());
- } else if (LearnFlowModsType.OUTPUT_TO_PORT.name().equals(values[0])) {
- FlowModOutputToPortBuilder builder = new FlowModOutputToPortBuilder();
- builder.setSrcField(Long.decode(values[1]));
- builder.setSrcOfs(0);
- builder.setFlowModNumBits(Integer.parseInt(values[2]));
-
- FlowModsBuilder flowModsBuilder = new FlowModsBuilder();
- FlowModOutputToPortCaseBuilder caseBuilder = new FlowModOutputToPortCaseBuilder();
- caseBuilder.setFlowModOutputToPort(builder.build());
- flowModsBuilder.setFlowModSpec(caseBuilder.build());
- flowModsList.add(flowModsBuilder.build());
- }
- }
- learnBuilder.setFlowMods(flowModsList);
-
- ActionBuilder abExt = new ActionBuilder();
- abExt.setKey(new ActionKey(newActionKey));
-
- abExt.setAction(new NxActionLearnNodesNodeTableFlowApplyActionsCaseBuilder()
- .setNxLearn(learnBuilder.build()).build());
- return abExt.build();
- }
-
- @Override
- public void setDependencies(BundleContext bundleContext, ServiceReference serviceReference) {
- super.setDependencies(bundleContext.getServiceReference(L2ForwardingLearnProvider.class.getName()), this);
- }
-
- @Override
- public void setDependencies(Object impl) {
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services;
-
-import java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import org.opendaylight.netvirt.openstack.netvirt.api.L2ForwardingProvider;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.AbstractServiceInstance;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.netvirt.openstack.netvirt.providers.ConfigInterface;
-import org.opendaylight.netvirt.utils.mdsal.openflow.ActionUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.FlowUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.InstructionUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.MatchUtils;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.OutputActionCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.OutputActionCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.output.action._case.OutputActionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
-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.flow.inventory.rev130819.FlowId;
-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.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;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionKey;
-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.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class L2ForwardingService extends AbstractServiceInstance implements ConfigInterface, L2ForwardingProvider {
- private static final Logger LOG = LoggerFactory.getLogger(L2ForwardingService.class);
- public L2ForwardingService() {
- super(Service.L2_FORWARDING);
- }
-
- public L2ForwardingService(Service service) {
- super(service);
- }
-
- /*
- * (Table:L2Forwarding) Local Unicast
- * Match: Tunnel ID and dMAC
- * Action: Output Port
- * table=2,tun_id=0x5,dl_dst=00:00:00:00:00:01 actions=output:2 goto:<next-table>
- */
- @Override
- public void programLocalUcastOut(Long dpidLong, String segmentationId,
- Long localPort, String attachedMac, boolean write) {
-
- String nodeName = OPENFLOW + dpidLong;
-
- NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
- FlowBuilder flowBuilder = new FlowBuilder();
-
- // Create the OF Match using MatchBuilder
- MatchBuilder matchBuilder = new MatchBuilder();
- MatchUtils.createTunnelIDMatch(matchBuilder, new BigInteger(segmentationId));
- MatchUtils.createDestEthMatch(matchBuilder, new MacAddress(attachedMac), null);
- flowBuilder.setMatch(matchBuilder.build());
-
- // Add Flow Attributes
- String flowName = "UcastOut_" + segmentationId + "_" + attachedMac;
- FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable());
-
- if (write) {
- // Set the Output Port/Iface
- Instruction setOutputPortInstruction =
- InstructionUtils.createOutputPortInstructions(new InstructionBuilder(), dpidLong, localPort)
- .setOrder(0)
- .setKey(new InstructionKey(0))
- .build();
-
- // Add InstructionsBuilder to FlowBuilder
- InstructionUtils.setFlowBuilderInstruction(flowBuilder, setOutputPortInstruction);
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
- }
-
- /*
- * (Table:2) Local VLAN unicast
- * Match: VLAN ID and dMAC
- * Action: Output Port
- * table=2,vlan_id=0x5,dl_dst=00:00:00:00:00:01 actions=output:2
- * table=110,dl_vlan=2001,dl_dst=fa:16:3e:a3:3b:cc actions=pop_vlan,output:1
- */
-
- @Override
- public void programLocalVlanUcastOut (Long dpidLong, String segmentationId, Long localPort, String attachedMac, boolean write) {
-
- String nodeName = OPENFLOW + dpidLong;
-
- NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
- FlowBuilder flowBuilder = new FlowBuilder();
-
- // Create the OF Match using MatchBuilder
- MatchBuilder matchBuilder = new MatchBuilder();
- MatchUtils.createVlanIdMatch(matchBuilder, new VlanId(Integer.valueOf(segmentationId)), true);
- MatchUtils.createDestEthMatch(matchBuilder, new MacAddress(attachedMac), null);
- flowBuilder.setMatch(matchBuilder.build());
-
- // Add Flow Attributes
- String flowName = "VlanUcastOut_" + segmentationId + "_" + localPort + "_" + attachedMac;
- FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable());
-
- if (write) {
- /* Strip vlan and store to tmp instruction space*/
- Instruction stripVlanInstruction = InstructionUtils.createPopVlanInstructions(new InstructionBuilder())
- .setOrder(0)
- .setKey(new InstructionKey(0))
- .build();
-
- // Set the Output Port/Iface
- Instruction setOutputPortInstruction =
- InstructionUtils.addOutputPortInstructions(new InstructionBuilder(), dpidLong, localPort,
- Collections.singletonList(stripVlanInstruction))
- .setOrder(1)
- .setKey(new InstructionKey(0))
- .build();
-
- // Add InstructionsBuilder to FlowBuilder
- InstructionUtils.setFlowBuilderInstruction(flowBuilder, setOutputPortInstruction);
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
- }
-
-
- /*
- * (Table:2) Local Broadcast Flood
- * Match: Tunnel ID and dMAC (::::FF:FF)
- * table=2,priority=16384,tun_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
- * actions=output:2,3,4,5
- */
-
- @Override
- public void programLocalBcastOut(Long dpidLong, String segmentationId, Long localPort, boolean write) {
-
- String nodeName = OPENFLOW + dpidLong;
-
- NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
- FlowBuilder flowBuilder = new FlowBuilder();
-
- // Create the OF Match using MatchBuilder
- 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());
-
- // Add Flow Attributes
- String flowName = "BcastOut_" + segmentationId;
- FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable())
- .setPriority(16384);
-
- Flow flow = this.getFlow(flowBuilder, nodeBuilder);
-
- // Retrieve the existing instructions
- List<Instruction> existingInstructions = InstructionUtils.extractExistingInstructions(flow);
-
- if (write) {
- // Create output port list
- Instruction outputPortInstruction =
- createOutputPortInstructions(new InstructionBuilder(), dpidLong, localPort, existingInstructions)
- .setOrder(0)
- .setKey(new InstructionKey(0))
- .build();
-
- /* 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
- InstructionUtils.setFlowBuilderInstruction(flowBuilder, outputPortInstruction);
-
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- InstructionBuilder ib = new InstructionBuilder();
- boolean flowRemove = InstructionUtils.removeOutputPortFromInstructions(ib, dpidLong, localPort,
- existingInstructions);
- if (flowRemove) {
- /* if all ports are removed, remove flow */
- removeFlow(flowBuilder, nodeBuilder);
- } else {
- /* Install instruction with new output port list*/
- Instruction outputPortInstruction = ib
- .setOrder(0)
- .setKey(new InstructionKey(0))
- .build();
-
- // Add InstructionsBuilder to FlowBuilder
- InstructionUtils.setFlowBuilderInstruction(flowBuilder, outputPortInstruction);
-
- writeFlow(flowBuilder, nodeBuilder);
- }
- }
- }
-
- /*
- * (Table:2) Local VLAN Broadcast Flood
- * Match: vlan ID and dMAC (::::FF:FF)
- * table=2,priority=16384,vlan_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
- * actions=strip_vlan, output:2,3,4,5
- * table=110,dl_vlan=2001,dl_dst=01:00:00:00:00:00/01:00:00:00:00:00 actions=output:2,pop_vlan,output:1,output:3,output:4
- */
-
- @Override
- public void programLocalVlanBcastOut(Long dpidLong, String segmentationId,
- Long localPort, Long ethPort, boolean write) {
-
- String nodeName = OPENFLOW + dpidLong;
-
- NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
- FlowBuilder flowBuilder = new FlowBuilder();
-
- // Create the OF Match using MatchBuilder
- 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());
-
- // Add Flow Attributes
- String flowName = "VlanBcastOut_" + segmentationId + "_" + ethPort;
- FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable())
- .setPriority(16384);
- Flow flow = this.getFlow(flowBuilder, nodeBuilder);
-
- // Retrieve the existing instructions
- List<Instruction> existingInstructions = InstructionUtils.extractExistingInstructions(flow);
-
- if (write) {
- 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.
- */
- 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(nodeConnectorUri)) {
- addNew = false;
- break;
- }
- }
- }
-
- if (addNew) {
- actionList.add(
- new ActionBuilder()
- .setAction(
- ActionUtils.outputAction(new NodeConnectorId(nodeName + ":" + localPort)))
- .setOrder(actionList.size())
- .setKey(new ActionKey(actionList.size()))
- .build());
- }
- }
-
- 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
- InstructionUtils.setFlowBuilderInstruction(flowBuilder, applyActionsInstruction);
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- InstructionBuilder ib = new InstructionBuilder();
- boolean flowRemove = removeOutputPortFromInstructions(ib, dpidLong, localPort, ethPort,
- existingInstructions);
- if (flowRemove) {
- /* if all ports are removed, remove flow */
- removeFlow(flowBuilder, nodeBuilder);
- } else {
- /* Install instruction with new output port list*/
- Instruction outputPortInstruction = ib
- .setOrder(0)
- .setKey(new InstructionKey(0))
- .build();
-
- // Add InstructionsBuilder to FlowBuilder
- InstructionUtils.setFlowBuilderInstruction(flowBuilder, outputPortInstruction);
- writeFlow(flowBuilder, nodeBuilder);
- }
- }
- }
-
- private boolean removeOutputPortFromInstructions(InstructionBuilder ib, Long dpidLong, Long localPort,
- Long ethPort, List<Instruction> instructions) {
- List<Action> actionList = new ArrayList<>();
- boolean removeFlow = true;
-
- 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
- int index = 2;
- for (Action action : oldActionList) {
- if (action.getAction() instanceof OutputActionCase) {
- OutputActionCase opAction = (OutputActionCase) action.getAction();
- if (opAction.getOutputAction().getOutputNodeConnector().equals(ethNodeConnectorUri)) {
- actionList.add(action);
- } 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);
- }
- }
- 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;
- }
-
- return removeFlow;
- }
-
- /*
- * (Table:1) Local Table Miss
- * Match: Any Remaining Flows w/a VLAN ID
- * Action: Drop w/ a low priority
- * table=2,priority=8192,vlan_id=0x5 actions=drop
- */
-
- @Override
- public void programLocalVlanTableMiss(Long dpidLong, String segmentationId, boolean write) {
-
- String nodeName = OPENFLOW + dpidLong;
-
- NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
- FlowBuilder flowBuilder = new FlowBuilder();
-
- // Create Match(es) and Set them in the FlowBuilder Object
- flowBuilder.setMatch(
- MatchUtils.createVlanIdMatch(new MatchBuilder(), new VlanId(Integer.valueOf(segmentationId)),
- true).build());
-
- if (write) {
- // Call the InstructionBuilder Methods Containing Actions
- Instruction dropInstruction = InstructionUtils.createDropInstructions(new InstructionBuilder())
- .setOrder(0)
- .setKey(new InstructionKey(0))
- .build();
-
- // Add InstructionsBuilder to FlowBuilder
- InstructionUtils.setFlowBuilderInstruction(flowBuilder, dropInstruction);
- }
-
- // Add Flow Attributes
- String flowName = "LocalTableMiss_" + segmentationId;
- FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable())
- .setPriority(8192);
- if (write) {
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
- }
-
-
- /*
- * (Table:1) Egress Tunnel Traffic
- * Match: Destination Ethernet Addr and Local InPort
- * Instruction: Set TunnelID and GOTO Table Tunnel Table (n)
- * table=1,tun_id=0x5,dl_dst=00:00:00:00:00:08 \
- * actions=output:10,goto_table:2"
- */
- // TODO : Check on the reason why the original handleTunnelOut was chaining the traffic to table 2
- @Override
- public void programTunnelOut(Long dpidLong, String segmentationId, Long OFPortOut, String attachedMac, boolean write) {
-
- String nodeName = OPENFLOW + dpidLong;
-
- NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
- FlowBuilder flowBuilder = new FlowBuilder();
-
- // Create the OF Match using MatchBuilder
- MatchBuilder matchBuilder = new MatchBuilder();
- MatchUtils.createTunnelIDMatch(matchBuilder, new BigInteger(segmentationId));
- MatchUtils.createDestEthMatch(matchBuilder, new MacAddress(attachedMac), null);
- flowBuilder.setMatch(matchBuilder.build());
-
- // Add Flow Attributes
- String flowName = "UcastOut_" + segmentationId + "_" + attachedMac;
- FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable());
-
- if (write) {
- // Set the Output Port/Iface
- Instruction outputPortInstruction =
- InstructionUtils.createOutputPortInstructions(new InstructionBuilder(), dpidLong, OFPortOut)
- .setOrder(0)
- .setKey(new InstructionKey(1))
- .build();
-
- // Add InstructionsBuilder to FlowBuilder
- InstructionUtils.setFlowBuilderInstruction(flowBuilder, outputPortInstruction);
-
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
- }
-
- /*
- * (Table:1) Egress VLAN Traffic
- * Match: Destination Ethernet Addr and VLAN id
- * Instruction: GOTO Table Table 2
- * table=1,vlan_id=0x5,dl_dst=00:00:00:00:00:08 \
- * actions= goto_table:2"
- */
- // TODO : Check on the reason why the original handleTunnelOut was chaining the traffic to table 2
- @Override
- public void programVlanOut(Long dpidLong, String segmentationId, Long ethPort, String attachedMac, boolean write) {
-
- String nodeName = OPENFLOW + dpidLong;
-
- NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
- FlowBuilder flowBuilder = new FlowBuilder();
-
- // Create the OF Match using MatchBuilder
- MatchBuilder matchBuilder = new MatchBuilder();
- MatchUtils.createVlanIdMatch(matchBuilder, new VlanId(Integer.valueOf(segmentationId)), true);
- MatchUtils.createDestEthMatch(matchBuilder, new MacAddress(attachedMac), null);
- flowBuilder.setMatch(matchBuilder.build());
-
- // Add Flow Attributes
- String flowName = "VlanOut_" + segmentationId + "_" + ethPort + "_" + attachedMac;
- FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable());
-
- if (write) {
- // Instructions List Stores Individual Instructions
- Instruction outputPortInstruction =
- InstructionUtils.createOutputPortInstructions(new InstructionBuilder(), dpidLong, ethPort)
- .setOrder(0)
- .setKey(new InstructionKey(1))
- .build();
-
- // Add InstructionsBuilder to FlowBuilder
- InstructionUtils.setFlowBuilderInstruction(flowBuilder, outputPortInstruction);
-
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
- }
-
- /*
- * (Table:1) Egress Tunnel Traffic
- * Match: Destination Ethernet Addr and Local InPort
- * Instruction: Set TunnelID and GOTO Table Tunnel Table (n)
- * table=1,priority=16384,tun_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
- * actions=output:10,output:11,goto_table:2
- */
- @Override
- public void programTunnelFloodOut(Long dpidLong, String segmentationId, Long OFPortOut, boolean write) {
-
- String nodeName = OPENFLOW + dpidLong;
-
- 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));
- MatchUtils.createTunnelIDMatch(matchBuilder, new BigInteger(segmentationId));
- // Match DMAC
- MatchUtils.createDestEthMatch(matchBuilder, new MacAddress("01:00:00:00:00:00"),
- new MacAddress("01:00:00:00:00:00"));
- flowBuilder.setMatch(matchBuilder.build());
-
- // Add Flow Attributes
- 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
- List<Instruction> existingInstructions = InstructionUtils.extractExistingInstructions(flow);
-
- if (write) {
- // Set the Output Port/Iface
- Instruction outputPortInstruction =
- createOutputPortInstructions(new InstructionBuilder(), dpidLong, OFPortOut, existingInstructions)
- .setOrder(0)
- .setKey(new InstructionKey(0))
- .build();
-
- // Add InstructionsBuilder to FlowBuilder
- 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);
- if (flowRemove) {
- /* if all port are removed, remove the flow too. */
- removeFlow(flowBuilder, nodeBuilder);
- } else {
- /* Install instruction with new output port list*/
- Instruction instruction = ib
- .setOrder(0)
- .setKey(new InstructionKey(0))
- .build();
-
- // Add InstructionsBuilder to FlowBuilder
- InstructionUtils.setFlowBuilderInstruction(flowBuilder, instruction);
- writeFlow(flowBuilder, nodeBuilder);
- }
- }
- }
-
- /*
- * (Table:110) Flooding local unknown unicast Traffic
- * Match: TunnelID and Unknown unicast and Local InPort
- * Instruction: Set TunnelID and GOTO Table Tunnel Table (n)
- * table=110,priority=16380,tun_id=0x5,dl_dst=00:00:00:00:00:00/01:00:00:00:00:00 \
- * actions=output:10,output:11
- */
- @Override
- public void programTunnelUnknownUcastFloodOut(Long dpidLong, String segmentationId, Long OFPortOut, boolean write) {
-
- String nodeName = OPENFLOW + dpidLong;
-
- 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));
- MatchUtils.createTunnelIDMatch(matchBuilder, new BigInteger(segmentationId));
- // Match DMAC
- MatchUtils.createDestEthMatch(matchBuilder, new MacAddress("00:00:00:00:00:00"),
- new MacAddress("01:00:00:00:00:00"));
- flowBuilder.setMatch(matchBuilder.build());
-
- // Add Flow Attributes
- String flowName = "TunnelUnknownUcastFloodOut_" + segmentationId;
- final FlowId flowId = new FlowId(flowName);
- flowBuilder
- .setId(flowId)
- .setBarrier(true)
- .setTableId(getTable())
- .setKey(new FlowKey(flowId))
- .setPriority(16380)
- .setFlowName(flowName)
- .setHardTimeout(0)
- .setIdleTimeout(0);
-
- Flow flow = this.getFlow(flowBuilder, nodeBuilder);
- // Instantiate the Builders for the OF Actions and Instructions
- List<Instruction> existingInstructions = InstructionUtils.extractExistingInstructions(flow);
-
- if (write) {
- // Set the Output Port/Iface
- Instruction outputPortInstruction =
- createOutputPortInstructions(new InstructionBuilder(), dpidLong, OFPortOut, existingInstructions)
- .setOrder(0)
- .setKey(new InstructionKey(0))
- .build();
-
- // Add InstructionsBuilder to FlowBuilder
- 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);
- if (flowRemove) {
- /* if all port are removed, remove the flow too. */
- removeFlow(flowBuilder, nodeBuilder);
- } else {
- /* Install instruction with new output port list*/
- Instruction instruction = ib
- .setOrder(0)
- .setKey(new InstructionKey(0))
- .build();
-
- // Add InstructionsBuilder to FlowBuilder
- InstructionUtils.setFlowBuilderInstruction(flowBuilder, instruction);
- writeFlow(flowBuilder, nodeBuilder);
- }
- }
- }
-
- /*
- * (Table:1) Table Drain w/ Catch All
- * Match: Vlan ID
- * Action: Output port eth interface
- * table=1,priority=8192,vlan_id=0x5 actions= output port:eth1
- * table=110,priority=8192,dl_vlan=2001 actions=output:2
- */
-
- @Override
- public void programVlanMiss(Long dpidLong, String segmentationId, Long ethPort, boolean write) {
-
- String nodeName = OPENFLOW + dpidLong;
-
- NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
- FlowBuilder flowBuilder = new FlowBuilder();
-
- // Create Match(es) and Set them in the FlowBuilder Object
- flowBuilder.setMatch(
- MatchUtils.createVlanIdMatch(new MatchBuilder(), new VlanId(Integer.valueOf(segmentationId)),
- true).build());
-
- if (write) {
- // Set the Output Port/Iface
- Instruction outputPortInstruction =
- InstructionUtils.createOutputPortInstructions(new InstructionBuilder(), dpidLong, ethPort)
- .setOrder(0)
- .setKey(new InstructionKey(1))
- .build();
-
- // Add InstructionsBuilder to FlowBuilder
- InstructionUtils.setFlowBuilderInstruction(flowBuilder, outputPortInstruction);
- }
-
- // Add Flow Attributes
- String flowName = "VlanMiss_" + segmentationId;
- FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable())
- .setPriority(8192);
- if (write) {
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
- }
-
- /**
- * Create Output Port Group Instruction
- *
- * @param ib Map InstructionBuilder without any instructions
- * @param dpidLong Long the datapath ID of a switch/node
- * @param port Long representing a port on a switch/node
- * @param instructions List of instructions
- * @return ib InstructionBuilder Map with instructions
- */
- protected InstructionBuilder createOutputPortInstructions(InstructionBuilder ib,
- Long dpidLong, Long port ,
- List<Instruction> instructions) {
- 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 = new ArrayList<>();
- ActionBuilder ab = new ActionBuilder();
-
- List<Action> existingActions;
- if (instructions != null && instructions.size() > 0) {
- /**
- * First instruction is the one containing the output ports.
- * So, only extract the actions from that.
- */
- Instruction in = instructions.get(0);
- if (in.getInstruction() instanceof ApplyActionsCase) {
- existingActions = (((ApplyActionsCase) in.getInstruction()).getApplyActions().getAction());
- // Only include output actions
- for (Action action : existingActions) {
- if (action.getAction() instanceof OutputActionCase) {
- actionList.add(action);
- }
- }
- }
- }
- /* Create output action for this port*/
- OutputActionBuilder oab = new OutputActionBuilder();
- oab.setOutputNodeConnector(ncid);
- ab.setAction(new OutputActionCaseBuilder().setOutputAction(oab.build()).build());
- boolean addNew = true;
-
- /* Find the group action and get the group */
- for (Action action : actionList) {
- OutputActionCase opAction = (OutputActionCase)action.getAction();
- /* If output port action already in the action list of one of the buckets, skip */
- if (opAction.getOutputAction().getOutputNodeConnector().equals(new Uri(ncid))) {
- addNew = false;
- break;
- }
- }
- if (addNew) {
- ab.setOrder(actionList.size());
- ab.setKey(new ActionKey(actionList.size()));
- actionList.add(ab.build());
- }
- // Create an Apply Action
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
- LOG.debug("createOutputPortInstructions() : applyAction {}", aab.build());
- return ib;
- }
-
- @Override
- public void setDependencies(BundleContext bundleContext, ServiceReference serviceReference) {
- super.setDependencies(bundleContext.getServiceReference(L2ForwardingProvider.class.getName()), this);
- }
-
- @Override
- public void setDependencies(Object impl) {
-
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services;
-
-import org.opendaylight.netvirt.openstack.netvirt.api.L2RewriteProvider;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.AbstractServiceInstance;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.netvirt.openstack.netvirt.providers.ConfigInterface;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-
-public class L2RewriteService extends AbstractServiceInstance implements ConfigInterface, L2RewriteProvider {
- public L2RewriteService() {
- super(Service.L2_REWRITE);
- }
-
- public L2RewriteService(Service service) {
- super(service);
- }
-
- @Override
- public void setDependencies(BundleContext bundleContext, ServiceReference serviceReference) {
- super.setDependencies(bundleContext.getServiceReference(L2RewriteProvider.class.getName()), this);
- }
-
- @Override
- public void setDependencies(Object impl) {
-
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services;
-
-import java.math.BigInteger;
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.util.ArrayList;
-import java.util.List;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.L3ForwardingProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.Status;
-import org.opendaylight.netvirt.openstack.netvirt.api.StatusCode;
-import org.opendaylight.netvirt.openstack.netvirt.providers.ConfigInterface;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.AbstractServiceInstance;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.netvirt.utils.mdsal.openflow.FlowUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.InstructionUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.MatchUtils;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.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.list.Instruction;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class L3ForwardingService extends AbstractServiceInstance implements L3ForwardingProvider, ConfigInterface {
- private static final Logger LOG = LoggerFactory.getLogger(L3ForwardingService.class);
-
- public L3ForwardingService() {
- super(Service.L3_FORWARDING);
- }
-
- public L3ForwardingService(Service service) {
- super(service);
- }
-
- @Override
- public Status programForwardingTableEntry(Long dpid, String segmentationId, InetAddress ipAddress,
- String macAddress, Action action) {
- if (ipAddress instanceof Inet6Address) {
- // WORKAROUND: For now ipv6 is not supported
- // TODO: implement ipv6 case
- LOG.debug("ipv6 address is not implemented yet. dpid {} segmentationId {} ipAddress {} macAddress {} Action {}",
- dpid, segmentationId, ipAddress, macAddress, action);
- return new Status(StatusCode.NOTIMPLEMENTED);
- }
-
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpid);
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = "L3Forwarding_" + segmentationId + "_" + ipAddress.getHostAddress();
- FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable()).setPriority(1024);
-
- MatchBuilder matchBuilder = new MatchBuilder();
- MatchUtils.createTunnelIDMatch(matchBuilder, new BigInteger(segmentationId));
- MatchUtils.createDstL3IPv4Match(matchBuilder, MatchUtils.iPv4PrefixFromIPv4Address(ipAddress.getHostAddress()));
-
- flowBuilder.setMatch(matchBuilder.build());
-
- if (action.equals(Action.ADD)) {
- // Instructions List Stores Individual Instructions
- InstructionsBuilder isb = new InstructionsBuilder();
- List<Instruction> instructions = new ArrayList<>();
- InstructionBuilder ib = new InstructionBuilder();
-
- // Set Dest Mac address
- InstructionUtils.createDlDstInstructions(ib, new MacAddress(macAddress));
- ib.setOrder(0);
- ib.setKey(new InstructionKey(0));
- instructions.add(ib.build());
-
- // Goto Next Table
- ib = getMutablePipelineInstructionBuilder();
- ib.setOrder(1);
- ib.setKey(new InstructionKey(1));
- instructions.add(ib.build());
-
- flowBuilder.setInstructions(isb.setInstruction(instructions).build());
-
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
-
- // ToDo: WriteFlow/RemoveFlow should return something we can use to check success
- return new Status(StatusCode.SUCCESS);
- }
-
- @Override
- public void setDependencies(BundleContext bundleContext, ServiceReference serviceReference) {
- super.setDependencies(bundleContext.getServiceReference(L3ForwardingProvider.class.getName()), this);
- }
-
- @Override
- public void setDependencies(Object impl) {
-
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 SDN Hub, LLC. 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.netvirt.openstack.netvirt.providers.openflow13.services;
-
-import java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import org.opendaylight.netvirt.openstack.netvirt.NetworkHandler;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-import org.opendaylight.netvirt.openstack.netvirt.api.LoadBalancerConfiguration;
-import org.opendaylight.netvirt.openstack.netvirt.api.LoadBalancerConfiguration.LoadBalancerPoolMember;
-import org.opendaylight.netvirt.openstack.netvirt.api.LoadBalancerProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.openstack.netvirt.api.Status;
-import org.opendaylight.netvirt.openstack.netvirt.api.StatusCode;
-import org.opendaylight.netvirt.openstack.netvirt.providers.ConfigInterface;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.AbstractServiceInstance;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.netvirt.utils.mdsal.openflow.ActionUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.FlowUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.MatchUtils;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
-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.FlowBuilder;
-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.ApplyActionsCaseBuilder;
-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;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.VlanId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.action.rev140421.OfjNxHashFields;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.action.rev140421.OfjNxMpAlgorithm;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg1;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg2;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.dst.choice.grouping.dst.choice.DstNxRegCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class LoadBalancerService extends AbstractServiceInstance implements LoadBalancerProvider, ConfigInterface {
-
- private static final Logger LOG = LoggerFactory.getLogger(LoadBalancerProvider.class);
- private static final int DEFAULT_FLOW_PRIORITY = 32768;
- private static final Long FIRST_PASS_REGA_MATCH_VALUE = 0L;
- private static final Long SECOND_PASS_REGA_MATCH_VALUE = 1L;
-
- private static final Class<? extends NxmNxReg> REG_FIELD_A = NxmNxReg1.class;
- private static final Class<? extends NxmNxReg> REG_FIELD_B = NxmNxReg2.class;
-
- private volatile Southbound southbound;
-
- public LoadBalancerService() {
- super(Service.LOAD_BALANCER);
- }
-
- public LoadBalancerService(Service service) {
- super(service);
- }
-
- private String getDpid(Node node) {
- long dpid = southbound.getDataPathId(node);
- if (dpid == 0) {
- LOG.warn("getDpid: DPID could not be found for node: {}", node.getNodeId().getValue());
- }
- return String.valueOf(dpid);
- }
-
- /**
- * When this method is called, we do the following for minimizing flow updates:
- * 1. Overwrite the solo multipath rule that applies to all members
- * 2. Append second pass rule for the header rewriting specific to this member
- * 3. Append reverse rules specific to this member
- */
- @Override
- public Status programLoadBalancerPoolMemberRules(Node node,
- LoadBalancerConfiguration lbConfig, LoadBalancerPoolMember member,
- org.opendaylight.netvirt.openstack.netvirt.api.Action action) {
- if (lbConfig == null || member == null) {
- LOG.error("Null value for LB config {} or Member {}", lbConfig, member);
- return new Status(StatusCode.BADREQUEST);
- }
- if (!lbConfig.isValid()) {
- LOG.error("LB config is invalid: {}", lbConfig);
- return new Status(StatusCode.BADREQUEST);
- }
- LOG.debug("Performing {} rules for member {} with index {} on LB with VIP {} and total members {}",
- action, member.getIP(), member.getIndex(), lbConfig.getVip(), lbConfig.getMembers().size());
-
- NodeBuilder nodeBuilder = new NodeBuilder();
- nodeBuilder.setId(new NodeId(Constants.OPENFLOW_NODE_PREFIX + getDpid(node)));
- nodeBuilder.setKey(new NodeKey(nodeBuilder.getId()));
-
- //Update the multipath rule
- manageLoadBalancerVIPRulesFirstPass(nodeBuilder, lbConfig, true);
-
- if (action.equals(org.opendaylight.netvirt.openstack.netvirt.api.Action.ADD)) {
- manageLoadBalancerMemberVIPRulesSecondPass(nodeBuilder, lbConfig, member, true);
- manageLoadBalancerMemberReverseRules(nodeBuilder, lbConfig, member, true);
- return new Status(StatusCode.SUCCESS);
- }
- /* TODO: Delete single member.
- * For now, removing a member requires deleting the full LB instance and re-adding
- */
- return new Status(StatusCode.NOTIMPLEMENTED);
- }
-
- /**
- * When this method is called, we perform the following:
- * 1. Write the solo multipath rule that applies to all members
- * 2. Append second pass rules for the header rewriting for all members
- * 3. Append reverse rules for all the members, specific to the protocol/port
- */
- @Override
- public Status programLoadBalancerRules(Node node, LoadBalancerConfiguration lbConfig,
- org.opendaylight.netvirt.openstack.netvirt.api.Action action) {
- if (lbConfig == null || !lbConfig.isValid()) {
- LOG.error("LB config is invalid: {}", lbConfig);
- return new Status(StatusCode.BADREQUEST);
- }
- LOG.debug("Performing {} rules for VIP {} and {} members", action, lbConfig.getVip(), lbConfig.getMembers().size());
-
- NodeBuilder nodeBuilder = new NodeBuilder();
- nodeBuilder.setId(new NodeId(Constants.OPENFLOW_NODE_PREFIX + getDpid(node)));
- nodeBuilder.setKey(new NodeKey(nodeBuilder.getId()));
-
- if (action.equals(org.opendaylight.netvirt.openstack.netvirt.api.Action.ADD)) {
- manageLoadBalancerVIPRulesFirstPass(nodeBuilder, lbConfig, true);
- manageLoadBalancerVIPRulesSecondPass(nodeBuilder, lbConfig, true);
- manageLoadBalancerReverseRules(nodeBuilder, lbConfig, true);
- return new Status(StatusCode.SUCCESS);
- }
- else if (action.equals(org.opendaylight.netvirt.openstack.netvirt.api.Action.DELETE)) {
- manageLoadBalancerVIPRulesFirstPass(nodeBuilder, lbConfig, false);
- manageLoadBalancerVIPRulesSecondPass(nodeBuilder, lbConfig, false);
- manageLoadBalancerReverseRules(nodeBuilder, lbConfig, false);
- return new Status(StatusCode.SUCCESS);
- }
-
- return new Status(StatusCode.NOTIMPLEMENTED);
- }
-
- /**
- * Method to insert/remove default rule for traffic destined to the VIP and no
- * server selection performed yet
- * @param nodeBuilder NodeBuilder
- * @param lbConfig LoadBalancerConfiguration
- * @param write Boolean to indicate of the flow is to be inserted or removed
- */
- private void manageLoadBalancerVIPRulesFirstPass(NodeBuilder nodeBuilder, LoadBalancerConfiguration lbConfig,
- boolean write) {
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = "LOADBALANCER_FORWARD_FLOW1_" + lbConfig.getProviderSegmentationId() + "_" + lbConfig.getVip();
- FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable()).setPriority(DEFAULT_FLOW_PRIORITY);
-
- MatchBuilder matchBuilder = new MatchBuilder();
-
- // Match Tunnel-ID, VIP, and Reg0==0
- if (lbConfig.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VXLAN) ||
- lbConfig.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_GRE)) {
- MatchUtils.createTunnelIDMatch(matchBuilder, new BigInteger(lbConfig.getProviderSegmentationId()));
- } else if (lbConfig.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VLAN)) {
- MatchUtils.createVlanIdMatch(matchBuilder, new VlanId(Integer.valueOf(lbConfig.getProviderSegmentationId())), true);
- } else {
- return; //Should not get here. TODO: Other types
- }
-
- MatchUtils.createDstL3IPv4Match(matchBuilder, MatchUtils.iPv4PrefixFromIPv4Address(lbConfig.getVip()));
- MatchUtils.addNxRegMatch(matchBuilder, new MatchUtils.RegMatch(REG_FIELD_A, FIRST_PASS_REGA_MATCH_VALUE));
- flowBuilder.setMatch(matchBuilder.build());
-
- if (write) {
- // Create the OF Actions and Instructions
- InstructionsBuilder isb = new InstructionsBuilder();
-
- // Instructions List Stores Individual Instructions
- List<Instruction> instructions = new ArrayList<>();
-
- List<Action> actionList = new ArrayList<>();
-
- ActionBuilder ab = new ActionBuilder();
- ab.setAction(ActionUtils.nxLoadRegAction(new DstNxRegCaseBuilder().setNxReg(REG_FIELD_A).build(),
- BigInteger.valueOf(SECOND_PASS_REGA_MATCH_VALUE)));
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
- actionList.add(ab.build());
-
- ab = new ActionBuilder();
- ab.setAction(ActionUtils.nxMultipathAction(OfjNxHashFields.NXHASHFIELDSSYMMETRICL4,
- 0, OfjNxMpAlgorithm.NXMPALGMODULON,
- lbConfig.getMembers().size()-1, //By Nicira-Ext spec, this field is max_link minus 1
- 0L, new DstNxRegCaseBuilder().setNxReg(REG_FIELD_B).build(),
- 0, 31));
- ab.setOrder(1);
- ab.setKey(new ActionKey(1));
- actionList.add(ab.build());
-
- ab = new ActionBuilder();
- ab.setAction(ActionUtils.nxResubmitAction(null, this.getTable()));
- ab.setOrder(2);
- ab.setKey(new ActionKey(2));
- actionList.add(ab.build());
-
- // Create an Apply Action
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
- InstructionBuilder ib = new InstructionBuilder();
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
-
- // Call the InstructionBuilder Methods Containing Actions
- ib.setOrder(0);
- ib.setKey(new InstructionKey(0));
- instructions.add(ib.build());
-
- // Add InstructionBuilder to the Instruction(s)Builder List
- isb.setInstruction(instructions);
-
- // Add InstructionsBuilder to FlowBuilder
- flowBuilder.setInstructions(isb.build());
-
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
- }
-
- /*
- * Method to program each rule that matches on Reg0 and Reg1 to insert appropriate header rewriting
- * rules for all members. This function calls manageLoadBalancerMemberVIPRulesSecondPass in turn.
- * @param nodeBuilder Node to insert rule to
- * @param lbConfig Configuration for this LoadBalancer instance
- * @param write Boolean to indicate of the flow is to be inserted or removed
- */
- private void manageLoadBalancerVIPRulesSecondPass(NodeBuilder nodeBuilder, LoadBalancerConfiguration lbConfig, boolean write) {
- for(Map.Entry<String, LoadBalancerPoolMember> entry : lbConfig.getMembers().entrySet()){
- manageLoadBalancerMemberVIPRulesSecondPass(nodeBuilder, lbConfig, entry.getValue(), write);
- }
- }
-
- private void manageLoadBalancerMemberVIPRulesSecondPass(NodeBuilder nodeBuilder,
- LoadBalancerConfiguration lbConfig,
- LoadBalancerPoolMember member, boolean write) {
- String vip = lbConfig.getVip();
-
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = "LOADBALANCER_FORWARD_FLOW2_" + lbConfig.getProviderSegmentationId() + "_"
- + vip + "_" + member.getIP();
- FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable()).setPriority(DEFAULT_FLOW_PRIORITY+1);
-
- MatchBuilder matchBuilder = new MatchBuilder();
-
- // Match Tunnel-ID, VIP, Reg0==1 and Reg1==Index of member
- if (lbConfig.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VXLAN) ||
- lbConfig.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_GRE)) {
- MatchUtils.createTunnelIDMatch(matchBuilder, new BigInteger(lbConfig.getProviderSegmentationId()));
- } else if (lbConfig.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VLAN)) {
- MatchUtils.createVlanIdMatch(matchBuilder, new VlanId(Integer.valueOf(lbConfig.getProviderSegmentationId())), true);
- } else {
- return; //Should not get here. TODO: Other types
- }
-
- MatchUtils.createDstL3IPv4Match(matchBuilder, MatchUtils.iPv4PrefixFromIPv4Address(vip));
- MatchUtils.addNxRegMatch(matchBuilder, new MatchUtils.RegMatch(REG_FIELD_A, SECOND_PASS_REGA_MATCH_VALUE),
- new MatchUtils.RegMatch(REG_FIELD_B, (long)member.getIndex()));
- flowBuilder.setMatch(matchBuilder.build());
-
- if (write) {
- // Create the OF Actions and Instructions
- InstructionsBuilder isb = new InstructionsBuilder();
-
- // Instructions List Stores Individual Instructions
- List<Instruction> instructions = new ArrayList<>();
-
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab = new ActionBuilder();
- ab.setAction(ActionUtils.setDlDstAction(new MacAddress(member.getMAC())));
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
- actionList.add(ab.build());
-
- ab = new ActionBuilder();
- Ipv4Builder ipb = new Ipv4Builder().setIpv4Address(MatchUtils.iPv4PrefixFromIPv4Address(member.getIP()));
- ab.setAction(ActionUtils.setNwDstAction(ipb.build()));
- ab.setOrder(1);
- ab.setKey(new ActionKey(1));
- actionList.add(ab.build());
-
- // Create an Apply Action
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
-
- // Call the InstructionBuilder Methods Containing Actions
- InstructionBuilder ib = new InstructionBuilder();
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
- ib.setOrder(0);
- ib.setKey(new InstructionKey(0));
- instructions.add(ib.build());
-
- // Call the InstructionBuilder Methods Containing Actions
- ib = this.getMutablePipelineInstructionBuilder();
- ib.setOrder(1);
- ib.setKey(new InstructionKey(1));
- instructions.add(ib.build());
-
- // Add InstructionBuilder to the Instruction(s)Builder List
- isb.setInstruction(instructions);
-
- // Add InstructionsBuilder to FlowBuilder
- flowBuilder.setInstructions(isb.build());
-
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
- }
-
- /**
- * Method to program all reverse rules that matches member {IP, Protocol, Port} for all members.
- * This function calls manageLoadBalancerMemberReverseRules in turn.
- * @param nodeBuilder Node to insert rule to
- * @param lbConfig Configuration for this LoadBalancer instance
- */
- private void manageLoadBalancerReverseRules(NodeBuilder nodeBuilder, LoadBalancerConfiguration lbConfig, boolean write) {
- for(Map.Entry<String, LoadBalancerPoolMember> entry : lbConfig.getMembers().entrySet()){
- manageLoadBalancerMemberReverseRules(nodeBuilder, lbConfig, entry.getValue(), write);
- }
- }
-
- private void manageLoadBalancerMemberReverseRules(NodeBuilder nodeBuilder, LoadBalancerConfiguration lbConfig,
- LoadBalancerPoolMember member, boolean write) {
-
- String vip = lbConfig.getVip();
- String vmac = lbConfig.getVmac();
-
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = "LOADBALANCER_REVERSE_FLOW_" + lbConfig.getProviderSegmentationId() +
- vip + "_" + member.getIP();
- FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable()).setPriority(DEFAULT_FLOW_PRIORITY);
-
- MatchBuilder matchBuilder = new MatchBuilder();
-
- // Match Tunnel-ID, MemberIP, and Protocol/Port
- if (lbConfig.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VXLAN) ||
- lbConfig.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_GRE)) {
- MatchUtils.createTunnelIDMatch(matchBuilder, new BigInteger(lbConfig.getProviderSegmentationId()));
- } else if (lbConfig.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VLAN)) {
- MatchUtils.createVlanIdMatch(matchBuilder,
- new VlanId(Integer.valueOf(lbConfig.getProviderSegmentationId())), true);
- } else {
- return; //Should not get here. TODO: Other types
- }
-
- MatchUtils.createSrcL3IPv4Match(matchBuilder, MatchUtils.iPv4PrefixFromIPv4Address(member.getIP()));
- MatchUtils.createSetSrcTcpMatch(matchBuilder, new PortNumber(member.getPort()));
- flowBuilder.setMatch(matchBuilder.build());
-
- if (write) {
- // Create the OF Actions and Instructions
- InstructionsBuilder isb = new InstructionsBuilder();
-
- // Instructions List Stores Individual Instructions
- List<Instruction> instructions = new ArrayList<>();
-
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab = new ActionBuilder();
- Ipv4Builder ipb = new Ipv4Builder().setIpv4Address(MatchUtils.iPv4PrefixFromIPv4Address(vip));
- ab.setAction(ActionUtils.setNwSrcAction(ipb.build()));
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
- actionList.add(ab.build());
-
- /* If a dummy MAC is assigned to the VIP, we use that as the
- * source MAC for the reverse traffic.
- */
- if (vmac != null) {
- ab = new ActionBuilder();
- ab.setAction(ActionUtils.setDlDstAction(new MacAddress(vmac)));
- ab.setOrder(1);
- ab.setKey(new ActionKey(1));
- actionList.add(ab.build());
- }
-
- // Create an Apply Action
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
-
- // Call the InstructionBuilder Methods Containing Actions
- InstructionBuilder ib = new InstructionBuilder();
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
- ib.setOrder(0);
- ib.setKey(new InstructionKey(0));
- instructions.add(ib.build());
-
- // Call the InstructionBuilder Methods Containing Actions
- ib = this.getMutablePipelineInstructionBuilder();
- ib.setOrder(1);
- ib.setKey(new InstructionKey(1));
- instructions.add(ib.build());
-
- // Add InstructionBuilder to the Instruction(s)Builder List
- isb.setInstruction(instructions);
-
- // Add InstructionsBuilder to FlowBuilder
- flowBuilder.setInstructions(isb.build());
-
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
- }
-
- @Override
- public void setDependencies(BundleContext bundleContext, ServiceReference serviceReference) {
- super.setDependencies(bundleContext.getServiceReference(LoadBalancerProvider.class.getName()), this);
- southbound =(Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this);
- }
-
- @Override
- public void setDependencies(Object impl) {
-
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services;
-
-import java.math.BigInteger;
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.ArrayList;
-import java.util.List;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.OutboundNatProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.Status;
-import org.opendaylight.netvirt.openstack.netvirt.api.StatusCode;
-import org.opendaylight.netvirt.openstack.netvirt.providers.ConfigInterface;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.AbstractServiceInstance;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.netvirt.utils.mdsal.openflow.ActionUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.FlowUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.InstructionUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.MatchUtils;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Prefix;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
-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.FlowBuilder;
-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.ApplyActionsCaseBuilder;
-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;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class OutboundNatService extends AbstractServiceInstance implements OutboundNatProvider, ConfigInterface {
- private static final Logger LOG = LoggerFactory.getLogger(OutboundNatService.class);
-
- public OutboundNatService() {
- super(Service.OUTBOUND_NAT);
- }
-
- public OutboundNatService(Service service) {
- super(service);
- }
-
- @Override
- public Status programIpRewriteRule(Long dpidLong,
- String matchSegmentationId,
- String matchDestMacAddress,
- InetAddress matchSrcAddress,
- String rewriteSrcMacAddress,
- String rewriteDestMacAddress,
- InetAddress rewriteSrcAddress,
- Long OutPort,
- Action action) {
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = "OutboundNAT_" + matchSegmentationId + "_" + matchSrcAddress.getHostAddress();
- FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable()).setPriority(512);
-
- MatchBuilder matchBuilder = new MatchBuilder();
- MatchUtils.createDmacIpSaMatch(matchBuilder,
- matchDestMacAddress,
- MatchUtils.iPv4PrefixFromIPv4Address(matchSrcAddress.getHostAddress()),
- matchSegmentationId);
- flowBuilder.setMatch(matchBuilder.build());
-
- if (action.equals(Action.ADD)) {
- // Instructions List Stores Individual Instructions
- InstructionsBuilder isb = new InstructionsBuilder();
- List<Instruction> instructions = new ArrayList<>();
- List<Instruction> instructions_tmp = new ArrayList<>();
- InstructionBuilder ib = new InstructionBuilder();
-
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- ActionBuilder ab = new ActionBuilder();
- List<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action> actionList =
- new ArrayList<>();
-
- // Set source Mac address
- ab.setAction(ActionUtils.setDlSrcAction(new MacAddress(rewriteSrcMacAddress)));
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
- actionList.add(ab.build());
-
- // DecTTL
- ab.setAction(ActionUtils.decNwTtlAction());
- ab.setOrder(1);
- ab.setKey(new ActionKey(1));
- actionList.add(ab.build());
-
- // Set Destination Mac address
- ab.setAction(ActionUtils.setDlDstAction(new MacAddress(rewriteDestMacAddress)));
- ab.setOrder(2);
- ab.setKey(new ActionKey(2));
- actionList.add(ab.build());
-
- // Set source Ip address
- Ipv4Builder ipb = new Ipv4Builder().setIpv4Address(
- MatchUtils.iPv4PrefixFromIPv4Address(rewriteSrcAddress.getHostAddress()));
- ab.setAction(ActionUtils.setNwSrcAction(ipb.build()));
- ab.setOrder(3);
- ab.setKey(new ActionKey(3));
- actionList.add(ab.build());
-
- // Create Apply Actions Instruction
- aab.setAction(actionList);
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
- ib.setOrder(0);
- ib.setKey(new InstructionKey(0));
- instructions_tmp.add(ib.build());
-
- // Set the Output Port/Iface
- ib = new InstructionBuilder();
- InstructionUtils.addOutputPortInstructions(ib, dpidLong, OutPort, instructions_tmp);
- ib.setOrder(0);
- ib.setKey(new InstructionKey(0));
- instructions.add(ib.build());
-
- flowBuilder.setInstructions(isb.setInstruction(instructions).build());
-
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
-
- // ToDo: WriteFlow/RemoveFlow should return something we can use to check success
- return new Status(StatusCode.SUCCESS);
- }
-
- @Override
- public Status programIpRewriteExclusion(Long dpid, String segmentationId, String excludedCidr,
- Action action) {
- String ipAddress = excludedCidr.substring(0, excludedCidr.indexOf("/"));
- InetAddress inetAddress;
- try {
- inetAddress = InetAddress.getByName(ipAddress);
- } catch (UnknownHostException e) {
- return new Status(StatusCode.BADREQUEST);
- }
- if (inetAddress instanceof Inet6Address) {
- // WORKAROUND: For now ipv6 is not supported
- // TODO: implement ipv6 cidr case
- LOG.debug("ipv6 cidr is not implemented yet. cidr {}",
- excludedCidr);
- return new Status(StatusCode.NOTIMPLEMENTED);
- }
-
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpid);
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = "OutboundNATExclusion_" + segmentationId + "_" + excludedCidr;
- FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable()).setPriority(1024);
-
- MatchBuilder matchBuilder = new MatchBuilder();
- MatchUtils.createTunnelIDMatch(matchBuilder, new BigInteger(segmentationId));
-
- MatchUtils.createDstL3IPv4Match(matchBuilder, new Ipv4Prefix(excludedCidr));
- flowBuilder.setMatch(matchBuilder.build());
-
- if (action.equals(Action.ADD)) {
- // Instructions List Stores Individual Instructions
- InstructionsBuilder isb = new InstructionsBuilder();
- List<Instruction> instructions = new ArrayList<>();
- InstructionBuilder ib;
-
- // Goto Next Table
- ib = getMutablePipelineInstructionBuilder();
- ib.setOrder(0);
- ib.setKey(new InstructionKey(0));
- instructions.add(ib.build());
-
- flowBuilder.setInstructions(isb.setInstruction(instructions).build());
-
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
-
- // ToDo: WriteFlow/RemoveFlow should return something we can use to check success
- return new Status(StatusCode.SUCCESS);
- }
-
- @Override
- public void setDependencies(BundleContext bundleContext, ServiceReference serviceReference) {
- super.setDependencies(bundleContext.getServiceReference(OutboundNatProvider.class.getName()), this);
- }
-
- @Override
- public void setDependencies(Object impl) {
-
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 NEC Corporation 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.netvirt.openstack.netvirt.providers.openflow13.services;
-
-import java.math.BigInteger;
-import java.net.InetAddress;
-import java.net.Inet6Address;
-import java.net.UnknownHostException;
-import java.util.List;
-import java.util.ArrayList;
-
-import org.opendaylight.netvirt.openstack.netvirt.api.StatusCode;
-import org.opendaylight.netvirt.openstack.netvirt.api.InboundNatProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.Status;
-import org.opendaylight.netvirt.openstack.netvirt.api.ResubmitAclLearnProvider;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.AbstractServiceInstance;
-import org.opendaylight.netvirt.openstack.netvirt.providers.ConfigInterface;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.netvirt.utils.mdsal.openflow.ActionUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.FlowUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.InstructionUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.MatchUtils;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Prefix;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.ActionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg3;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.dst.choice.grouping.dst.choice.DstNxRegCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.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.list.Instruction;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.ActionKey;
-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.openflowplugin.extension.nicira.action.rev140714.add.group.input.buckets.bucket.action.action.NxActionResubmitRpcAddGroupCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.resubmit.grouping.NxResubmitBuilder;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ResubmitAclLearnService extends AbstractServiceInstance implements ConfigInterface, ResubmitAclLearnProvider {
- private static final Logger LOG = LoggerFactory.getLogger(ResubmitAclLearnService.class);
- public static final Class<? extends NxmNxReg> REG_FIELD = NxmNxReg3.class;
-
- public ResubmitAclLearnService() {
- super(Service.RESUBMIT_ACL_SERVICE);
- }
-
- public ResubmitAclLearnService(Service service) {
- super(service);
- }
-
- @Override
- public Status programResubmit(Long dpid) {
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpid);
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = "ReSubmit_";
- FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable()).setPriority(0);
- List<Action> listAction = new ArrayList<>();
-
- NxResubmitBuilder nxarsb = new NxResubmitBuilder();
- //nxarsb.setTable(Short.parseShort("39"));
- nxarsb.setTable(getTable(Service.ACL_LEARN_SERVICE));
- ActionBuilder actionBuilder = new ActionBuilder();
- actionBuilder.setAction(new NxActionResubmitRpcAddGroupCaseBuilder().setNxResubmit(nxarsb.build()).build());
- actionBuilder.setKey(new ActionKey(0));
- listAction.add(actionBuilder.build());
-
- nxarsb = new NxResubmitBuilder();
- //nxarsb.setTable(Short.parseShort("40"));
- nxarsb.setTable(getTable(Service.EGRESS_ACL));
- actionBuilder = new ActionBuilder();
- actionBuilder.setAction(new NxActionResubmitRpcAddGroupCaseBuilder().setNxResubmit(nxarsb.build()).build());
- actionBuilder.setKey(new ActionKey(1));
- listAction.add(actionBuilder.build());
-
- ApplyActions applyActions = new ApplyActionsBuilder().setAction(listAction).build();
- ApplyActionsCase applyActionsCase = new ApplyActionsCaseBuilder().setApplyActions(applyActions).build();
- InstructionsBuilder instructionsBuilder = new InstructionsBuilder();
- InstructionBuilder instructionBuilder = new InstructionBuilder();
- List<Instruction> instructions = new ArrayList<>();
- instructionBuilder.setInstruction(applyActionsCase);
- instructionBuilder.setOrder(0);
- instructionBuilder.setKey(new InstructionKey(0));
- instructions.add(instructionBuilder.build());
- instructionsBuilder.setInstruction(instructions);
- // Add InstructionsBuilder to FlowBuilder
- flowBuilder.setInstructions(instructionsBuilder.build());
-
- writeFlow(flowBuilder, nodeBuilder);
-
- // ToDo: WriteFlow/RemoveFlow should return something we can use to check success
- return new Status(StatusCode.SUCCESS);
- }
-
- @Override
- protected void programDefaultPipelineRule(Node node) {
- // no default flow for Resubmit ACL Learn Service
- }
-
- @Override
- public void setDependencies(BundleContext bundleContext, ServiceReference serviceReference) {
- super.setDependencies(bundleContext.getServiceReference(ResubmitAclLearnProvider.class.getName()), this);
- }
-
- @Override
- public void setDependencies(Object impl) {}
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services;
-
-import java.math.BigInteger;
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.util.ArrayList;
-import java.util.List;
-import org.apache.commons.net.util.SubnetUtils;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-import org.opendaylight.netvirt.openstack.netvirt.api.RoutingProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.Status;
-import org.opendaylight.netvirt.openstack.netvirt.api.StatusCode;
-import org.opendaylight.netvirt.openstack.netvirt.providers.ConfigInterface;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.AbstractServiceInstance;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.netvirt.utils.mdsal.openflow.ActionUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.FlowUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.MatchUtils;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Prefix;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
-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.flow.inventory.rev130819.tables.table.FlowBuilder;
-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.ApplyActionsCaseBuilder;
-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;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.dst.choice.grouping.dst.choice.DstNxRegCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.src.choice.grouping.src.choice.SrcOfEthSrcCaseBuilder;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class RoutingService extends AbstractServiceInstance implements RoutingProvider, ConfigInterface {
- private static final Logger LOG = LoggerFactory.getLogger(RoutingService.class);
- public RoutingService() {
- super(Service.ROUTING);
- }
-
- public RoutingService(Service service) {
- super(service);
- }
-
- @Override
- public Status programRouterInterface(Long dpid, String sourceSegId, String destSegId, String macAddress,
- InetAddress address, int mask, Action action) {
- if (address instanceof Inet6Address) {
- // WORKAROUND: For now ipv6 is not supported
- // TODO: implement ipv6 case
- LOG.debug("ipv6 address is not implemented yet. address {}", address);
- return new Status(StatusCode.NOTIMPLEMENTED);
- }
-
- SubnetUtils addressSubnetInfo = new SubnetUtils(address.getHostAddress() + "/" + mask);
- final String prefixString = addressSubnetInfo.getInfo().getNetworkAddress() + "/" + mask;
-
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpid);
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = "Routing_" + sourceSegId + "_" + destSegId + "_" + prefixString;
- FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable()).setPriority(2048);
-
- boolean isExternalNet = sourceSegId.equals(Constants.EXTERNAL_NETWORK);
- MatchBuilder matchBuilder = new MatchBuilder();
- if (isExternalNet) {
- // If matching on external network, use register reserved for InboundNatService to ensure that
- // ip rewrite is meant to be consumed by this destination tunnel id.
- MatchUtils.addNxRegMatch(matchBuilder,
- new MatchUtils.RegMatch(InboundNatService.REG_FIELD, Long.valueOf(destSegId)));
- } else {
- MatchUtils.createTunnelIDMatch(matchBuilder, new BigInteger(sourceSegId));
- }
-
- MatchUtils.createDstL3IPv4Match(matchBuilder, new Ipv4Prefix(prefixString));
- flowBuilder.setMatch(matchBuilder.build());
-
- if (action.equals(Action.ADD)) {
- // Instructions List Stores Individual Instructions
- InstructionsBuilder isb = new InstructionsBuilder();
- List<Instruction> instructions = new ArrayList<>();
- InstructionBuilder ib = new InstructionBuilder();
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- ActionBuilder ab = new ActionBuilder();
- List<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action> actionList
- = new ArrayList<>();
-
- //if this is an east<->west route, save the src mac in case this is an ICMP echo request
- if(!isExternalNet) {
- ab.setAction(ActionUtils.nxMoveRegAction(
- new SrcOfEthSrcCaseBuilder().setOfEthSrc(Boolean.TRUE).build(),
- new DstNxRegCaseBuilder().setNxReg(IcmpEchoResponderService.SRC_MAC_4_HIGH_BYTES_FIELD).build(),
- 0,0,31, false));
- ab.setOrder(actionList.size());
- ab.setKey(new ActionKey(actionList.size()));
- actionList.add(ab.build());
-
- ab.setAction(ActionUtils.nxMoveRegAction(
- new SrcOfEthSrcCaseBuilder().setOfEthSrc(Boolean.TRUE).build(),
- new DstNxRegCaseBuilder().setNxReg(IcmpEchoResponderService.SRC_MAC_2_LOW_BYTES_FIELD).build(),
- 32,0,15, false));
- ab.setOrder(actionList.size());
- ab.setKey(new ActionKey(actionList.size()));
- actionList.add(ab.build());
- }
-
- // Set source Mac address
- ab.setAction(ActionUtils.setDlSrcAction(new MacAddress(macAddress)));
- ab.setOrder(actionList.size());
- ab.setKey(new ActionKey(actionList.size()));
- actionList.add(ab.build());
-
- // DecTTL
- ab.setAction(ActionUtils.decNwTtlAction());
- ab.setOrder(actionList.size());
- ab.setKey(new ActionKey(actionList.size()));
- actionList.add(ab.build());
-
- // Set Destination Tunnel ID
- ab.setAction(ActionUtils.setTunnelIdAction(new BigInteger(destSegId)));
- ab.setOrder(actionList.size());
- ab.setKey(new ActionKey(actionList.size()));
- actionList.add(ab.build());
-
- // Create Apply Actions Instruction
- aab.setAction(actionList);
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
- ib.setOrder(0);
- ib.setKey(new InstructionKey(0));
- instructions.add(ib.build());
-
- // Goto Next Table
- ib = getMutablePipelineInstructionBuilder();
- ib.setOrder(2);
- ib.setKey(new InstructionKey(2));
- instructions.add(ib.build());
-
- flowBuilder.setInstructions(isb.setInstruction(instructions).build());
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
-
- // ToDo: WriteFlow/RemoveFlow should return something we can use to check success
- return new Status(StatusCode.SUCCESS);
- }
-
- @Override
- public Status programDefaultRouteEntry(Long dpid, String segmentationId, String macAddress,
- InetAddress nextHop, Action action) {
-
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpid);
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = "DefaultRoute_" + nextHop.getHostAddress();
- FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable()).setPriority(1024);
-
- MatchBuilder matchBuilder = new MatchBuilder();
- MatchUtils.createTunnelIDMatch(matchBuilder, new BigInteger(segmentationId));
- flowBuilder.setMatch(matchBuilder.build());
-
- if (action.equals(Action.ADD)) {
- // Instructions List Stores Individual Instructions
- InstructionsBuilder isb = new InstructionsBuilder();
- List<Instruction> instructions = new ArrayList<>();
- InstructionBuilder ib = new InstructionBuilder();
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- ActionBuilder ab = new ActionBuilder();
- List<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action> actionList =
- new ArrayList<>();
-
- // Set source Mac address
- ab.setAction(ActionUtils.setDlSrcAction(new MacAddress(macAddress)));
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
- actionList.add(ab.build());
-
- // DecTTL
- ab.setAction(ActionUtils.decNwTtlAction());
- ab.setOrder(1);
- ab.setKey(new ActionKey(1));
- actionList.add(ab.build());
-
- // Create Apply Actions Instruction
- aab.setAction(actionList);
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
- ib.setOrder(0);
- ib.setKey(new InstructionKey(0));
- instructions.add(ib.build());
-
- // Goto Next Table
- ib = getMutablePipelineInstructionBuilder();
- ib.setOrder(1);
- ib.setKey(new InstructionKey(1));
- instructions.add(ib.build());
-
- flowBuilder.setInstructions(isb.setInstruction(instructions).build());
-
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
-
- // ToDo: WriteFlow/RemoveFlow should return something we can use to check success
- return new Status(StatusCode.SUCCESS);
- }
-
- @Override
- public void setDependencies(BundleContext bundleContext, ServiceReference serviceReference) {
- super.setDependencies(bundleContext.getServiceReference(RoutingProvider.class.getName()), this);
- }
-
- @Override
- public void setDependencies(Object impl) {
-
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 NEC Corporation 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.netvirt.openstack.netvirt.providers.openflow13.services;
-
-import java.util.ArrayList;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.opendaylight.netvirt.openstack.netvirt.api.ConfigurationService;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.openstack.netvirt.api.TenantNetworkManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.VlanResponderProvider;
-import org.opendaylight.netvirt.openstack.netvirt.providers.ConfigInterface;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.AbstractServiceInstance;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronNetworkCRUD;
-import org.opendaylight.netvirt.utils.mdsal.openflow.FlowUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.InstructionUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.MatchUtils;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.OutputActionCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.OutputActionCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.output.action._case.OutputActionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
-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.flow.inventory.rev130819.FlowId;
-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.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.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;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionKey;
-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.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.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class VlanResponderService extends AbstractServiceInstance implements VlanResponderProvider, ConfigInterface {
- private static final Logger LOG = LoggerFactory.getLogger(VlanResponderService.class);
- private static final int PRIORITY_2 = 2;
- private static final int PRIORITY_4 = 4;
- private static final int PRIORITY_5 = 5;
-
- private volatile ConfigurationService configurationService;
- private volatile NodeCacheManager nodeCacheManager;
- private volatile TenantNetworkManager tenantNetworkManager;
- private volatile Southbound southbound;
- private volatile INeutronNetworkCRUD neutronNetworkCache;
- private volatile Map<String, ArrayList<ImmutablePair<String, Long>>> segmentationOfPortMap =
- new ConcurrentHashMap<String, ArrayList<ImmutablePair<String, Long>>>();
-
- public VlanResponderService() {
- super(Service.OUTBOUND_NAT);
- }
-
- public VlanResponderService(Service service) {
- super(service);
- }
-
- /**
- * Creates provider network flows for internal bridge.
- *
- * @param dpIdInt dp Id
- * @param segmentationId segmentation id
- * @param patchIntPort patch port of internal bridge
- * @param ofPort of port value
- * @param macAddress mac address
- * @param vlanProviderCache Initial VLAN cache with processing cache
- * @param write - flag to indicate the operation
- */
- @Override
- public void programProviderNetworkRulesInternal(Long dpIdInt, String segmentationId, Long ofPort, Long patchIntPort,
- String macAddress, Map<String, Set<String>> vlanProviderCache, boolean write) {
-
- programProviderBroadAndMultiCastOfRouter(dpIdInt, segmentationId, ofPort, patchIntPort, macAddress, write);
- programProviderUnicastFlowOfRouters(dpIdInt, segmentationId, ofPort, patchIntPort, macAddress, write);
- programProviderUnicastFlowOfExternal(dpIdInt, segmentationId, ofPort, patchIntPort, macAddress, write);
- programProviderBroadAndMultiCastOfExternal(dpIdInt, segmentationId, ofPort, patchIntPort, macAddress, write);
- programProviderUnicastFlowFromExternal(dpIdInt, segmentationId, ofPort, patchIntPort, macAddress, vlanProviderCache, write);
- }
-
- /**
- * Creates provider network flows for external bridge.
- *
- * @param dpIdExt dp id
- * @param segmentationId segmentation id
- * @param patchExtPort patch port of external bridge
- * @param macAddress mac address
- * @param vlanProviderCache Initial VLAN cache with processing cache
- * @param write - flag indicate the operation
- */
- @Override
- public void programProviderNetworkRulesExternal(Long dpIdExt, String segmentationId, Long patchExtPort,
- String macAddress, Map<String, Set<String>> vlanProviderCache, boolean write) {
-
- programProviderNetworkForExternal(dpIdExt, segmentationId, patchExtPort, macAddress, vlanProviderCache, write);
- programProviderNetworkDrop(dpIdExt, patchExtPort, vlanProviderCache, write);
- }
-
-
- /**
- * Write or remove the flows for forward the BC/MC packets of router to patch port and
- * the router ports connected to same external network.
- * Sample flow: table=100, priority=5,in_port=2,dl_src=fa:16:3e:ff:9c:57,dl_dst=01:00:00:00:00:00/01:00:00:00:00:00
- * actions=output:3,push_vlan:0x8100,set_field:4196->vlan_vid,output:1
- */
- private void programProviderBroadAndMultiCastOfRouter(Long dpidLong, String segmentationId, Long ofPort, Long patchPort,
- String macAddress, boolean write) {
- try {
- String nodeName = OPENFLOW + dpidLong;
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(nodeName);
- FlowBuilder flowBuilder = new FlowBuilder();
- // Create the OF Match using MatchBuilder
- MatchBuilder matchBuilder = new MatchBuilder();
- //Match In Port
- MatchUtils.createInPortMatch(matchBuilder, dpidLong, ofPort);
- matchBuilder = MatchUtils.createEthSrcDestMatch(matchBuilder, new MacAddress(macAddress),
- new MacAddress("01:00:00:00:00:00"), new MacAddress("01:00:00:00:00:00"));
- flowBuilder.setMatch(matchBuilder.build());
- // Add Flow Attributes
- String flowName = "ProviderNetwork_BC_Router_" + dpidLong + "_" + ofPort;
- final FlowId flowId = new FlowId(flowName);
- flowBuilder.setId(flowId).setBarrier(true).setTableId(getTable()).setKey(new FlowKey(flowId))
- .setPriority(PRIORITY_5).setFlowName(flowName).setHardTimeout(0).setIdleTimeout(0);
- ArrayList<ImmutablePair<String, Long>> macAddrOfPortPairList = segmentationOfPortMap.get(segmentationId);
- if (macAddrOfPortPairList == null) {
- macAddrOfPortPairList = new ArrayList<ImmutablePair<String, Long>>();
- segmentationOfPortMap.put(segmentationId, macAddrOfPortPairList);
- }
- if (write) {
- ImmutablePair<String, Long> ofPortMacAddressPair = new ImmutablePair<>(macAddress, ofPort);
- if (macAddrOfPortPairList.contains(ofPortMacAddressPair)) {
- return;
- }
- List<Instruction> outputInstructions = new ArrayList<Instruction>();
- int instructionIndex = 0;
- for (ImmutablePair<String, Long> macAddressOfPortPair : macAddrOfPortPairList) {
- InstructionUtils.createOutputPortInstruction(instructionIndex, dpidLong, macAddressOfPortPair.getRight(),
- outputInstructions);
- instructionIndex++;
- }
- // Set the Output Port/Iface
- Instruction outputPortInstruction = InstructionUtils.createVlanOutputPortInstructions(new InstructionBuilder(),
- dpidLong, patchPort, outputInstructions, new VlanId(Integer.valueOf(segmentationId)))
- .setOrder(0).setKey(new InstructionKey(0)).build();
- // Add InstructionsBuilder to FlowBuilder
- InstructionUtils.setFlowBuilderInstruction(flowBuilder, outputPortInstruction);
- writeFlow(flowBuilder, nodeBuilder);
- macAddrOfPortPairList.add(ofPortMacAddressPair);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- Iterator<ImmutablePair<String, Long>> iterator = macAddrOfPortPairList.iterator();
- while (iterator.hasNext()) {
- ImmutablePair<String, Long> macAddressOfPortPair = iterator.next();
- if (macAddress.equals(macAddressOfPortPair.getLeft())) {
- iterator.remove();
- break;
- }
- }
- }
- programExistingProviderBroadAndMultiCastOfRouter(dpidLong, segmentationId, ofPort, patchPort, macAddress, write);
- } catch (Exception e) {
- LOG.error("Error while writing/removing broadcast flows. dpidLong = {}, patchPort={}, write = {}."
- + " Caused due to, {}", dpidLong, patchPort, write, e.getMessage());
- }
- }
-
- /**
- * Write or remove the existing flows of forward the BC/MC packets of router to patch port and
- * the router ports connected to same external network.
- * Sample flow: table=100, priority=5,in_port=2,dl_src=fa:16:3e:ff:9c:57,dl_dst=01:00:00:00:00:00/01:00:00:00:00:00
- * actions=output:3,push_vlan:0x8100,set_field:4196->vlan_vid,output:1
- */
- private void programExistingProviderBroadAndMultiCastOfRouter(Long dpidLong, String segmentationId, Long currentOfPort, Long patchPort,
- String macAddress, boolean write) {
-
- String nodeName = OPENFLOW + dpidLong;
- NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
- FlowBuilder flowBuilder = new FlowBuilder();
-
- MatchBuilder matchBuilder = new MatchBuilder();
- ArrayList<ImmutablePair<String, Long>> macAddrOfPortPairList = segmentationOfPortMap.get(segmentationId);
- for (ImmutablePair<String, Long> macAddrOfPortPair : macAddrOfPortPairList) {
- Long ofPort = macAddrOfPortPair.getRight();
- if (ofPort.equals(currentOfPort)) {
- continue;
- }
- //Match In Port
- MatchUtils.createInPortMatch(matchBuilder, dpidLong, ofPort);
- matchBuilder = MatchUtils.createEthSrcDestMatch(matchBuilder, new MacAddress(macAddrOfPortPair.getLeft()),
- new MacAddress("01:00:00:00:00:00"), new MacAddress("01:00:00:00:00:00"));
- flowBuilder.setMatch(matchBuilder.build());
- // Add Flow Attributes
- String flowName = "ProviderNetwork_BC_Router_" + dpidLong + "_" + ofPort;
- final FlowId flowId = new FlowId(flowName);
- flowBuilder.setId(flowId).setBarrier(true).setTableId(getTable()).setKey(new FlowKey(flowId))
- .setPriority(PRIORITY_5).setFlowName(flowName).setHardTimeout(0).setIdleTimeout(0);
-
- if (write) {
- List<Instruction> outputInstructions = new ArrayList<Instruction>();
- int instructionIndex = 0;
- for (ImmutablePair<String, Long> macAddressOfPortPair : macAddrOfPortPairList) {
- if (ofPort.equals(macAddressOfPortPair.getRight())) {
- continue;
- }
- InstructionUtils.createOutputPortInstruction(instructionIndex, dpidLong, macAddressOfPortPair.getRight(),
- outputInstructions);
- instructionIndex++;
- }
-
- Instruction outputPortInstruction = InstructionUtils.createVlanOutputPortInstructions(new InstructionBuilder(),
- dpidLong, patchPort, outputInstructions, new VlanId(Integer.valueOf(segmentationId)))
- .setOrder(0).setKey(new InstructionKey(0)).build();
- // Add InstructionsBuilder to FlowBuilder
- InstructionUtils.setFlowBuilderInstruction(flowBuilder, outputPortInstruction);
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- List<Instruction> outputInstructions = new ArrayList<Instruction>();
- int instructionIndex = 0;
- for (ImmutablePair<String, Long> ofPortMacAddrPair : macAddrOfPortPairList) {
- Long cachedOfPort = ofPortMacAddrPair.getRight();
- if (cachedOfPort.equals(ofPort) || cachedOfPort.equals(currentOfPort)) {
- continue;
- }
- InstructionUtils.createOutputPortInstruction(instructionIndex, dpidLong, cachedOfPort, outputInstructions);
- instructionIndex++;
- }
- Instruction outputPortInstruction = InstructionUtils.createVlanOutputPortInstructions(new InstructionBuilder(),
- dpidLong, patchPort, outputInstructions, new VlanId(Integer.valueOf(segmentationId)))
- .setOrder(0).setKey(new InstructionKey(0)).build();
- // Add InstructionsBuilder to FlowBuilder
- InstructionUtils.setFlowBuilderInstruction(flowBuilder, outputPortInstruction);
- writeFlow(flowBuilder, nodeBuilder);
- }
- }
- }
-
- /**
- * Write or remove the flows for forward the packets from one router to another routers (Unicast flow)
- * Sample flow: table=100, priority=4,in_port=2,dl_dst=fa:16:3e:4b:cc:0a actions=output:8
- */
- private void programProviderUnicastFlowOfRouters(Long dpidLong, String segmentationId, Long ofPort, Long patchPort,
- String macAddress, boolean write) {
- try {
- String nodeName = OPENFLOW + dpidLong;
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(nodeName);
- FlowBuilder flowBuilder = new FlowBuilder();
- ArrayList<ImmutablePair<String, Long>> macAddrOfPortPairList = segmentationOfPortMap.get(segmentationId);
- if (write) {
- for (ImmutablePair<String, Long> macAddressOfPortPair : macAddrOfPortPairList) {
- for (ImmutablePair<String, Long> subMacAddressOfPortPair : macAddrOfPortPairList) {
- if (macAddressOfPortPair.getLeft().equals(subMacAddressOfPortPair.getLeft())
- || ((!macAddressOfPortPair.getLeft().equals(macAddress) &&
- !subMacAddressOfPortPair.getLeft().equals(macAddress)))) {
- continue;
- }
- // Create the OF Match using MatchBuilder
- MatchBuilder currentMatchBuilder = new MatchBuilder();
- //Match In Port
- MatchUtils.createInPortMatch(currentMatchBuilder, dpidLong, macAddressOfPortPair.getRight());
- currentMatchBuilder = MatchUtils.createDestEthMatch(currentMatchBuilder,
- new MacAddress(subMacAddressOfPortPair.getLeft()), null);
- flowBuilder.setMatch(currentMatchBuilder.build());
- // Add Flow Attributes
- String currentFlowName = "ProviderNetwork_unicast_router_" + dpidLong + "_" +
- macAddressOfPortPair.getLeft() + "_" + subMacAddressOfPortPair.getLeft();
-
- final FlowId flowId = new FlowId(currentFlowName);
- flowBuilder.setId(flowId).setBarrier(true).setTableId(getTable()).setKey(new FlowKey(flowId))
- .setPriority(PRIORITY_4).setFlowName(currentFlowName).setHardTimeout(0).setIdleTimeout(0);
-
- Instruction outputPortInstruction = InstructionUtils.createOutputPortInstructions(new InstructionBuilder(),
- dpidLong, subMacAddressOfPortPair.getRight()).setOrder(0).setKey(new InstructionKey(0)).build();
- // Add InstructionsBuilder to FlowBuilder
- InstructionUtils.setFlowBuilderInstruction(flowBuilder, outputPortInstruction);
- writeFlow(flowBuilder, nodeBuilder);
- }
- }
- } else {
- for (ImmutablePair<String, Long> macAddressOfPortPair : macAddrOfPortPairList) {
- if (macAddressOfPortPair.getLeft().equals(macAddress)) {
- continue;
- }
- // Create the OF Match using MatchBuilder
- MatchBuilder matchBuilder = new MatchBuilder();
- //Match In Port
- MatchUtils.createInPortMatch(matchBuilder, dpidLong, ofPort);
- matchBuilder = MatchUtils.createDestEthMatch(matchBuilder, new MacAddress(macAddressOfPortPair.getLeft()), null);
- flowBuilder.setMatch(matchBuilder.build());
- // Add Flow Attributes
- String flowName = "ProviderNetwork_unicast_router_" + dpidLong + "_" + macAddress + "_" + macAddressOfPortPair.getLeft();
- FlowId flowId = new FlowId(flowName);
- flowBuilder.setId(flowId).setBarrier(true).setTableId(getTable()).setKey(new FlowKey(flowId))
- .setPriority(PRIORITY_4).setFlowName(flowName).setHardTimeout(0).setIdleTimeout(0);
-
- removeFlow(flowBuilder, nodeBuilder);
-
- MatchUtils.createInPortMatch(matchBuilder, dpidLong, macAddressOfPortPair.getRight());
- matchBuilder = MatchUtils.createDestEthMatch(matchBuilder, new MacAddress(macAddress), null);
- flowBuilder.setMatch(matchBuilder.build());
- // Add Flow Attributes
- flowName = "ProviderNetwork_unicast_router_" + dpidLong + "_" + macAddressOfPortPair.getLeft() + "_" + macAddress;
- flowId = new FlowId(flowName);
- flowBuilder.setId(flowId).setBarrier(true).setTableId(getTable()).setKey(new FlowKey(flowId))
- .setPriority(PRIORITY_4).setFlowName(flowName).setHardTimeout(0).setIdleTimeout(0);
-
- removeFlow(flowBuilder, nodeBuilder);
- }
- }
- } catch (Exception e) {
- LOG.error("Error while writing/removing unicast flow of routers. dpidLong = {}, patchPort={}, write = {}."
- + " Caused due to, {}", dpidLong, patchPort, write, e.getMessage());
- }
- }
-
- /**
- * Write or remove the flows for forwarding the BC/MC packets to all other router ports connected to same external network.
- * Sample flow: table=100, priority=4,in_port=1,dl_vlan=100,dl_dst=01:00:00:00:00:00/01:00:00:00:00:00 actions=pop_vlan,output:2,output:8
- */
- private void programProviderBroadAndMultiCastOfExternal(Long dpidLong, String segmentationId, Long ofPort, Long patchPort,
- String macAddress, boolean write) {
- try {
- String nodeName = OPENFLOW + dpidLong;
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(nodeName);
- FlowBuilder flowBuilder = new FlowBuilder();
- // Create the OF Match using MatchBuilder
- MatchBuilder matchBuilder = new MatchBuilder();
- // Match Vlan ID
- MatchUtils.createVlanIdMatch(matchBuilder, new VlanId(Integer.valueOf(segmentationId)), true);
- //Match In Port
- MatchUtils.createInPortMatch(matchBuilder, dpidLong, patchPort);
- matchBuilder = MatchUtils.createDestEthMatch(matchBuilder, new MacAddress("01:00:00:00:00:00"),
- new MacAddress("01:00:00:00:00:00"));
- flowBuilder.setMatch(matchBuilder.build());
- // Add Flow Attributes
- String flowName = "ProviderNetwork_BC_External_" + segmentationId + "_" + patchPort;
- final FlowId flowId = new FlowId(flowName);
- flowBuilder.setId(flowId).setBarrier(true).setTableId(getTable()).setKey(new FlowKey(flowId))
- .setPriority(PRIORITY_4).setFlowName(flowName).setHardTimeout(0).setIdleTimeout(0);
- if (write) {
- ArrayList<ImmutablePair<String, Long>> macAddrOfPortPairList = segmentationOfPortMap.get(segmentationId);
- List<Instruction> outputInstructions = new ArrayList<Instruction>();
- int instructionIndex = 1;
- for (ImmutablePair<String, Long> ofPortMacAddrPair : macAddrOfPortPairList) {
- InstructionUtils.createOutputPortInstruction(instructionIndex, dpidLong,
- ofPortMacAddrPair.getRight(), outputInstructions);
- instructionIndex++;
- }
- Instruction outputPortInstruction =
- InstructionUtils.createPopOutputPortInstructions(new InstructionBuilder(), dpidLong, null, outputInstructions)
- .setOrder(0)
- .setKey(new InstructionKey(0))
- .build();
- InstructionUtils.setFlowBuilderInstruction(flowBuilder, outputPortInstruction);
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- ArrayList<ImmutablePair<String, Long>> macAddrOfPortPairList = segmentationOfPortMap.get(segmentationId);
- if (macAddrOfPortPairList == null || macAddrOfPortPairList.isEmpty()) {
- removeFlow(flowBuilder, nodeBuilder);
- } else {
- List<Instruction> outputInstructions = new ArrayList<Instruction>();
- int instructionIndex = 1;
- for (ImmutablePair<String, Long> ofPortMacAddrPair : macAddrOfPortPairList) {
- InstructionUtils.createOutputPortInstruction(instructionIndex, dpidLong, ofPortMacAddrPair.getRight(),
- outputInstructions);
- instructionIndex++;
- }
- Instruction outputPortInstruction = InstructionUtils.createPopOutputPortInstructions(new InstructionBuilder(),
- dpidLong, null, outputInstructions).setOrder(0).setKey(new InstructionKey(0)).build();
- // Add InstructionsBuilder to FlowBuilder
- InstructionUtils.setFlowBuilderInstruction(flowBuilder, outputPortInstruction);
- writeFlow(flowBuilder, nodeBuilder);
- }
- }
- } catch (Exception e) {
- LOG.error("Error while writing/removing BC/MC flow of external interface. dpidLong = {}, patchPort={}, write = {}."
- +" Caused due to, {}", dpidLong, patchPort, write, e.getMessage());
- }
- }
-
-
- /**
- * Write or remove the flows for forwarding unicast packets from router to external Gateway.
- * Sample flow: table=100, priority=2,in_port=2,dl_src=fa:16:3e:ff:9c:57 actions=push_vlan:0x8100,set_field:4196- >vlan_vid,output:1
- */
- private void programProviderUnicastFlowOfExternal(Long dpidLong, String segmentationId, Long ofPort, Long patchPort,
- String macAddress, boolean write) {
- try {
- String nodeName = OPENFLOW + dpidLong;
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(nodeName);
- FlowBuilder flowBuilder = new FlowBuilder();
- // Create the OF Match using MatchBuilder
- MatchBuilder matchBuilder = new MatchBuilder();
- //Match In Port
- MatchUtils.createInPortMatch(matchBuilder, dpidLong, ofPort);
- MatchUtils.createEthSrcMatch(matchBuilder, new MacAddress(macAddress));
- flowBuilder.setMatch(matchBuilder.build());
- // Add Flow Attributes
- String flowName = "ProviderNetwork_unicast_external_" + dpidLong + "_" + ofPort;
- final FlowId flowId = new FlowId(flowName);
- flowBuilder.setId(flowId).setBarrier(true).setTableId(getTable()).setKey(new FlowKey(flowId))
- .setPriority(PRIORITY_2).setFlowName(flowName).setHardTimeout(0).setIdleTimeout(0);
- if (write) {
- // Set the Output Port/Iface
- Instruction outputPortInstruction = InstructionUtils.createPushVlanInstruction(new InstructionBuilder(),
- dpidLong, patchPort, new VlanId(Integer.valueOf(segmentationId)), new ArrayList<>())
- .setOrder(0).setKey(new InstructionKey(0)).build();
- // Add InstructionsBuilder to FlowBuilder
- InstructionUtils.setFlowBuilderInstruction(flowBuilder, outputPortInstruction);
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
- } catch (Exception e) {
- LOG.error("Error while writing/removing unicast flow of external gateway. dpidLong = {}, write = {}."
- +" Caused due to, {}", dpidLong, write, e.getMessage());
- }
- }
-
- /**
- * Write or remove the flows for forwarding unicast packets from external Gateway to router.
- * Sample flow: table=100, priority=4,in_port=1,dl_vlan=100,dl_dst=fa:16:3e:ff:9c:57 actions=pop_vlan,output:2
- */
- private void programProviderUnicastFlowFromExternal(Long dpidLong, String segmentationId,
- Long ofPort, Long patchPort, String macAddress,
- Map<String, Set<String>> vlanProviderCache, boolean write) {
- try {
- String nodeName = OPENFLOW + dpidLong;
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(nodeName);
- FlowBuilder flowBuilder = new FlowBuilder();
- ArrayList<ImmutablePair<String, Long>> macAddrOfPortPairList = segmentationOfPortMap.get(segmentationId);
- // Create the OF Match using MatchBuilder
- MatchBuilder matchBuilder = new MatchBuilder();
- // Match Vlan ID
- MatchUtils.createVlanIdMatch(matchBuilder, new VlanId(Integer.valueOf(segmentationId)), true);
- //Match In Port
- MatchUtils.createInPortMatch(matchBuilder, dpidLong, patchPort);
- matchBuilder = MatchUtils.createDestEthMatch(matchBuilder, new MacAddress(macAddress), null);
- flowBuilder.setMatch(matchBuilder.build());
- // Add Flow Attributes
- String flowName = "ProviderNetwork_unicast_ext_int" + segmentationId + "_" + ofPort;
- final FlowId flowId = new FlowId(flowName);
- flowBuilder.setId(flowId).setBarrier(true).setTableId(getTable()).setKey(new FlowKey(flowId))
- .setPriority(PRIORITY_4).setFlowName(flowName).setHardTimeout(0).setIdleTimeout(0);
- if (write) {
- // Set the Output Port/Iface
- Instruction outputPortInstruction = InstructionUtils.createPopOutputPortInstructions(new InstructionBuilder(),
- dpidLong, ofPort, null).setOrder(0).setKey(new InstructionKey(0)).build();
- // Add InstructionsBuilder to FlowBuilder
- InstructionUtils.setFlowBuilderInstruction(flowBuilder, outputPortInstruction);
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
- } catch (Exception e) {
- LOG.error("Error while writing/removing unicast flow of external gateway to router. dpidLong = {}, patchPort={}, write = {}."
- + "Caused due to, {}", dpidLong, patchPort, write, e.getMessage());
- }
- }
-
- /**
- * Write or remove the flows for external bridge.
- * Sample flow: cookie=0x0, duration=4831.827s, table=0, n_packets=1202, n_bytes=56476, priority=4,in_port=3,
- * dl_src=fa:16:3e:74:a9:2e actions=push_vlan:0x8100,set_field:4196 vlan_vid,NORMAL
- */
- private void programProviderNetworkForExternal(Long dpidLong, String segmentationId,
- Long patchExtPort, String macAddress,
- Map<String, Set<String>> vlanProviderCache, boolean write) {
- try {
- String nodeName = OPENFLOW + dpidLong;
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(nodeName);
- FlowBuilder flowBuilder = new FlowBuilder();
- // Create the OF Match using MatchBuilder
- MatchBuilder matchBuilder = new MatchBuilder();
- //Match Vlan ID
- MatchUtils.createVlanIdMatch(matchBuilder, new VlanId(Integer.valueOf(segmentationId)), true);
- //Match In Port
- MatchUtils.createInPortMatch(matchBuilder, dpidLong, patchExtPort);
- flowBuilder.setMatch(matchBuilder.build());
- // Add Flow Attributes
- String flowName = "ProviderNetwork_pushVLAN_" + dpidLong + "_" + segmentationId;
- final FlowId flowId = new FlowId(flowName);
- flowBuilder.setId(flowId).setBarrier(true).setTableId((short) 0).setKey(new FlowKey(flowId))
- .setPriority(PRIORITY_4).setFlowName(flowName).setHardTimeout(0).setIdleTimeout(0);
- if (write) {
- LOG.debug("In programProviderNetworkPushVlan macAddress:" + macAddress
- + "segmentationId:" + segmentationId);
- Set<String> lstMacAddress = new HashSet<String>();
- if (vlanProviderCache != null && !vlanProviderCache.isEmpty() && vlanProviderCache.containsKey(segmentationId)) {
- lstMacAddress = vlanProviderCache.get(segmentationId);
- } else {
- lstMacAddress = new HashSet<String>();
- vlanProviderCache.put(segmentationId, lstMacAddress);
- }
- lstMacAddress.add(macAddress);
- Instruction normalInstruction = InstructionUtils.createNormalInstructions(
- FlowUtils.getNodeName(dpidLong), new InstructionBuilder()).
- setOrder(0).setKey(new InstructionKey(0)).build();
- // Add InstructionsBuilder to FlowBuilder
- InstructionUtils.setFlowBuilderInstruction(flowBuilder, normalInstruction);
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- Set<String> lstMacAddress = new HashSet<String>();
- if (vlanProviderCache != null && !vlanProviderCache.isEmpty() && vlanProviderCache.containsKey(segmentationId)) {
- lstMacAddress = vlanProviderCache.get(segmentationId);
- lstMacAddress.remove(macAddress);
- }
- if (lstMacAddress == null || lstMacAddress.isEmpty()) {
- vlanProviderCache.remove(segmentationId);
- }
- boolean isSegmentationIdExist = vlanProviderCache.containsKey(segmentationId);
- if (!isSegmentationIdExist) {
- removeFlow(flowBuilder, nodeBuilder);
- }
- //removeFlow(flowBuilder, nodeBuilder);
- }
- } catch (Exception e) {
- LOG.error("Error while writing/removing push vlan instruction flow. dpidLong = {}, patchPort={}, write = {}."
- + "Caused due to, {}", dpidLong, patchExtPort, write, e.getMessage());
- }
- }
-
- /**
- * Write or remove the flows for drop instructions based on flag value actions.
- * Sample flow: table=0, n_packets=0, n_bytes=0, priority=2,in_port=3 actions=drop
- */
- private void programProviderNetworkDrop(Long dpidLong, Long patchExtPort,
- Map<String, Set<String>> vlanProviderCache, boolean write) {
- try {
- String nodeName = OPENFLOW + dpidLong;
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(nodeName);
- FlowBuilder flowBuilder = new FlowBuilder();
- // Create the OF Match using MatchBuilder
- MatchBuilder matchBuilder = new MatchBuilder();
- //Match In Port
- MatchUtils.createInPortMatch(matchBuilder, dpidLong, patchExtPort);
- flowBuilder.setMatch(matchBuilder.build());
- // Add Flow Attributes
- String flowName = "ProviderNetwork_drop_" + dpidLong + "_" + patchExtPort;
- final FlowId flowId = new FlowId(flowName);
- flowBuilder.setId(flowId).setBarrier(true).setTableId((short) 0)
- .setKey(new FlowKey(flowId)).setPriority(PRIORITY_2).setFlowName(flowName)
- .setHardTimeout(0).setIdleTimeout(0);
- if (write) {
- // Call the InstructionBuilder Methods Containing Actions
- Instruction dropInstruction = InstructionUtils.createDropInstructions(new InstructionBuilder())
- .setOrder(0)
- .setKey(new InstructionKey(0))
- .build();
- // Add InstructionsBuilder to FlowBuilder
- InstructionUtils.setFlowBuilderInstruction(flowBuilder, dropInstruction);
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- if (vlanProviderCache.isEmpty()) {
- removeFlow(flowBuilder, nodeBuilder);
- }
- }
- } catch (Exception e) {
- LOG.error("Error while writing/removing drop instruction flow. dpidLong = {}, patchPort={}, write = {}."
- + "Caused due to, {}", dpidLong, patchExtPort, write, e.getMessage());
- }
- }
-
- private void populateSegmentationCache() {
- try {
- Map<String, String> networkUUIDSegIdMap = new ConcurrentHashMap<String, String>();
- for (Node node : nodeCacheManager.getBridgeNodes()) {
- Node srcBridgeNode = southbound.getBridgeNode(node, configurationService.getIntegrationBridgeName());
- if (srcBridgeNode != null) {
- List<OvsdbTerminationPointAugmentation> terminationPointOfBridgeList =
- southbound.getTerminationPointsOfBridge(srcBridgeNode);
- for (OvsdbTerminationPointAugmentation intf : terminationPointOfBridgeList) {
- NeutronPort neutronPort = tenantNetworkManager.getTenantPort(intf);
- if (neutronPort != null && neutronPort.getDeviceOwner().equalsIgnoreCase(Constants.OWNER_ROUTER_GATEWAY)) {
- final String macAddress = neutronPort.getMacAddress();
- final String networkUUID = neutronPort.getNetworkUUID();
- String providerSegmentationId = networkUUIDSegIdMap.get(networkUUID);
- if (providerSegmentationId == null) {
- NeutronNetwork neutronNetwork = neutronNetworkCache.getNetwork(networkUUID);
- providerSegmentationId = neutronNetwork != null ?
- neutronNetwork.getProviderSegmentationID() : null;
- }
- if (providerSegmentationId == null || providerSegmentationId.isEmpty()
- || macAddress == null || macAddress.isEmpty()) {
- continue;
- }
- networkUUIDSegIdMap.put(networkUUID, providerSegmentationId);
- ArrayList<ImmutablePair<String, Long>> macAddrOfPortPairList = segmentationOfPortMap.get(providerSegmentationId);
- if (macAddrOfPortPairList == null)
- {
- macAddrOfPortPairList = new ArrayList<ImmutablePair<String, Long>>();
- segmentationOfPortMap.put(providerSegmentationId, macAddrOfPortPairList);
- }
- ImmutablePair<String, Long> macAddrOfPortPair = new ImmutablePair<String, Long>(macAddress, intf.getOfport());
- macAddrOfPortPairList.add(macAddrOfPortPair);
- }
- }
- }
- }
- }
- catch (Exception e) {
- LOG.error("Error while populating segmentation mac-ofport cache, due to {} ", e.getMessage());
- }
- }
-
- @Override
- public void setDependencies(BundleContext bundleContext, ServiceReference serviceReference) {
- super.setDependencies(bundleContext.getServiceReference(VlanResponderProvider.class.getName()), this);
- configurationService =
- (ConfigurationService) ServiceHelper.getGlobalInstance(ConfigurationService.class, this);
- southbound =
- (Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this);
- nodeCacheManager =
- (NodeCacheManager) ServiceHelper.getGlobalInstance(NodeCacheManager.class, this);
- tenantNetworkManager =
- (TenantNetworkManager) ServiceHelper.getGlobalInstance(TenantNetworkManager.class, this);
- }
-
- @Override
- public void setDependencies(Object impl) {
- if (impl instanceof INeutronNetworkCRUD) {
- neutronNetworkCache = (INeutronNetworkCRUD)impl;
- }
- populateSegmentationCache();
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services.arp;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-import io.netty.buffer.Unpooled;
-
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.Map;
-
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.apache.commons.lang3.tuple.Pair;
-import org.opendaylight.controller.liblldp.EtherTypes;
-import org.opendaylight.controller.liblldp.NetUtils;
-import org.opendaylight.controller.liblldp.Packet;
-import org.opendaylight.controller.liblldp.PacketException;
-
-/**
- * Represents ARP packet. Contains methods ({@link #setSHAFieldCoordinate(Pair)}
- * {@link #setSPAFieldCoordinate(Pair)} {@link #setTHAFieldCoordinate(Pair)}
- * {@link #setTPAFieldCoordinate(Pair)}) for customization of ARP.
- * Arp by default contain fields for IPv4 as protocol address and MAC as hardware address.
- */
-public class Arp extends Packet {
-
- private static final String HTYPE = "htype";
- private static final String PTYPE = "ptype";
- private static final String HLEN = "hlen";
- private static final String PLEN = "plen";
- private static final String OPERATION = "operation";
- private static final String SHA = "sha";
- private static final String SPA = "spa";
- private static final String THA = "tha";
- private static final String TPA = "tpa";
-
- private static final int ARP_FIELDS_COUNT = 9;
- private static final int ETHERNET_HW_TYPE = 1;
- private final Map<String, Pair<Integer, Integer>> ARP_FIELD_COORDINATES = new LinkedHashMap<String, Pair<Integer, Integer>>() {
-
- private static final long serialVersionUID = 1L;
-
- {
- put(HTYPE, ImmutablePair.of(0, 16));
- put(PTYPE, ImmutablePair.of(16, 16));
- put(HLEN, ImmutablePair.of(32, 8));
- put(PLEN, ImmutablePair.of(40, 8));
- put(OPERATION, ImmutablePair.of(48, 16));
- put(SHA, ImmutablePair.of(64, 48));
- put(SPA, ImmutablePair.of(112, 32));
- put(THA, ImmutablePair.of(144, 48));
- put(TPA, ImmutablePair.of(192, 32));
- }
- };
-
- public Arp() {
- payload = null;
- hdrFieldsMap = new HashMap<>(ARP_FIELDS_COUNT);
- setHardwareLength((short) 6); // MAC address length
- setProtocolLength((short) 4); // IPv4 address length
- setHardwareType(ETHERNET_HW_TYPE);
- setProtocolType(EtherTypes.IPv4.intValue());
- hdrFieldCoordMap = ARP_FIELD_COORDINATES;
- }
-
- public Pair<Integer, Integer> setSHAFieldCoordinate(Pair<Integer, Integer> bitOffsetAndBitLength) {
- checkNotNullPair(bitOffsetAndBitLength);
- return ARP_FIELD_COORDINATES.put(SHA, bitOffsetAndBitLength);
- }
-
- public Pair<Integer, Integer> setSPAFieldCoordinate(Pair<Integer, Integer> bitOffsetAndBitLength) {
- checkNotNullPair(bitOffsetAndBitLength);
- return ARP_FIELD_COORDINATES.put(SPA, bitOffsetAndBitLength);
- }
-
- public Pair<Integer, Integer> setTHAFieldCoordinate(Pair<Integer, Integer> bitOffsetAndBitLength) {
- checkNotNullPair(bitOffsetAndBitLength);
- return ARP_FIELD_COORDINATES.put(THA, bitOffsetAndBitLength);
- }
-
- public Pair<Integer, Integer> setTPAFieldCoordinate(Pair<Integer, Integer> bitOffsetAndBitLength) {
- checkNotNullPair(bitOffsetAndBitLength);
- return ARP_FIELD_COORDINATES.put(TPA, bitOffsetAndBitLength);
- }
-
- private void checkNotNullPair(Pair<Integer, Integer> pair) {
- checkNotNull(pair);
- checkNotNull(pair.getLeft());
- checkNotNull(pair.getRight());
- }
-
- @Override
- public Packet deserialize(byte[] data, int bitOffset, int size) throws PacketException {
- return super.deserialize(data, bitOffset, size);
- }
-
- @Override
- public byte[] serialize() throws PacketException {
- return super.serialize();
- }
-
- @Override
- public int getfieldnumBits(String fieldName) {
- if (fieldName.equals(SHA) || fieldName.equals(THA)) {
- return getHardwareLength() * NetUtils.NumBitsInAByte;
- } else if (fieldName.equals(SPA) || fieldName.equals(TPA)) {
- return getProtocolLength() * NetUtils.NumBitsInAByte;
- }
- return hdrFieldCoordMap.get(fieldName).getRight();
- }
-
- public Arp setHardwareType(int value) {
- hdrFieldsMap.put(HTYPE, Unpooled.copyShort(value).array());
- return this;
- }
-
- public Arp setProtocolType(int value) {
- hdrFieldsMap.put(PTYPE, Unpooled.copyShort(value).array());
- return this;
- }
-
- /**
- * @param value hardware length in Bytes
- * @return Arp
- */
- public Arp setHardwareLength(short value) {
- hdrFieldsMap.put(HLEN, Unpooled.buffer(1).writeByte(value).array());
- return this;
- }
-
- /**
- * @param value protocol length in Bytes
- * @return Arp
- */
- public Arp setProtocolLength(short value) {
- hdrFieldsMap.put(PLEN, Unpooled.buffer(1).writeByte(value).array());
- return this;
- }
-
- public Arp setOperation(int value) {
- hdrFieldsMap.put(OPERATION, Unpooled.copyShort(value).array());
- return this;
- }
-
- public Arp setSenderHardwareAddress(byte[] value) {
- hdrFieldsMap.put(SHA, value);
- return this;
- }
-
- public Arp setSenderProtocolAddress(byte[] value) {
- hdrFieldsMap.put(SPA, value);
- return this;
- }
-
- public Arp setTargetHardwareAddress(byte[] value) {
- hdrFieldsMap.put(THA, value);
- return this;
- }
-
- public Arp setTargetProtocolAddress(byte[] value) {
- hdrFieldsMap.put(TPA, value);
- return this;
- }
-
- public int getHardwareType() {
- byte[] htype = hdrFieldsMap.get(HTYPE);
- return Unpooled.wrappedBuffer(htype).readUnsignedShort();
- }
-
- public int getProtocolType() {
- byte[] ptype = hdrFieldsMap.get(PTYPE);
- return Unpooled.wrappedBuffer(ptype).readUnsignedShort();
- }
-
- public short getHardwareLength() {
- byte[] hlen = hdrFieldsMap.get(HLEN);
- return Unpooled.wrappedBuffer(hlen).readUnsignedByte();
- }
-
- public short getProtocolLength() {
- byte[] plen = hdrFieldsMap.get(PLEN);
- return Unpooled.wrappedBuffer(plen).readUnsignedByte();
- }
-
- public int getOperation() {
- byte[] operation = hdrFieldsMap.get(OPERATION);
- return Unpooled.wrappedBuffer(operation).readUnsignedShort();
- }
-
- public byte[] getSenderHardwareAddress() {
- return hdrFieldsMap.get(SHA);
- }
-
- public byte[] getSenderProtocolAddress() {
- return hdrFieldsMap.get(SPA);
- }
-
- public byte[] getTargetHardwareAddress() {
- return hdrFieldsMap.get(THA);
- }
-
- public byte[] getTargetProtocolAddress() {
- return hdrFieldsMap.get(TPA);
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services.arp;
-
-import org.opendaylight.controller.liblldp.EtherTypes;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Prefix;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.OutputActionCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.output.action._case.OutputActionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
-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.flow.types.rev131026.OutputPortValues;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.EtherType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.arp.match.fields.ArpTargetHardwareAddressBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ethernet.match.fields.EthernetDestinationBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ethernet.match.fields.EthernetTypeBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.EthernetMatch;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.EthernetMatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.ArpMatch;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.ArpMatchBuilder;
-
-/**
- * Contains methods creating flow part for ARP flow.
- */
-public class ArpFlowFactory {
-
- private static final String HOST_MASK = "/32";
-
- /**
- * Creates {@link EthernetMatch} containing ARP ether-type and the given destination MAC address
- * @param destinationMacAddress Destination MAC Address
- * @return EthernetMatch ethernetMatch
- */
- public static EthernetMatch createEthernetMatch(MacAddress destinationMacAddress) {
- return new EthernetMatchBuilder().setEthernetType(
- new EthernetTypeBuilder().setType(new EtherType((long) EtherTypes.ARP.intValue())).build())
- .setEthernetDestination(new EthernetDestinationBuilder().setAddress(destinationMacAddress).build())
- .build();
- }
-
- /**
- * Creates {@link ArpMatch} containing Reply ARP operation, THA and TPA for the given target
- * address and SPA for the given sender protocol address
- * @param targetAddress Target Address
- * @param senderProtocolAddress Sender Protocol Address
- * @return ArpMatch arpMatch
- */
- public static ArpMatch createArpMatch(ArpMessageAddress targetAddress, Ipv4Address senderProtocolAddress) {
- return new ArpMatchBuilder().setArpOp(ArpOperation.REPLY.intValue())
- .setArpTargetHardwareAddress(
- new ArpTargetHardwareAddressBuilder().setAddress(targetAddress.getHardwareAddress()).build())
- .setArpTargetTransportAddress(new Ipv4Prefix(targetAddress.getProtocolAddress().getValue() + HOST_MASK))
- .setArpSourceTransportAddress(new Ipv4Prefix(senderProtocolAddress.getValue() + HOST_MASK))
- .build();
- }
-
- /**
- * Creates {@link Action} representing output to the controller
- *
- * @param order the order for the action
- * @return Action action
- */
- public static Action createSendToControllerAction(int order) {
- return new ActionBuilder().setOrder(order)
- .setKey(new ActionKey(order))
- .setAction(
- new OutputActionCaseBuilder().setOutputAction(
- new OutputActionBuilder().setMaxLength(0xffff)
- .setOutputNodeConnector(new Uri(OutputPortValues.CONTROLLER.toString()))
- .build()).build())
- .build();
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services.arp;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import javax.annotation.concurrent.Immutable;
-
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
-
-/**
- * Represents ARP fields where protocol address is IPv4 address and hardware address is MAC address.
- */
-@Immutable
-public class ArpMessageAddress {
-
- private final MacAddress hwAddress;
- private final Ipv4Address protocolAddress;
-
- public ArpMessageAddress(MacAddress hwAddress, Ipv4Address protocolAddress) {
- this.hwAddress = checkNotNull(hwAddress);
- this.protocolAddress = checkNotNull(protocolAddress);
- }
-
- public MacAddress getHardwareAddress() {
- return hwAddress;
- }
-
- public Ipv4Address getProtocolAddress() {
- return protocolAddress;
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services.arp;
-
-import javax.annotation.Nullable;
-
-public enum ArpOperation {
-
- REQUEST(1), REPLY(2);
-
- private final int intOperation;
-
- ArpOperation(int operationNumber) {
- this.intOperation = operationNumber;
- }
-
- public int intValue() {
- return intOperation;
- }
-
- public static @Nullable ArpOperation loadFromInt(int intOperation) {
- for (ArpOperation operation : ArpOperation.values()) {
- if (operation.intOperation == intOperation) {
- return operation;
- }
- }
- return null;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services.arp;
-
-import org.opendaylight.controller.liblldp.NetUtils;
-import org.opendaylight.netvirt.openstack.netvirt.api.GatewayMacResolverListener;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowInput;
-
-/**
-*
-* @author Anil Vishnoi (avishnoi@Brocade.com)
-*
-*/
-
-public final class ArpResolverMetadata {
-
- private final GatewayMacResolverListener gatewayMacResolverListener;
- private final Ipv4Address gatewayIpAddress;
- private Long externalNetworkBridgeDpid;
- private final boolean refreshExternalNetworkBridgeDpidIfNeeded;
- private final Ipv4Address arpRequestSourceIp;
- private final MacAddress arpRequestSourceMacAddress;
- private final boolean periodicRefresh;
- private RemoveFlowInput flowToRemove;
- private MacAddress gatewayMacAddress;
- private boolean gatewayMacAddressResolved;
- private int numberOfOutstandingArpRequests;
- private static final int MAX_OUTSTANDING_ARP_REQUESTS = 2;
-
- public ArpResolverMetadata(final GatewayMacResolverListener gatewayMacResolverListener,
- final Long externalNetworkBridgeDpid,
- final boolean refreshExternalNetworkBridgeDpidIfNeeded,
- final Ipv4Address gatewayIpAddress, final Ipv4Address arpRequestSourceIp,
- final MacAddress arpRequestMacAddress, final boolean periodicRefresh){
- this.gatewayMacResolverListener = gatewayMacResolverListener;
- this.externalNetworkBridgeDpid = externalNetworkBridgeDpid;
- this.refreshExternalNetworkBridgeDpidIfNeeded = refreshExternalNetworkBridgeDpidIfNeeded;
- this.gatewayIpAddress = gatewayIpAddress;
- this.arpRequestSourceIp = arpRequestSourceIp;
- this.arpRequestSourceMacAddress = arpRequestMacAddress;
- this.periodicRefresh = periodicRefresh;
- this.gatewayMacAddress = null;
- this.gatewayMacAddressResolved = false;
- this.numberOfOutstandingArpRequests = 0;
- }
-
- public boolean isRefreshExternalNetworkBridgeDpidIfNeeded() {
- return refreshExternalNetworkBridgeDpidIfNeeded;
- }
- public boolean isPeriodicRefresh() {
- return periodicRefresh;
- }
- public RemoveFlowInput getFlowToRemove() {
- return flowToRemove;
- }
- public void setFlowToRemove(RemoveFlowInput flowToRemove) {
- this.flowToRemove = flowToRemove;
- }
- public Ipv4Address getGatewayIpAddress() {
- return gatewayIpAddress;
- }
- public MacAddress getGatewayMacAddress() {
- return gatewayMacAddress;
- }
- public void setGatewayMacAddress(MacAddress gatewayMacAddress) {
- if (gatewayMacAddress != null) {
- if (gatewayMacResolverListener != null &&
- !gatewayMacAddress.equals(this.gatewayMacAddress)) {
- gatewayMacResolverListener.gatewayMacResolved(externalNetworkBridgeDpid,
- new IpAddress(gatewayIpAddress), gatewayMacAddress);
- }
- gatewayMacAddressResolved = true;
- numberOfOutstandingArpRequests = 0;
- } else {
- gatewayMacAddressResolved = false;
- }
- this.gatewayMacAddress = gatewayMacAddress;
- }
-
- public Long getExternalNetworkBridgeDpid() {
- return externalNetworkBridgeDpid;
- }
- public void setExternalNetworkBridgeDpid(Long externalNetworkBridgeDpid) {
- this.externalNetworkBridgeDpid = externalNetworkBridgeDpid;
- }
- public Ipv4Address getArpRequestSourceIp() {
- return arpRequestSourceIp;
- }
- public MacAddress getArpRequestSourceMacAddress() {
- return arpRequestSourceMacAddress;
- }
- public boolean isGatewayMacAddressResolved() {
- return gatewayMacAddressResolved;
- }
-
- /**
- * This method is used to determine whether to use the broadcast MAC or the unicast MAC as the destination address
- * for an ARP request packet based on whether one of the last MAX_OUTSTANDING_ARP_REQUESTS requests has been
- * answered.
- *
- * A counter (numberOfOutstandingArpRequests) is maintained to track outstanding ARP requests. This counter is
- * incremented in this method and reset when setGatewayMacAddress() is called with an updated MAC address after an
- * ARP reply is received. It is therefore expected that this method be called exactly once for each ARP request
- * event, and not be called for other reasons, or it may result in more broadcast ARP request packets being sent
- * than needed.
- *
- * @return Destination MAC address to be used in ARP request packet: Either the unicast MAC or the broadcast MAC
- * as described above.
- */
- public MacAddress getArpRequestDestMacAddress() {
-
- numberOfOutstandingArpRequests++;
-
- if (numberOfOutstandingArpRequests > MAX_OUTSTANDING_ARP_REQUESTS) {
- gatewayMacAddressResolved = false;
- }
-
- if (gatewayMacAddressResolved) {
- return gatewayMacAddress;
- } else {
- return ArpUtils.bytesToMac(NetUtils.getBroadcastMACAddr());
- }
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
-
- result = prime
- * result
- + ((gatewayMacResolverListener == null) ? 0 : gatewayMacResolverListener.hashCode());
- result = prime
- * result
- + ((arpRequestSourceMacAddress == null) ? 0 : arpRequestSourceMacAddress
- .hashCode());
- result = prime
- * result
- + ((arpRequestSourceIp == null) ? 0 : arpRequestSourceIp
- .hashCode());
- result = prime
- * result
- + ((externalNetworkBridgeDpid == null) ? 0
- : externalNetworkBridgeDpid.hashCode());
- result = prime
- * result
- + ((gatewayIpAddress == null) ? 0 : gatewayIpAddress.hashCode());
- result = prime * result + (periodicRefresh ? 1231 : 1237);
- result = prime * result + (refreshExternalNetworkBridgeDpidIfNeeded ? 1231 : 1237);
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- ArpResolverMetadata other = (ArpResolverMetadata) obj;
- if (gatewayMacResolverListener == null) {
- if (other.gatewayMacResolverListener != null)
- return false;
- } else if (!gatewayMacResolverListener.equals(other.gatewayMacResolverListener))
- return false;
- if (arpRequestSourceMacAddress == null) {
- if (other.arpRequestSourceMacAddress != null)
- return false;
- } else if (!arpRequestSourceMacAddress.equals(other.arpRequestSourceMacAddress))
- return false;
- if (arpRequestSourceIp == null) {
- if (other.arpRequestSourceIp != null)
- return false;
- } else if (!arpRequestSourceIp.equals(other.arpRequestSourceIp))
- return false;
- if (externalNetworkBridgeDpid == null) {
- if (other.externalNetworkBridgeDpid != null)
- return false;
- } else if (!externalNetworkBridgeDpid
- .equals(other.externalNetworkBridgeDpid))
- return false;
- if (gatewayIpAddress == null) {
- if (other.gatewayIpAddress != null)
- return false;
- } else if (!gatewayIpAddress.equals(other.gatewayIpAddress))
- return false;
- if (periodicRefresh != other.periodicRefresh)
- return false;
- if (refreshExternalNetworkBridgeDpidIfNeeded != other.refreshExternalNetworkBridgeDpidIfNeeded)
- return false;
- return true;
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services.arp;
-
-import org.opendaylight.controller.liblldp.EtherTypes;
-import org.opendaylight.controller.liblldp.Ethernet;
-import org.opendaylight.controller.liblldp.NetUtils;
-import org.opendaylight.controller.liblldp.PacketException;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceived;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ArpResolverUtils {
- private static final Logger LOG = LoggerFactory.getLogger(ArpResolverUtils.class);
-
-
- static {
- Ethernet.etherTypeClassMap.put(EtherTypes.ARP.shortValue(), Arp.class);
- }
-
- /**
- * Tries to deserialize received packet as ARP packet with IPv4 protocol address and MAC
- * hardware address.
- *
- * @param potentialArp the packet for deserialization
- * @return ARP packet if received packet is ARP and deserialization was successful
- */
- public static Arp getArpFrom(PacketReceived potentialArp) {
- byte[] payload = potentialArp.getPayload();
- Ethernet ethPkt = new Ethernet();
- try {
- ethPkt.deserialize(payload, 0, payload.length * NetUtils.NumBitsInAByte);
- } catch (PacketException e) {
- LOG.trace("Failed to decode the incoming packet. ignoring it.");
- }
- if (ethPkt.getPayload() instanceof Arp) {
- return (Arp) ethPkt.getPayload();
- }
- return null;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services.arp;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import java.util.concurrent.Future;
-
-import org.opendaylight.controller.liblldp.EtherTypes;
-import org.opendaylight.controller.liblldp.Ethernet;
-import org.opendaylight.controller.liblldp.NetUtils;
-import org.opendaylight.controller.liblldp.PacketException;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketProcessingService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.TransmitPacketInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.TransmitPacketInputBuilder;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.JdkFutureAdapters;
-import com.google.common.util.concurrent.ListenableFuture;
-
-/**
- * Uses packet-out for sending ARP Requests.
- */
-public class ArpSender {
-
- private static final Logger LOG = LoggerFactory.getLogger(ArpSender.class);
-
- private static final String OFPP_ALL = "0xfffffffc";
- private final PacketProcessingService packetProcessingService;
-
- public ArpSender(PacketProcessingService packetProcessingService) {
- this.packetProcessingService = checkNotNull(packetProcessingService);
- }
-
- /**
- * Sends ARP Request as packet-out from all openflow physical ports on the given node.
- *
- * @param senderAddress the addresses used in sender part of ARP packet
- * @param tpa the target protocol address, in this case IPv4 address for which MAC should be
- * discovered
- * @param nodeIid the path to node from where the ARP packet will be flooded
- * @return future result about success of packet-out
- */
- public ListenableFuture<RpcResult<Void>> floodArp(ArpMessageAddress senderAddress, Ipv4Address tpa,
- InstanceIdentifier<Node> nodeIid) {
- checkNotNull(senderAddress);
- checkNotNull(tpa);
- checkNotNull(nodeIid);
- // node connector representing all physical ports on node
- NodeConnectorKey nodeConnectorKey = new NodeConnectorKey(createNodeConnectorId(OFPP_ALL,
- nodeIid.firstKeyOf(Node.class, NodeKey.class).getId()));
- InstanceIdentifier<NodeConnector> egressNc = nodeIid.child(NodeConnector.class, nodeConnectorKey);
- return sendArp(senderAddress, tpa, null, egressNc);
- }
-
- private NodeConnectorId createNodeConnectorId(String connectorId, NodeId nodeId) {
- return new NodeConnectorId(nodeId.getValue() + ":" + connectorId);
- }
-
- /**
- * Sends ARP Request as packet-out from the given port (node connector).
- *
- * @param senderAddress the addresses used in sender part of ARP packet
- * @param tpa the target protocol address, in this case IPv4 address for which MAC should be
- * discovered
- * @param arpRequestDestMacAddress the destination MAC address to be used in the ARP packet or null if not known.
- * @param egressNc the path to node connector from where the ARP packet will be sent @return future result about success of * packet-out
- * @return future result about success of packet-out
- */
- public ListenableFuture<RpcResult<Void>> sendArp(ArpMessageAddress senderAddress, Ipv4Address tpa,
- MacAddress arpRequestDestMacAddress, InstanceIdentifier<NodeConnector> egressNc) {
- checkNotNull(senderAddress);
- checkNotNull(tpa);
- checkNotNull(egressNc);
- final Ethernet arpFrame = createArpFrame(senderAddress, tpa, arpRequestDestMacAddress);
- byte[] arpFrameAsBytes;
- try {
- arpFrameAsBytes = arpFrame.serialize();
- } catch (PacketException e) {
- LOG.warn("Serializition of ARP packet is not successful.", e);
- if (LOG.isDebugEnabled()) {
- LOG.debug("ARP packet: {}", ArpUtils.getArpFrameToStringFormat(arpFrame));
- }
- return Futures.immediateFailedFuture(e);
- }
- // Generate packet with destination switch and port
- TransmitPacketInput packet = new TransmitPacketInputBuilder().setEgress(new NodeConnectorRef(egressNc))
- .setNode(new NodeRef(egressNc.firstIdentifierOf(Node.class)))
- .setPayload(arpFrameAsBytes)
- .build();
- if (LOG.isTraceEnabled()) {
- LOG.trace("Sending ARP REQUEST \n{}", ArpUtils.getArpFrameToStringFormat(arpFrame));
- }
- Future<RpcResult<Void>> futureTransmitPacketResult = packetProcessingService.transmitPacket(packet);
- return JdkFutureAdapters.listenInPoolThread(futureTransmitPacketResult);
- }
-
- private Ethernet createArpFrame(ArpMessageAddress senderAddress, Ipv4Address tpa, MacAddress arpRequestDestMacAddress) {
- byte[] senderMac = ArpUtils.macToBytes(senderAddress.getHardwareAddress());
- byte[] senderIp = ArpUtils.ipToBytes(senderAddress.getProtocolAddress());
- byte[] targetMac;
- if (arpRequestDestMacAddress != null) {
- targetMac = ArpUtils.macToBytes(arpRequestDestMacAddress);
- } else {
- targetMac = NetUtils.getBroadcastMACAddr();
- }
- byte[] targetIp = ArpUtils.ipToBytes(tpa);
- Ethernet arpFrame = new Ethernet().setSourceMACAddress(senderMac)
- .setDestinationMACAddress(targetMac)
- .setEtherType(EtherTypes.ARP.shortValue());
- Arp arp = new Arp().setOperation(ArpOperation.REQUEST.intValue())
- .setSenderHardwareAddress(senderMac)
- .setSenderProtocolAddress(senderIp)
- .setTargetHardwareAddress(targetMac)
- .setTargetProtocolAddress(targetIp);
- arpFrame.setPayload(arp);
- return arpFrame;
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services.arp;
-
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-
-import javax.annotation.Nullable;
-
-import org.opendaylight.controller.liblldp.EtherTypes;
-import org.opendaylight.controller.liblldp.Ethernet;
-import org.opendaylight.controller.liblldp.HexEncode;
-import org.opendaylight.controller.liblldp.Packet;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
-
-import com.google.common.net.InetAddresses;
-
-public class ArpUtils {
-
- private ArpUtils() {
- throw new UnsupportedOperationException("Cannot create an instance.");
- }
-
- /**
- * Returns Ethernet and ARP in readable string format
- * @param eth Ethernet
- * @return ARP Value
- */
- public static String getArpFrameToStringFormat(Ethernet eth) {
- String ethernetString = "Ethernet [getEtherType()="
- + EtherTypes.loadFromString(String.valueOf(eth.getEtherType())) + ", getSourceMACAddress()="
- + HexEncode.bytesToHexStringFormat(eth.getSourceMACAddress()) + ", getDestinationMACAddress()="
- + HexEncode.bytesToHexStringFormat(eth.getDestinationMACAddress()) + "]\n";
- Packet potentialArp = eth.getPayload();
- String arpString = null;
- if (potentialArp instanceof Arp) {
- Arp arp = (Arp) potentialArp;
- arpString = ArpUtils.getArpToStringFormat(arp);
- } else {
- arpString = "ARP was not found in Ethernet frame.";
- }
- return ethernetString.concat(arpString);
- }
-
- /**
- * Returns ARP in readable string format
- * @param arp arp
- * @return ARP Value
- */
- public static String getArpToStringFormat(Arp arp) {
- try {
- return "Arp [getHardwareType()=" + arp.getHardwareType() + ", getProtocolType()=" + arp.getProtocolType()
- + ", getHardwareLength()=" + arp.getHardwareLength() + ", getProtocolLength()="
- + arp.getProtocolLength() + ", getOperation()=" + ArpOperation.loadFromInt(arp.getOperation())
- + ", getSenderHardwareAddress()="
- + HexEncode.bytesToHexStringFormat(arp.getSenderHardwareAddress())
- + ", getSenderProtocolAddress()="
- + InetAddress.getByAddress(arp.getSenderProtocolAddress()).getHostAddress()
- + ", getTargetHardwareAddress()="
- + HexEncode.bytesToHexStringFormat(arp.getTargetHardwareAddress())
- + ", getTargetProtocolAddress()="
- + InetAddress.getByAddress(arp.getTargetProtocolAddress()).getHostAddress() + "]\n";
- } catch (UnknownHostException e1) {
- return "Error during parsing Arp " + arp;
- }
- }
-
- public static byte[] macToBytes(MacAddress mac) {
- return HexEncode.bytesFromHexString(mac.getValue());
- }
-
- public static @Nullable MacAddress bytesToMac(byte[] macBytes) {
- String mac = HexEncode.bytesToHexStringFormat(macBytes);
- if (!"null".equals(mac)) {
- return new MacAddress(mac);
- }
- return null;
- }
-
- public static byte[] ipToBytes(Ipv4Address ip) {
- return InetAddresses.forString(ip.getValue()).getAddress();
- }
-
- public static @Nullable Ipv4Address bytesToIp(byte[] ipv4AsBytes) {
- try {
- return new Ipv4Address(InetAddress.getByAddress(ipv4AsBytes).getHostAddress());
- } catch (UnknownHostException e) {
- return null;
- }
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services.arp;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.ImmutableList;
-import com.google.common.util.concurrent.FutureCallback;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.JdkFutureAdapters;
-import com.google.common.util.concurrent.ListenableFuture;
-import com.google.common.util.concurrent.ListeningExecutorService;
-import com.google.common.util.concurrent.MoreExecutors;
-import com.google.common.util.concurrent.ThreadFactoryBuilder;
-import java.math.BigInteger;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map.Entry;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ThreadFactory;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicLong;
-import org.opendaylight.netvirt.openstack.netvirt.api.ConfigurationService;
-import org.opendaylight.netvirt.openstack.netvirt.api.GatewayMacResolver;
-import org.opendaylight.netvirt.openstack.netvirt.api.GatewayMacResolverListener;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheManager;
-import org.opendaylight.netvirt.openstack.netvirt.providers.ConfigInterface;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.AbstractServiceInstance;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.openflowplugin.api.OFConstants;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
-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.service.rev130819.AddFlowInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.SalFlowService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowCookie;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowModFlags;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowRef;
-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.Match;
-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.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;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.EthernetMatch;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.ArpMatch;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketProcessingListener;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketProcessingService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceived;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- *
- * @author Anil Vishnoi (avishnoi@Brocade.com)
- *
- */
-public class GatewayMacResolverService extends AbstractServiceInstance
- implements ConfigInterface, GatewayMacResolver,PacketProcessingListener {
-
- private static final Logger LOG = LoggerFactory.getLogger(GatewayMacResolverService.class);
- private static final String ARP_REPLY_TO_CONTROLLER_FLOW_NAME = "GatewayArpReplyRouter";
- private static final int ARP_REPLY_TO_CONTROLLER_FLOW_PRIORITY = 10000;
- private static final Instruction SEND_TO_CONTROLLER_INSTRUCTION;
- private ArpSender arpSender;
- private final SalFlowService flowService;
- private final AtomicLong flowCookie = new AtomicLong();
- private final ConcurrentMap<Ipv4Address, ArpResolverMetadata> gatewayToArpMetadataMap =
- new ConcurrentHashMap<>();
- private static final int ARP_WATCH_BROTHERS = 10;
- private static final int WAIT_CYCLES = 3;
- private static final int PER_CYCLE_WAIT_DURATION = 1000;
- private static final int REFRESH_INTERVAL = 10;
- private static final ThreadFactory threadFactoryArpWatcher = new ThreadFactoryBuilder()
- .setNameFormat("NV-ArpWatcher-%d").build();
- private static final ThreadFactory threadFactoryMacRefresher = new ThreadFactoryBuilder()
- .setNameFormat("NV-GWMacRfrshr-%d").build();
- private static final ThreadFactory threadFactoryRefreshReq = new ThreadFactoryBuilder()
- .setNameFormat("NV-RfrshRqstr-%d").build();
- private final ListeningExecutorService arpWatcherWall = MoreExecutors.listeningDecorator(
- Executors.newFixedThreadPool(ARP_WATCH_BROTHERS, threadFactoryArpWatcher));
- private final ScheduledExecutorService gatewayMacRefresherPool =
- Executors.newScheduledThreadPool(1, threadFactoryMacRefresher);
- private final ScheduledExecutorService refreshRequester =
- Executors.newSingleThreadScheduledExecutor(threadFactoryRefreshReq);
- private AtomicBoolean initializationDone = new AtomicBoolean(false);
- private volatile ConfigurationService configurationService;
- private volatile NodeCacheManager nodeCacheManager;
-
- private final PacketProcessingService packetProcessingService;
-
- static {
- ApplyActions applyActions = new ApplyActionsBuilder().setAction(
- ImmutableList.of(ArpFlowFactory.createSendToControllerAction(0))).build();
- SEND_TO_CONTROLLER_INSTRUCTION = new InstructionBuilder().setOrder(0)
- .setInstruction(new ApplyActionsCaseBuilder().setApplyActions(applyActions).build())
- .build();
- }
-
- public GatewayMacResolverService(final PacketProcessingService packetProcessingService, final SalFlowService salFlowService) {
- this(Service.GATEWAY_RESOLVER, packetProcessingService, salFlowService);
- }
-
- public GatewayMacResolverService(Service service, final PacketProcessingService packetProcessingService, final SalFlowService salFlowService) {
- super(service);
- this.packetProcessingService = packetProcessingService;
- this.flowService = salFlowService;
- }
-
- private void init(){
- if(!initializationDone.get()){
- initializationDone.set(true);
- if (packetProcessingService != null) {
- LOG.debug("{} was found.", PacketProcessingService.class.getSimpleName());
- this.arpSender = new ArpSender(packetProcessingService);
- } else {
- LOG.error("Missing service {}", PacketProcessingService.class.getSimpleName());
- this.arpSender = null;
- }
- refreshRequester.scheduleWithFixedDelay(() -> {
- if (!gatewayToArpMetadataMap.isEmpty()){
- for(final Entry<Ipv4Address, ArpResolverMetadata> gatewayToArpMetadataEntry : gatewayToArpMetadataMap.entrySet()){
- final Ipv4Address gatewayIp = gatewayToArpMetadataEntry.getKey();
- final ArpResolverMetadata gatewayMetaData =
- checkAndGetExternalBridgeDpid(
- resetFlowToRemove(gatewayIp, gatewayToArpMetadataEntry.getValue()));
- gatewayMacRefresherPool.schedule(() -> {
-
- final Node externalNetworkBridge = getExternalBridge(gatewayMetaData.getExternalNetworkBridgeDpid());
- if(externalNetworkBridge == null){
- LOG.error("MAC address for gateway {} can not be resolved, because external bridge {} "
- + "is not connected to controller.",
- gatewayIp.getValue(),
- gatewayMetaData.getExternalNetworkBridgeDpid() );
- } else {
- LOG.debug("Refresh Gateway Mac for gateway {} using source ip {} and mac {} for ARP request",
- gatewayIp.getValue(),gatewayMetaData.getArpRequestSourceIp().getValue(),gatewayMetaData.getArpRequestSourceMacAddress().getValue());
-
- sendGatewayArpRequest(externalNetworkBridge,gatewayIp,gatewayMetaData.getArpRequestSourceIp(), gatewayMetaData.getArpRequestSourceMacAddress());
- }
- }, 1, TimeUnit.SECONDS);
- }
- }
- }, REFRESH_INTERVAL, REFRESH_INTERVAL, TimeUnit.SECONDS);
- }
- }
- /**
- * Method do following actions:
- * 1. Install flow to direct ARP response packet to controller
- * 2. Send ARP request packet out on all port of the given External network bridge.
- * 3. Cache the flow that need to be removed once ARP resolution is done.
- * 4. Return listenable future so that user can add callback to get the MacAddress
- * @param externalNetworkBridgeDpid Broadcast ARP request packet on this bridge
- * @param gatewayIp IP address for which MAC need to be resolved
- * @param sourceIpAddress Source Ip address for the ARP request packet
- * @param sourceMacAddress Source Mac address for the ARP request packet
- * @param periodicRefresh Enable/Disable periodic refresh of the Gateway Mac address
- * @return Future object
- */
- @Override
- public ListenableFuture<MacAddress> resolveMacAddress(
- final GatewayMacResolverListener gatewayMacResolverListener, final Long externalNetworkBridgeDpid,
- final Boolean refreshExternalNetworkBridgeDpidIfNeeded,
- final Ipv4Address gatewayIp, final Ipv4Address sourceIpAddress, final MacAddress sourceMacAddress,
- final Boolean periodicRefresh){
- Preconditions.checkNotNull(refreshExternalNetworkBridgeDpidIfNeeded);
- Preconditions.checkNotNull(sourceIpAddress);
- Preconditions.checkNotNull(sourceMacAddress);
- Preconditions.checkNotNull(gatewayIp);
-
- LOG.info("Trigger Mac resolution for gateway {}, using source ip {} and mac {}",
- gatewayIp.getValue(),sourceIpAddress.getValue(),sourceMacAddress.getValue());
-
- init();
- if(gatewayToArpMetadataMap.containsKey(gatewayIp)){
- if(gatewayToArpMetadataMap.get(gatewayIp).getGatewayMacAddress() != null){
- return arpWatcherWall.submit(() -> gatewayToArpMetadataMap.get(gatewayIp).getGatewayMacAddress());
- }
- }else{
- gatewayToArpMetadataMap.put(gatewayIp,new ArpResolverMetadata(gatewayMacResolverListener,
- externalNetworkBridgeDpid, refreshExternalNetworkBridgeDpidIfNeeded,
- gatewayIp, sourceIpAddress, sourceMacAddress, periodicRefresh));
- }
-
-
- final Node externalNetworkBridge = getExternalBridge(externalNetworkBridgeDpid);
- if (externalNetworkBridge == null) {
- if (!refreshExternalNetworkBridgeDpidIfNeeded) {
- LOG.error("MAC address for gateway {} can not be resolved, because external bridge {} "
- + "is not connected to controller.", gatewayIp.getValue(), externalNetworkBridgeDpid);
- } else {
- LOG.debug("MAC address for gateway {} can not be resolved, since dpid was not refreshed yet",
- gatewayIp.getValue());
- }
- return null;
- }
-
- sendGatewayArpRequest(externalNetworkBridge,gatewayIp,sourceIpAddress, sourceMacAddress);
-
- //Wait for MacAddress population in cache
- return waitForMacAddress(gatewayIp);
- }
-
- private Node getExternalBridge(final Long externalNetworkBridgeDpid){
- if (externalNetworkBridgeDpid != null) {
- final String nodeName = OPENFLOW + externalNetworkBridgeDpid;
- return getOpenFlowNode(nodeName);
- }
- return null;
- }
-
- private ArpResolverMetadata checkAndGetExternalBridgeDpid(ArpResolverMetadata gatewayMetaData) {
- final Long origDpid = gatewayMetaData.getExternalNetworkBridgeDpid();
-
- // If we are not allowing dpid to change, there is nothing further to do here
- if (!gatewayMetaData.isRefreshExternalNetworkBridgeDpidIfNeeded()) {
- return gatewayMetaData;
- }
-
- // If current dpid is null, or if mac is not getting resolved, make an attempt to
- // grab a different dpid, so a different (or updated) external bridge gets used
- if (origDpid == null || !gatewayMetaData.isGatewayMacAddressResolved()) {
- Long newDpid = getAnotherExternalBridgeDpid(origDpid);
- gatewayMetaData.setExternalNetworkBridgeDpid(newDpid);
- }
-
- return gatewayMetaData;
- }
-
- private Long getAnotherExternalBridgeDpid(final Long unwantedDpid) {
- LOG.trace("Being asked to find a new dpid. unwantedDpid:{} cachemanager:{} configurationService:{}",
- unwantedDpid, nodeCacheManager, configurationService);
-
- if (nodeCacheManager == null) {
- LOG.error("Unable to find external dpid to use for resolver: no nodeCacheManager");
- return unwantedDpid;
- }
- if (configurationService == null) {
- LOG.error("Unable to find external dpid to use for resolver: no configurationService");
- return unwantedDpid;
- }
-
- // Pickup another dpid in list that is different than the unwanted one provided and is in the
- // operational tree. If none can be found, return the provided dpid as a last resort.
- // NOTE: We are assuming that all the br-ex are serving one external network and gateway ip of
- // the external network is reachable from every br-ex
- // TODO: Consider other deployment scenario, and think of another solution.
- List<Long> dpids = nodeCacheManager.getBridgeDpids(configurationService.getExternalBridgeName());
- Collections.shuffle(dpids);
- for (Long dpid : dpids) {
- if (dpid == null || dpid.equals(unwantedDpid) || getExternalBridge(dpid) == null) {
- continue;
- }
-
- LOG.debug("Gateway Mac Resolver Service will use dpid {}", dpid);
- return dpid;
- }
-
- LOG.warn("Unable to find usable external dpid for resolver. Best choice is still {}", unwantedDpid);
- return unwantedDpid;
- }
-
- private void sendGatewayArpRequest(final Node externalNetworkBridge,final Ipv4Address gatewayIp,
- final Ipv4Address sourceIpAddress, final MacAddress sourceMacAddress){
- final ArpMessageAddress senderAddress = new ArpMessageAddress(sourceMacAddress,sourceIpAddress);
-
- //Build arp reply router flow
- final Flow arpReplyToControllerFlow = createArpReplyToControllerFlow(senderAddress, gatewayIp);
-
- final InstanceIdentifier<Node> nodeIid = InstanceIdentifier.builder(Nodes.class)
- .child(Node.class, externalNetworkBridge.getKey())
- .build();
- final InstanceIdentifier<Flow> flowIid = createFlowIid(arpReplyToControllerFlow, nodeIid);
- final NodeRef nodeRef = new NodeRef(nodeIid);
-
- //Install flow
- Future<RpcResult<AddFlowOutput>> addFlowResult = flowService.addFlow(new AddFlowInputBuilder(
- arpReplyToControllerFlow).setFlowRef(new FlowRef(flowIid)).setNode(nodeRef).build());
- //wait for flow installation
- Futures.addCallback(JdkFutureAdapters.listenInPoolThread(addFlowResult),
- new FutureCallback<RpcResult<AddFlowOutput>>() {
-
- @Override
- public void onSuccess(RpcResult<AddFlowOutput> result) {
- if (!result.isSuccessful()) {
- LOG.warn("Flow to route ARP Reply to Controller is not installed successfully : {} \nErrors: {}", flowIid,result.getErrors());
- return;
- }
- LOG.debug("Flow to route ARP Reply to Controller installed successfully : {}", flowIid);
-
- ArpResolverMetadata gatewayArpMetadata = gatewayToArpMetadataMap.get(gatewayIp);
- if (gatewayArpMetadata == null) {
- LOG.warn("No metadata found for gatewayIp: {}", gatewayIp);
- return;
- }
-
- //cache metadata
- gatewayArpMetadata.setFlowToRemove(new RemoveFlowInputBuilder(arpReplyToControllerFlow).setNode(nodeRef).build());
-
- //get MAC DA for ARP packets
- MacAddress arpRequestDestMacAddress = gatewayArpMetadata.getArpRequestDestMacAddress();
-
- //Send ARP request packets
- for (NodeConnector egressNc : externalNetworkBridge.getNodeConnector()) {
- KeyedInstanceIdentifier<NodeConnector, NodeConnectorKey> egressNcIid = nodeIid.child(
- NodeConnector.class, new NodeConnectorKey(egressNc.getId()));
- ListenableFuture<RpcResult<Void>> futureSendArpResult = arpSender.sendArp(
- senderAddress, gatewayIp, arpRequestDestMacAddress, egressNcIid);
- Futures.addCallback(futureSendArpResult, logResult(gatewayIp, egressNcIid));
- }
- }
-
- @Override
- public void onFailure(Throwable t) {
- LOG.warn("ARP Reply to Controller flow was not created: {}", flowIid, t);
- }
- }
- );
- }
-
- private ListenableFuture<MacAddress> waitForMacAddress(final Ipv4Address gatewayIp){
-
- return arpWatcherWall.submit(() -> {
- for(int cycle = 0;cycle < WAIT_CYCLES;cycle++){
- //Sleep before checking mac address, so meanwhile ARP request packets
- // will be broadcasted on the bridge.
- Thread.sleep(PER_CYCLE_WAIT_DURATION);
- ArpResolverMetadata arpResolverMetadata = gatewayToArpMetadataMap.get(gatewayIp);
- if(arpResolverMetadata != null && arpResolverMetadata.getGatewayMacAddress() != null){
- if(!arpResolverMetadata.isPeriodicRefresh()){
- resetFlowToRemove(gatewayIp, arpResolverMetadata);
- return gatewayToArpMetadataMap.remove(gatewayIp).getGatewayMacAddress();
- }
- return arpResolverMetadata.getGatewayMacAddress();
- }
- }
- return null;
- });
- }
-
- private Flow createArpReplyToControllerFlow(final ArpMessageAddress senderAddress, final Ipv4Address ipForRequestedMac) {
- checkNotNull(senderAddress);
- checkNotNull(ipForRequestedMac);
- FlowBuilder arpFlow = new FlowBuilder().setTableId(Service.CLASSIFIER.getTable())
- .setFlowName(ARP_REPLY_TO_CONTROLLER_FLOW_NAME)
- .setPriority(ARP_REPLY_TO_CONTROLLER_FLOW_PRIORITY)
- .setBufferId(OFConstants.OFP_NO_BUFFER)
- .setIdleTimeout(0)
- .setHardTimeout(0)
- .setCookie(new FlowCookie(BigInteger.valueOf(flowCookie.incrementAndGet())))
- .setFlags(new FlowModFlags(false, false, false, false, false));
-
- EthernetMatch ethernetMatch = ArpFlowFactory.createEthernetMatch(senderAddress.getHardwareAddress());
- ArpMatch arpMatch = ArpFlowFactory.createArpMatch(senderAddress, ipForRequestedMac);
- Match match = new MatchBuilder().setEthernetMatch(ethernetMatch).setLayer3Match(arpMatch).build();
- arpFlow.setMatch(match);
- arpFlow.setInstructions(new InstructionsBuilder().setInstruction(
- ImmutableList.of(SEND_TO_CONTROLLER_INSTRUCTION)).build());
- arpFlow.setId(createFlowId(ipForRequestedMac));
- return arpFlow.build();
- }
-
- private FlowId createFlowId(Ipv4Address ipForRequestedMac) {
- String flowId = ARP_REPLY_TO_CONTROLLER_FLOW_NAME + "|" + ipForRequestedMac.getValue();
- return new FlowId(flowId);
- }
-
- private static InstanceIdentifier<Flow> createFlowIid(Flow flow, InstanceIdentifier<Node> nodeIid) {
- return nodeIid.builder()
- .augmentation(FlowCapableNode.class)
- .child(Table.class, new TableKey(flow.getTableId()))
- .child(Flow.class, new FlowKey(flow.getId()))
- .build();
- }
-
- private FutureCallback<RpcResult<Void>> logResult(final Ipv4Address tpa,
- final KeyedInstanceIdentifier<NodeConnector, NodeConnectorKey> egressNcIid) {
- return new FutureCallback<RpcResult<Void>>() {
-
- @Override
- public void onSuccess(RpcResult<Void> result) {
- LOG.debug("ARP Request for IP {} was sent from {}.", tpa.getValue(), egressNcIid);
- }
-
- @Override
- public void onFailure(Throwable t) {
- LOG.warn("ARP Request for IP {} was NOT sent from {}.", tpa.getValue(), egressNcIid);
- }
- };
- }
-
- @Override
- public void onPacketReceived(PacketReceived potentialArp) {
- Arp arp = ArpResolverUtils.getArpFrom(potentialArp);
- if(arp != null){
- if (arp.getOperation() != ArpOperation.REPLY.intValue()) {
- LOG.trace("Packet is not ARP REPLY packet.");
- return;
- }
- if (LOG.isTraceEnabled()) {
- LOG.trace("ARP REPLY received - {}", ArpUtils.getArpToStringFormat(arp));
- }
- NodeKey nodeKey = potentialArp.getIngress().getValue().firstKeyOf(Node.class, NodeKey.class);
- if (nodeKey == null) {
- LOG.info("Unknown source node of ARP packet: {}", potentialArp);
- return;
- }
- Ipv4Address gatewayIpAddress = ArpUtils.bytesToIp(arp.getSenderProtocolAddress());
- MacAddress gatewayMacAddress = ArpUtils.bytesToMac(arp.getSenderHardwareAddress());
- ArpResolverMetadata candidateGatewayIp = gatewayToArpMetadataMap.get(gatewayIpAddress);
- if(candidateGatewayIp != null){
- LOG.debug("Resolved MAC for Gateway Ip {} is {}",gatewayIpAddress.getValue(),gatewayMacAddress.getValue());
- candidateGatewayIp.setGatewayMacAddress(gatewayMacAddress);
- resetFlowToRemove(gatewayIpAddress, candidateGatewayIp);
- }
- }
- }
-
- @Override
- public void setDependencies(BundleContext bundleContext,
- ServiceReference serviceReference) {
- super.setDependencies(bundleContext.getServiceReference(GatewayMacResolver.class.getName()), this);
-
- }
-
- @Override
- public void setDependencies(Object impl) {
- if (impl instanceof NodeCacheManager) {
- nodeCacheManager = (NodeCacheManager) impl;
- } else if (impl instanceof ConfigurationService) {
- configurationService = (ConfigurationService) impl;
- }
- }
-
- @Override
- public void stopPeriodicRefresh(Ipv4Address gatewayIp) {
- init();
- resetFlowToRemove(gatewayIp, null);
- gatewayToArpMetadataMap.remove(gatewayIp);
- }
-
- private ArpResolverMetadata resetFlowToRemove(
- final Ipv4Address gatewayIp, ArpResolverMetadata gatewayArpMetadata) {
- checkNotNull(gatewayIp);
-
- // If gatewayArpMetadata was not provided, look it up
- if (gatewayArpMetadata == null) {
- gatewayArpMetadata = gatewayToArpMetadataMap.get(gatewayIp);
- }
- if (gatewayArpMetadata != null && gatewayArpMetadata.getFlowToRemove() != null) {
- LOG.debug("Flow to route ARP Reply to Controller from {} being removed from node {}",
- gatewayIp, gatewayArpMetadata.getFlowToRemove().getNode());
- flowService.removeFlow(gatewayArpMetadata.getFlowToRemove());
- gatewayArpMetadata.setFlowToRemove(null);
- }
- return gatewayArpMetadata;
- }
-
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
- xmlns:odl="http://opendaylight.org/xmlns/blueprint/v1.0.0"
- odl:use-default-for-reference-types="true">
-
- <reference id="dataBroker"
- interface="org.opendaylight.controller.md.sal.binding.api.DataBroker" />
- <reference id="entityOwnershipService"
- interface="org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService" />
- <reference id="notificationService"
- interface="org.opendaylight.controller.sal.binding.api.NotificationProviderService" />
- <reference id="rpcRegistry"
- interface="org.opendaylight.controller.sal.binding.api.RpcProviderRegistry" />
- <reference id="ovsdbInventoryService"
- interface="org.opendaylight.netvirt.openstack.netvirt.api.OvsdbInventoryService" />
-
- <odl:rpc-service id="salFlowService"
- interface="org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.SalFlowService" />
- <odl:rpc-service id="packetProcessingService"
- interface="org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketProcessingService" />
-
- <bean id="netvirtProviders"
- class="org.opendaylight.netvirt.openstack.netvirt.providers.NetvirtProvidersProvider"
- init-method="start" destroy-method="close">
- <argument ref="dataBroker" />
- <argument ref="entityOwnershipService" />
- <argument ref="notificationService" />
- <argument ref="packetProcessingService" />
- <argument ref="salFlowService" />
- <argument value="0" />
- </bean>
-
-</blueprint>
+++ /dev/null
-module netvirt-providers-config {
- yang-version 1;
- namespace "urn:opendaylight:params:xml:ns:yang:netvirt:providers:config";
- prefix "netvirt-providers-config";
-
- revision "2016-01-09" {
- description "Initial revision of the netvirt providers config";
- }
-
- container netvirt-providers-config {
- description "Configuration for NetvirtProviders";
-
- config true;
-
- leaf table-offset {
- description "The table-offset is used to set the starting table for the netvirt pipeline";
- type uint8;
- default 0;
- }
-
- leaf security-group-tcp-idle-timeout {
- type uint16;
- default 18000;
- }
- leaf security-group-tcp-hard-timeout {
- type uint16;
- default 0;
- }
- leaf security-group-tcp-fin-idle-timeout {
- type uint16;
- default 300;
- }
- leaf security-group-tcp-fin-hard-timeout {
- type uint16;
- default 0;
- }
- leaf security-group-udp-idle-timeout {
- type uint16;
- default 300;
- }
- leaf security-group-udp-hard-timeout {
- type uint16;
- default 0;
- }
- leaf security-group-default-idle-timeout {
- type uint16;
- default 300;
- }
- leaf security-group-default-hard-timeout {
- type uint16;
- default 0;
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.providers;
-
-import static org.junit.Assert.assertEquals;
-
-import org.junit.Test;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-
-/**
- * Unit tests for {@link NetvirtProvidersProvider}
- */
-public class NetvirtProvidersProviderTest {
-
- /**
- * Test for {@link NetvirtProvidersProvider#getTableOffset()}
- */
- @Test
- public void testGetTableOffset() {
- short tableOffset = 10;
- NetvirtProvidersProvider.setTableOffset(tableOffset);
- assertEquals("Table offset was not set", tableOffset, NetvirtProvidersProvider.getTableOffset());
- }
-
- /**
- * Test for method {@link NetvirtProvidersProvider#setTableOffset(short)}
- */
- @Test
- public void testSetTableOffset() {
- // verify a good value can be set
- short tableOffset = 0;
-
- tableOffset = 10;
- NetvirtProvidersProvider.setTableOffset(tableOffset);
- assertEquals("tableOffset was not set", tableOffset, NetvirtProvidersProvider.getTableOffset());
- }
-
- /**
- * Negative test for method {@link NetvirtProvidersProvider#setTableOffset(short)}
- */
- @Test
- public void testTableOffsetNegative() {
- // verify an out of range value is not set
- short tableOffset = 0;
- NetvirtProvidersProvider.setTableOffset(tableOffset);
- short tableOffsetBad = (short)(256 - Service.L2_FORWARDING.getTable());
- NetvirtProvidersProvider.setTableOffset(tableOffsetBad);
- assertEquals("tableOffset should not be set", 0, NetvirtProvidersProvider.getTableOffset());
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2016 Inocybe 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.netvirt.openstack.netvirt.providers.openflow13;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-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;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
-import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
-import org.opendaylight.netvirt.openstack.netvirt.providers.NetvirtProvidersProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-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.instruction.list.InstructionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
-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.support.membermodification.MemberModifier;
-import org.powermock.modules.junit4.PowerMockRunner;
-
-import com.google.common.base.Optional;
-import com.google.common.util.concurrent.CheckedFuture;
-
-/**
- * Unit test for {@link AbstractServiceInstance}
- */
-@RunWith(PowerMockRunner.class)
-@SuppressWarnings("unchecked")
-public class AbstractServiceInstanceTest {
-
- @InjectMocks private AbstractServiceInstance abstractServiceInstance = mock(AbstractServiceInstance.class, Mockito.CALLS_REAL_METHODS);
-
- @Mock private DataBroker dataBroker;
- @Mock private PipelineOrchestrator orchestrator;
- @Mock private Southbound southbound;
-
- private Service service = Service.L3_FORWARDING;
-
- private final String ID = "5710881121";
- private final String NODE_ID = Constants.INTEGRATION_BRIDGE + ":" + ID;
-
- /**
- * Test method {@link AbstractServiceInstance#isBridgeInPipeline(Node)}
- */
- @Test
- public void testIsBridgeInPipeline() {
- when(southbound.getBridgeName(any(Node.class))).thenReturn(Constants.INTEGRATION_BRIDGE);
- assertTrue("Error, isBridgeInPipeline() did not return the correct value", abstractServiceInstance.isBridgeInPipeline(mock(Node.class)));
- }
-
- /**
- * Test method {@link AbstractServiceInstance#getTable()}
- */
- @Test
- public void testGetTable() {
- abstractServiceInstance.setService(service);
- assertEquals("Error, getTable() did not return the correct value",
- service.getTable(), abstractServiceInstance.getTable());
-
- when(orchestrator.getTableOffset()).thenReturn(Service.DIRECTOR.getTable());
- assertEquals("Error, getTable() did not return the correct value",
- (short)(Service.DIRECTOR.getTable() + service.getTable()), abstractServiceInstance.getTable());
- }
-
- /**
- * Test method {@link AbstractServiceInstance#getTable(Service)}
- */
- @Test
- public void testGetTableWithService() {
- when(orchestrator.getTableOffset()).thenReturn((short)0);
- abstractServiceInstance.setService(service);
- assertEquals("Error, getTables(service) did not return the correct value",
- Service.L2_FORWARDING.getTable(), abstractServiceInstance.getTable(Service.L2_FORWARDING));
- }
-
- @Test
- public void testGetService() {
- abstractServiceInstance.setService(service);
- assertEquals("Error, getService() did not return the correct value", service, abstractServiceInstance.getService());
- }
-
- /**
- * Test method {@link AbstractServiceInstance#createNodeBuilder(String)}
- */
- @Test
- public void testCreateNodeBuilder() {
- NodeId nodeId = mock(NodeId.class);
- when(nodeId.getValue()).thenReturn(NODE_ID);
-
- NodeBuilder nodeBuilder = abstractServiceInstance.createNodeBuilder(NODE_ID);
- assertNotNull("Error, createNodeBuilder() did not return the correct value", nodeBuilder);
- assertEquals("Error, createNodeBuilder() did not return the correct ID", NODE_ID, nodeBuilder.getId().getValue());
- assertEquals("Error, createNodeBuilder() did not return the correct Key", new NodeKey(nodeBuilder.getId()), nodeBuilder.getKey());
- }
-
- /**
- * Test method {@link AbstractServiceInstance#getMutablePipelineInstructionBuilder()}
- */
- @Test
- public void testGetMutablePipelineInstructionBuilder() {
- // service == null
- assertNotNull("Error, getMutablePipelineInstructionBuilder() did not return the correct value", abstractServiceInstance.getMutablePipelineInstructionBuilder());
- assertTrue("Error, getMutablePipelineInstructionBuilder() did not return a InstructionBuilder object", abstractServiceInstance.getMutablePipelineInstructionBuilder() instanceof InstructionBuilder);
-
- when(orchestrator.getNextServiceInPipeline(any(Service.class))).thenReturn(Service.ARP_RESPONDER);
-
- // service defined
- assertNotNull("Error, getMutablePipelineInstructionBuilder() did not return the correct value", abstractServiceInstance.getMutablePipelineInstructionBuilder());
- assertTrue("Error, getMutablePipelineInstructionBuilder() did not return a InstructionBuilder object", abstractServiceInstance.getMutablePipelineInstructionBuilder() instanceof InstructionBuilder);
- }
-
- /**
- * Test method {@link AbstractServiceInstance#writeFlow(FlowBuilder, NodeBuilder)}
- */
- @Test
- public void testWriteFlow() throws Exception {
- WriteTransaction transaction = mock(WriteTransaction.class);
- when(dataBroker.newWriteOnlyTransaction()).thenReturn(transaction);
- CheckedFuture<Void, TransactionCommitFailedException> commitFuture = mock(CheckedFuture.class);
- when(transaction.submit()).thenReturn(commitFuture);
-
- NodeBuilder nodeBuilder = mock(NodeBuilder.class);
- when(nodeBuilder.getKey()).thenReturn(mock(NodeKey.class));
-
- FlowBuilder flowBuilder = mock(FlowBuilder.class);
- when(flowBuilder.getKey()).thenReturn(mock(FlowKey.class));
-
- NetvirtProvidersProvider netvirtProvider = mock(NetvirtProvidersProvider.class);
- MemberModifier.field(NetvirtProvidersProvider.class, "hasProviderEntityOwnership").set(netvirtProvider, new AtomicBoolean(true));
-
- abstractServiceInstance.writeFlow(flowBuilder, nodeBuilder);
-
- //verify(transaction, times(1)).put(eq(LogicalDatastoreType.CONFIGURATION), any(InstanceIdentifier.class), any(DataObject.class), eq(true));
- //verify(transaction, times(1)).merge(eq(LogicalDatastoreType.CONFIGURATION), any(InstanceIdentifier.class), any(DataObject.class), eq(true));
- //verify(commitFuture, times(1)).get();
- }
-
- /**
- * Test method {@link AbstractServiceInstance#removeFlow(FlowBuilder, NodeBuilder)}
- */
- @Test
- public void testRemoveFlow() throws Exception {
- WriteTransaction transaction = mock(WriteTransaction.class);
- when(dataBroker.newWriteOnlyTransaction()).thenReturn(transaction);
- CheckedFuture<Void, TransactionCommitFailedException> commitFuture = mock(CheckedFuture.class);
- when(transaction.submit()).thenReturn(commitFuture);
-
- NodeBuilder nodeBuilder = mock(NodeBuilder.class);
- when(nodeBuilder.getKey()).thenReturn(mock(NodeKey.class));
-
- FlowBuilder flowBuilder = mock(FlowBuilder.class);
- when(flowBuilder.getKey()).thenReturn(mock(FlowKey.class));
-
- NetvirtProvidersProvider netvirtProvider = mock(NetvirtProvidersProvider.class);
- MemberModifier.field(NetvirtProvidersProvider.class, "hasProviderEntityOwnership").set(netvirtProvider, new AtomicBoolean(true));
-
- abstractServiceInstance.removeFlow(flowBuilder, nodeBuilder);
- verify(transaction, times(1)).delete(eq(LogicalDatastoreType.CONFIGURATION), any(InstanceIdentifier.class));
- verify(commitFuture, times(1)).get();
- }
-
- /**
- * Test method {@link AbstractServiceInstance#getFlow(FlowBuilder, NodeBuilder)}
- */
- @Test
- public void testGetFlow() throws Exception {
- ReadOnlyTransaction transaction = mock(ReadOnlyTransaction.class);
- when(dataBroker.newReadOnlyTransaction()).thenReturn(transaction);
- //when(mdsalConsumer.getDataBroker()).thenReturn(dataBrocker);
-
- NodeBuilder nodeBuilder = mock(NodeBuilder.class);
- when(nodeBuilder.getKey()).thenReturn(mock(NodeKey.class));
-
- FlowBuilder flowBuilder = mock(FlowBuilder.class);
- when(flowBuilder.getKey()).thenReturn(mock(FlowKey.class));
-
- CheckedFuture dataRead = mock(CheckedFuture.class);
- when(transaction.read(eq(LogicalDatastoreType.CONFIGURATION), any(InstanceIdentifier.class))).thenReturn(dataRead);
- Optional<Flow> data = mock(Optional.class);
- when(dataRead.get()).thenReturn(data);
-
- abstractServiceInstance.getFlow(flowBuilder, nodeBuilder);
- verify(transaction, times(1)).read(eq(LogicalDatastoreType.CONFIGURATION), any(InstanceIdentifier.class));
- }
-
- /**
- * Test method {@link AbstractServiceInstance#programDefaultPipelineRule(Node)}
- */
- @Test
- public void testProgramDefaultPipelineRule() {
- when(southbound.getBridgeName(any(Node.class))).thenReturn(Constants.INTEGRATION_BRIDGE);
- when(southbound.getDataPathId(any(Node.class))).thenReturn(261L);
-
- when(orchestrator.getNextServiceInPipeline(any(Service.class))).thenReturn(Service.ARP_RESPONDER);
-
- abstractServiceInstance.setService(service);
-
- WriteTransaction transaction = mock(WriteTransaction.class);
- when(dataBroker.newWriteOnlyTransaction()).thenReturn(transaction);
- CheckedFuture<Void, TransactionCommitFailedException> commitFuture = mock(CheckedFuture.class);
- when(transaction.submit()).thenReturn(commitFuture);
-
- NodeBuilder nodeBuilder = mock(NodeBuilder.class);
- when(nodeBuilder.getKey()).thenReturn(mock(NodeKey.class));
-
- FlowBuilder flowBuilder = mock(FlowBuilder.class);
- when(flowBuilder.getKey()).thenReturn(mock(FlowKey.class));
-
- abstractServiceInstance.programDefaultPipelineRule(mock(Node.class));
-
- verify(abstractServiceInstance, times(1)).isBridgeInPipeline(any(Node.class));
- verify(abstractServiceInstance, times(1)).createNodeBuilder(anyString());
- verify(abstractServiceInstance, times(1)).writeFlow(any(FlowBuilder.class), any(NodeBuilder.class));
- }
-
- @Test
- public void testSetDependencies() throws Exception {
- PipelineOrchestrator pipelineOrchestrator = mock(PipelineOrchestrator.class);
- Southbound southbound = mock(Southbound.class);
-
- ServiceHelper.overrideGlobalInstance(PipelineOrchestrator.class, pipelineOrchestrator);
- ServiceHelper.overrideGlobalInstance(Southbound.class, southbound);
-
- abstractServiceInstance.setDependencies(mock(ServiceReference.class), mock(AbstractServiceInstance.class));
-
- assertEquals("Error, did not return the correct object", getField("orchestrator"), pipelineOrchestrator);
- assertEquals("Error, did not return the correct object", getField("southbound"), southbound);
- }
-
- private Object getField(String fieldName) throws Exception {
- Field field = AbstractServiceInstance.class.getDeclaredField(fieldName);
- field.setAccessible(true);
- return field.get(abstractServiceInstance);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2016 Inocybe Technologies. 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.netvirt.openstack.netvirt.providers.openflow13;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyBoolean;
-import static org.mockito.Matchers.anyLong;
-import static org.mockito.Matchers.anyShort;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Matchers.same;
-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;
-import java.net.InetAddress;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.opendaylight.netvirt.openstack.netvirt.NetworkHandler;
-import org.opendaylight.netvirt.openstack.netvirt.api.ClassifierProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.L2ForwardingProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.TenantNetworkManager;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.openstack.netvirt.MdsalHelper;
-import org.opendaylight.netvirt.openstack.netvirt.api.BridgeConfigurationManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.ConfigurationService;
-import org.opendaylight.netvirt.openstack.netvirt.api.EgressAclProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.IngressAclProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.NetworkingProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.NetworkingProviderManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.SecurityServicesManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.openstack.netvirt.api.Status;
-import org.opendaylight.netvirt.openstack.netvirt.api.StatusCode;
-import org.opendaylight.netvirt.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.NodeId;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.powermock.api.mockito.PowerMockito;
-import org.powermock.api.support.membermodification.MemberMatcher;
-import org.powermock.api.support.membermodification.MemberModifier;
-import org.powermock.core.classloader.annotations.PrepareForTest;
-import org.powermock.modules.junit4.PowerMockRunner;
-import org.powermock.reflect.Whitebox;
-
-/**
- * Unit test for {@link OF13Provider}
- */
-@PrepareForTest({OF13Provider.class, InetAddress.class, MdsalHelper.class, ServiceHelper.class})
-@RunWith(PowerMockRunner.class)
-public class OF13ProviderTest {
-
- @Mock private OF13Provider of13Provider;
-
- private static final String TYPE = "gre";
- private static final String IP = "127.0.0.1";
- private static final String BR_INT = "br-int";
- private static final String ID = "4";
- private static final String PORT = "port-int";
- private static final String SEG_ID = "5";
- private static final String MAC_ADDRESS = "mac-address";
- private static final long LOCAL_PORT = 3;
-
- @Before
- public void setUp() throws Exception{
- of13Provider = PowerMockito.mock(OF13Provider.class, Mockito.CALLS_REAL_METHODS);
- }
-
- @Test
- public void testGetName() {
- assertEquals("Error, did not return the correct name", OF13Provider.NAME, of13Provider.getName());
- }
-
- @Test
- public void testSupportsServices() {
- assertTrue("Error, did not return the correct boolean", of13Provider.supportsServices());
- }
-
- @Test
- public void testHasPerTenantTunneling() {
- assertFalse("Error, did not return the correct boolean", of13Provider.hasPerTenantTunneling());
- }
-
- @Test
- public void testGetTunnelReadinessStatus() throws Exception {
- ConfigurationService configurationService = mock(ConfigurationService.class);
- BridgeConfigurationManager bridgeConfigurationManager = mock(BridgeConfigurationManager.class);
- TenantNetworkManager tenantNetworkManager = mock(TenantNetworkManager.class);
-
- MemberModifier.field(OF13Provider.class, "configurationService").set(of13Provider , configurationService);
- MemberModifier.field(OF13Provider.class, "bridgeConfigurationManager").set(of13Provider , bridgeConfigurationManager);
- MemberModifier.field(OF13Provider.class, "tenantNetworkManager").set(of13Provider , tenantNetworkManager);
-
- assertEquals("Error, did not return the correct status code", new Status(StatusCode.NOTFOUND), Whitebox.invokeMethod(of13Provider, "getTunnelReadinessStatus", mock(Node.class), ""));
-
- when(configurationService.getTunnelEndPoint(any(Node.class))).thenReturn(mock(InetAddress.class));
- when(bridgeConfigurationManager.isNodeNeutronReady(any(Node.class))).thenReturn(false, true);
-
- assertEquals("Error, did not return the correct status code", new Status(StatusCode.NOTACCEPTABLE), Whitebox.invokeMethod(of13Provider, "getTunnelReadinessStatus", mock(Node.class), ""));
-
- when(tenantNetworkManager.isTenantNetworkPresentInNode(any(Node.class), anyString())).thenReturn(false, true);
-
- assertEquals("Error, did not return the correct status code", new Status(StatusCode.NOTACCEPTABLE), Whitebox.invokeMethod(of13Provider, "getTunnelReadinessStatus", mock(Node.class), ""));
- assertEquals("Error, did not return the correct status code", new Status(StatusCode.SUCCESS), Whitebox.invokeMethod(of13Provider, "getTunnelReadinessStatus", mock(Node.class), ""));
- }
-
- @Test
- public void testGetTunnelName() throws Exception {
- PowerMockito.mockStatic(InetAddress.class);
- InetAddress inetAddress = mock(InetAddress.class);
- PowerMockito.when(inetAddress.getHostAddress()).thenReturn(IP);
-
- String ret = TYPE + "-" + inetAddress.getHostAddress();
- assertEquals("Error, did not return the correct status code", ret, Whitebox.invokeMethod(of13Provider, "getTunnelName", TYPE, inetAddress));
- }
-
- @SuppressWarnings("unchecked")
- @Test
- public void testAddTunnelPort() throws Exception {
- ConfigurationService configurationService = mock(ConfigurationService.class);
- when(configurationService.getIntegrationBridgeName()).thenReturn(BR_INT);
- Southbound southbound = mock(Southbound.class);
- when(southbound.extractTerminationPointAugmentation(any(Node.class), anyString())).thenReturn(mock(OvsdbTerminationPointAugmentation.class));
- NodeId nodeId = mock(NodeId.class);
- when(nodeId.getValue()).thenReturn(ID);
- Node node = mock(Node.class);
- when(node.getNodeId()).thenReturn(nodeId);
-
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "getTunnelName", String.class, InetAddress.class));
-
- MemberModifier.field(OF13Provider.class, "configurationService").set(of13Provider , configurationService);
- MemberModifier.field(OF13Provider.class, "southbound").set(of13Provider , southbound);
-
- assertTrue("Error, did not add the port", (boolean) Whitebox.invokeMethod(of13Provider, "addTunnelPort", node, TYPE, mock(InetAddress.class), mock(InetAddress.class)));
-
- when(southbound.extractTerminationPointAugmentation(any(Node.class), anyString())).thenReturn(null);
- when(southbound.addTunnelTerminationPoint(any(Node.class), anyString(), anyString(), anyString(), any(HashMap.class))).thenReturn(false);
-
- assertFalse("Error, did add the port", (boolean) Whitebox.invokeMethod(of13Provider, "addTunnelPort", node, TYPE, mock(InetAddress.class), mock(InetAddress.class)));
-
- when(southbound.addTunnelTerminationPoint(any(Node.class), anyString(), anyString(), anyString(), any(HashMap.class))).thenReturn(true);
-
- assertTrue("Error, did not add the port", (boolean) Whitebox.invokeMethod(of13Provider, "addTunnelPort", node, TYPE, mock(InetAddress.class), mock(InetAddress.class)));
- PowerMockito.verifyPrivate(of13Provider, times(3)).invoke("getTunnelName", anyString(), any(InetAddress.class));
- }
-
- @Test
- public void testDeletePort() throws Exception {
- Southbound southbound = mock(Southbound.class);
- when(southbound.deleteTerminationPoint(any(Node.class), anyString())).thenReturn(false, true);
- MemberModifier.field(OF13Provider.class, "southbound").set(of13Provider , southbound);
-
- assertFalse("Error, did delete the port", (boolean) Whitebox.invokeMethod(of13Provider, "deletePort", mock(Node.class), TYPE, PORT));
- assertTrue("Error, did not delete the port", (boolean) Whitebox.invokeMethod(of13Provider, "deletePort", mock(Node.class), TYPE, PORT));
- }
-
- @Test
- public void testDeleteTunnelPort() throws Exception {
- ConfigurationService configurationService = mock(ConfigurationService.class);
- when(configurationService.getIntegrationBridgeName()).thenReturn(BR_INT);
-
- MemberModifier.field(OF13Provider.class, "configurationService").set(of13Provider , configurationService);
-
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "getTunnelName", String.class, InetAddress.class));
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "deletePort", Node.class, String.class, String.class));
-
- PowerMockito.when(of13Provider, "deletePort", any(Node.class), anyString(), anyString()).thenReturn(true);
-
- assertTrue("Error, did not delete the tunnel", (boolean) Whitebox.invokeMethod(of13Provider, "deleteTunnelPort", mock(Node.class), TYPE, mock(InetAddress.class), mock(InetAddress.class)));
-
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("getTunnelName", anyString(), any(InetAddress.class));
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("deletePort", any(Node.class), anyString(), anyString());
-
- PowerMockito.when(of13Provider, "deletePort", any(Node.class), anyString(), anyString()).thenReturn(false);
-
- assertFalse("Error, did delete the tunnel", (boolean) Whitebox.invokeMethod(of13Provider, "deleteTunnelPort", mock(Node.class), TYPE, mock(InetAddress.class), mock(InetAddress.class)));
-
- PowerMockito.verifyPrivate(of13Provider, times(2)).invoke("getTunnelName", anyString(), any(InetAddress.class));
- PowerMockito.verifyPrivate(of13Provider, times(2)).invoke("deletePort", any(Node.class), anyString(), anyString());
- }
-
- @Test
- public void testProgramLocalBridgeRules() throws Exception {
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "handleLocalInPort", Long.class, Short.class, Short.class, String.class, Long.class, String.class, boolean.class));
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "handleDropSrcIface", Long.class, Long.class, boolean.class));
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "handleLocalUcastOut", Long.class, Short.class, String.class, Long.class, String.class, boolean.class));
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "handleLocalBcastOut", Long.class, Short.class, String.class, Long.class, boolean.class));
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "handleTunnelFloodOut", Long.class, Short.class, Short.class, String.class, Long.class, boolean.class));
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "handleTunnelUnknownUcastFloodOut", Long.class, Short.class, Short.class, String.class, Long.class, boolean.class));
-
- Whitebox.invokeMethod(of13Provider, "programLocalBridgeRules", mock(Node.class), Long.valueOf("45"), SEG_ID, MAC_ADDRESS, LOCAL_PORT);
-
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("handleLocalInPort", anyLong(), anyShort(), anyShort(), anyString(), anyLong(), anyString(), anyBoolean());
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("handleDropSrcIface", anyLong(), anyLong(), anyBoolean());
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("handleLocalUcastOut", anyLong(), anyShort(), anyString(), anyLong(), anyString(), anyBoolean());
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("handleLocalBcastOut", anyLong(), anyShort(), anyString(), anyLong(), anyBoolean());
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("handleTunnelFloodOut", anyLong(), anyShort(), anyShort(), anyString(), anyLong(), anyBoolean());
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("handleTunnelUnknownUcastFloodOut", anyLong(), anyShort(), anyShort(), anyString(), anyLong(), anyBoolean());
- }
-
- @Test
- public void testRemoveLocalBridgeRules() throws Exception {
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "handleLocalInPort", Long.class, Short.class, Short.class, String.class, Long.class, String.class, boolean.class));
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "handleDropSrcIface", Long.class, Long.class, boolean.class));
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "handleLocalUcastOut", Long.class, Short.class, String.class, Long.class, String.class, boolean.class));
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "handleLocalBcastOut", Long.class, Short.class, String.class, Long.class, boolean.class));
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "handleTunnelFloodOut", Long.class, Short.class, Short.class, String.class, Long.class, boolean.class));
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "handleTunnelUnknownUcastFloodOut", Long.class, Short.class, Short.class, String.class, Long.class, boolean.class));
-
-
- Whitebox.invokeMethod(of13Provider, "removeLocalBridgeRules", mock(Node.class), Long.valueOf("45"), SEG_ID, MAC_ADDRESS, LOCAL_PORT, false);
-
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("handleLocalInPort", anyLong(), anyShort(), anyShort(), anyString(), anyLong(), anyString(), anyBoolean());
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("handleDropSrcIface", anyLong(), anyLong(), anyBoolean());
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("handleLocalUcastOut", anyLong(), anyShort(), anyString(), anyLong(), anyString(), anyBoolean());
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("handleLocalBcastOut", anyLong(), anyShort(), anyString(), anyLong(), anyBoolean());
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("handleTunnelFloodOut", anyLong(), anyShort(), anyShort(), anyString(), anyLong(), anyBoolean());
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("handleTunnelUnknownUcastFloodOut", anyLong(), anyShort(), anyShort(), anyString(), anyLong(), anyBoolean());
- }
-
- @Test
- public void testProgramLocalIngressTunnelBridgeRules() throws Exception {
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "handleTunnelIn", Long.class, Short.class, Short.class, String.class, Long.class, boolean.class));
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "handleTunnelFloodOut", Long.class, Short.class, Short.class, String.class, Long.class, boolean.class));
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "handleTunnelUnknownUcastFloodOut", Long.class, Short.class, Short.class, String.class, Long.class, boolean.class));
-
-
- Whitebox.invokeMethod(of13Provider, "programLocalIngressTunnelBridgeRules", mock(Node.class), Long.valueOf("45"), SEG_ID, MAC_ADDRESS, LOCAL_PORT, LOCAL_PORT);
-
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("handleTunnelIn", anyLong(), anyShort(), anyShort(), anyString(), anyLong(), anyBoolean());
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("handleTunnelFloodOut", anyLong(), anyShort(), anyShort(), anyString(), anyLong(), anyBoolean());
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("handleTunnelUnknownUcastFloodOut", anyLong(), anyShort(), anyShort(), anyString(), anyLong(), anyBoolean());
- }
-
- @Test
- public void testProgramRemoteEgressTunnelBridgeRules() throws Exception {
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "handleTunnelOut", Long.class, Short.class, Short.class, String.class, Long.class, String.class, boolean.class));
-
- Whitebox.invokeMethod(of13Provider, "programRemoteEgressTunnelBridgeRules", mock(Node.class), Long.valueOf("45"), SEG_ID, MAC_ADDRESS, LOCAL_PORT, LOCAL_PORT);
-
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("handleTunnelOut", anyLong(), anyShort(), anyShort(), anyString(), anyLong(), anyString(), anyBoolean());
- }
-
- @Test
- public void testRemovePerTunnelRules() throws Exception {
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "handleTunnelIn", Long.class, Short.class, Short.class, String.class, Long.class, boolean.class));
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "handleTunnelFloodOut", Long.class, Short.class, Short.class, String.class, Long.class, boolean.class));
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "handleTunnelUnknownUcastFloodOut", Long.class, Short.class, Short.class, String.class, Long.class, boolean.class));
-
- Whitebox.invokeMethod(of13Provider, "removePerTunnelRules", mock(Node.class), Long.valueOf("45"), SEG_ID, LOCAL_PORT);
-
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("handleTunnelIn", anyLong(), anyShort(), anyShort(), anyString(), anyLong(), anyBoolean());
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("handleTunnelFloodOut", anyLong(), anyShort(), anyShort(), anyString(), anyLong(), anyBoolean());
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("handleTunnelUnknownUcastFloodOut", anyLong(), anyShort(), anyShort(), anyString(), anyLong(), anyBoolean());
- }
-
- @Test
- public void testProgramLocalVlanRules() throws Exception {
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "handleLocalInPortSetVlan", Long.class, Short.class, Short.class, String.class, Long.class, String.class, boolean.class));
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "handleDropSrcIface", Long.class, Long.class, boolean.class));
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "handleLocalVlanUcastOut", Long.class, Short.class, String.class, Long.class, String.class, boolean.class));
-
- Whitebox.invokeMethod(of13Provider, "programLocalVlanRules", mock(Node.class), Long.valueOf("45"), SEG_ID, MAC_ADDRESS, LOCAL_PORT);
-
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("handleLocalInPortSetVlan", anyLong(), anyShort(), anyShort(), anyString(), anyLong(), anyString(), anyBoolean());
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("handleDropSrcIface", anyLong(), anyLong(), anyBoolean());
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("handleLocalVlanUcastOut", anyLong(), anyShort(), anyString(), anyLong(), anyString(), anyBoolean());
- }
-
- @Test
- public void testRemoveLocalVlanRules() throws Exception {
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "handleLocalInPortSetVlan", Long.class, Short.class, Short.class, String.class, Long.class, String.class, boolean.class));
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "handleDropSrcIface", Long.class, Long.class, boolean.class));
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "handleLocalVlanUcastOut", Long.class, Short.class, String.class, Long.class, String.class, boolean.class));
-
- Whitebox.invokeMethod(of13Provider, "programLocalVlanRules", mock(Node.class), Long.valueOf("45"), SEG_ID, MAC_ADDRESS, LOCAL_PORT);
-
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("handleLocalInPortSetVlan", anyLong(), anyShort(), anyShort(), anyString(), anyLong(), anyString(), anyBoolean());
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("handleDropSrcIface", anyLong(), anyLong(), anyBoolean());
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("handleLocalVlanUcastOut", anyLong(), anyShort(), anyString(), anyLong(), anyString(), anyBoolean());
- }
-
-
- @Test
- public void testProgramLocalIngressVlanRules() throws Exception {
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "handleVlanIn", Long.class, Short.class, Short.class, String.class, Long.class, boolean.class));
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "handleLocalVlanBcastOut", Long.class, Short.class, String.class, Long.class, Long.class, boolean.class));
-
- Whitebox.invokeMethod(of13Provider, "programLocalIngressVlanRules", mock(Node.class), Long.valueOf("45"), SEG_ID, MAC_ADDRESS, LOCAL_PORT, LOCAL_PORT);
-
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("handleVlanIn", anyLong(), anyShort(), anyShort(), anyString(), anyLong(), anyBoolean());
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("handleLocalVlanBcastOut", anyLong(), anyShort(), anyString(), anyLong(), anyLong(), anyBoolean());
- }
-
- @Test
- public void testProgramRemoteEgressVlanRules() throws Exception {
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "handleVlanMiss", Long.class, Short.class, Short.class, String.class, Long.class, boolean.class));
-
- Whitebox.invokeMethod(of13Provider, "programRemoteEgressVlanRules", mock(Node.class), Long.valueOf("45"), SEG_ID, MAC_ADDRESS, LOCAL_PORT);
-
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("handleVlanMiss", anyLong(), anyShort(), anyShort(), anyString(), anyLong(), anyBoolean());
- }
-
- @Test
- public void testRemoveRemoteEgressVlanRules() throws Exception {
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "handleLocalVlanBcastOut", Long.class, Short.class, String.class, Long.class, Long.class, boolean.class));
-
- Whitebox.invokeMethod(of13Provider, "removeRemoteEgressVlanRules", mock(Node.class), Long.valueOf("45"), SEG_ID, MAC_ADDRESS, LOCAL_PORT, LOCAL_PORT);
-
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("handleLocalVlanBcastOut", anyLong(), anyShort(), anyString(), anyLong(), anyLong(), anyBoolean());
- }
-
- @Test
- public void testRemovePerVlanRules() throws Exception {
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "handleVlanIn", Long.class, Short.class, Short.class, String.class, Long.class, boolean.class));
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "handleVlanMiss", Long.class, Short.class, Short.class, String.class, Long.class, boolean.class));
-
- Whitebox.invokeMethod(of13Provider, "removePerVlanRules", mock(Node.class), Long.valueOf("45"), SEG_ID, LOCAL_PORT, LOCAL_PORT);
-
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("handleVlanIn", anyLong(), anyShort(), anyShort(), anyString(), anyLong(), anyBoolean());
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("handleVlanMiss", anyLong(), anyShort(), anyShort(), anyString(), anyLong(), anyBoolean());
- }
-
- @Test
- public void testHandleInterfaceUpdate() throws Exception{
- NeutronNetwork neutronNetwork = mock(NeutronNetwork.class);
- when(neutronNetwork.getProviderNetworkType()).thenReturn(NetworkHandler.NETWORK_TYPE_VLAN, NetworkHandler.NETWORK_TYPE_GRE);
- NodeCacheManager nodeCacheManager = mock(NodeCacheManager.class);
- Map<NodeId, Node> nodes = new HashMap<>();
- nodes.put(mock(NodeId.class), mock(Node.class));
- when(nodeCacheManager.getOvsdbNodes()).thenReturn(nodes);
- Southbound southbound = mock(Southbound.class);
- when(southbound.extractBridgeOvsdbNodeId(any(Node.class))).thenReturn(mock(NodeId.class));
- when(southbound.getBridgeNode(any(Node.class), anyString())).thenReturn(mock(Node.class));
- ConfigurationService configurationService = mock(ConfigurationService.class);
- when(configurationService.getIntegrationBridgeName()).thenReturn(BR_INT);
-
- MemberModifier.field(OF13Provider.class, "nodeCacheManager").set(of13Provider , nodeCacheManager);
- MemberModifier.field(OF13Provider.class, "southbound").set(of13Provider , southbound);
- MemberModifier.field(OF13Provider.class, "configurationService").set(of13Provider , configurationService);
-
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "programLocalRules", String.class, String.class, Node.class, OvsdbTerminationPointAugmentation.class));
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "programVlanRules", NeutronNetwork.class, Node.class, OvsdbTerminationPointAugmentation.class));
-
- TenantNetworkManager tenantNetworkManager = mock(TenantNetworkManager.class);
- MemberModifier.field(OF13Provider.class, "tenantNetworkManager").set(of13Provider, tenantNetworkManager);
- when(tenantNetworkManager.isTenantNetworkPresentInNode(any(Node.class), eq(ID))).thenReturn(true);
-
- assertTrue("Error, did not update the interface correclty", of13Provider.handleInterfaceUpdate(neutronNetwork, mock(Node.class), mock(OvsdbTerminationPointAugmentation.class)));
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("programLocalRules", anyString(), anyString(), any(Node.class), any(OvsdbTerminationPointAugmentation.class));
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("programVlanRules", any(NeutronNetwork.class), any(Node.class), any(OvsdbTerminationPointAugmentation.class));
-
- when(configurationService.getTunnelEndPoint(any(Node.class))).thenReturn(mock(InetAddress.class));
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "addTunnelPort", Node.class, String.class, InetAddress.class, InetAddress.class));
- PowerMockito.when(of13Provider, "addTunnelPort", any(Node.class), anyString(), any(InetAddress.class), any(InetAddress.class)).thenReturn(true);
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "programTunnelRules", String.class, String.class, InetAddress.class, Node.class, OvsdbTerminationPointAugmentation.class, boolean.class));
-
- assertTrue("Error, did not update the interface correclty", of13Provider.handleInterfaceUpdate(neutronNetwork, mock(Node.class), mock(OvsdbTerminationPointAugmentation.class)));
- PowerMockito.verifyPrivate(of13Provider, times(2)).invoke("addTunnelPort", any(Node.class), anyString(), any(InetAddress.class), any(InetAddress.class));
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("programTunnelRules", anyString(), anyString(), any(InetAddress.class), any(Node.class), any(OvsdbTerminationPointAugmentation.class), anyBoolean());
- }
-
- private static final String INTF = "interface";
-
- @SuppressWarnings("unchecked")
- @Test
- public void testHandlerInterfaceDelete() throws Exception {
- NeutronNetwork neutronNetwork = mock(NeutronNetwork.class);
- NodeCacheManager nodeCacheManager = mock(NodeCacheManager.class);
- NodeId nodeId = mock(NodeId.class);
- when(nodeId.getValue()).thenReturn(ID);
- Node node = mock(Node.class);
- when(node.getNodeId()).thenReturn(nodeId);
- Map<NodeId, Node> nodes = new HashMap<>();
- nodes.put(mock(NodeId.class), node);
- when(nodeCacheManager.getOvsdbNodes()).thenReturn(nodes);
- Southbound southbound = mock(Southbound.class);
- when(southbound.extractBridgeOvsdbNodeId(any(Node.class))).thenReturn(mock(NodeId.class));
- when(southbound.isTunnel(any(OvsdbTerminationPointAugmentation.class))).thenReturn(true);
- when(southbound.getOptionsValue(any(List.class), anyString())).thenReturn(IP);
- OvsdbTerminationPointAugmentation intf = mock(OvsdbTerminationPointAugmentation.class);
- when(intf.getName()).thenReturn(INTF);
- List<String> intfs = new ArrayList<>();
- intfs.add(INTF);
- BridgeConfigurationManager bridgeConfigurationManager = mock(BridgeConfigurationManager.class);
- when(bridgeConfigurationManager.getAllPhysicalInterfaceNames(any(Node.class))).thenReturn(intfs);
- ConfigurationService configurationService = mock(ConfigurationService.class);
- when(configurationService.getTunnelEndPoint(any(Node.class))).thenReturn(mock(InetAddress.class));
-
- PowerMockito.mockStatic(InetAddress.class);
- PowerMockito.when(InetAddress.getByName(anyString())).thenReturn(mock(InetAddress.class));
-
- PowerMockito.mockStatic(MdsalHelper.class);
- PowerMockito.when(MdsalHelper.createOvsdbInterfaceType(any(Class.class))).thenReturn(INTF);
-
- MemberModifier.field(OF13Provider.class, "nodeCacheManager").set(of13Provider , nodeCacheManager);
- MemberModifier.field(OF13Provider.class, "southbound").set(of13Provider , southbound);
- MemberModifier.field(OF13Provider.class, "bridgeConfigurationManager").set(of13Provider , bridgeConfigurationManager);
- MemberModifier.field(OF13Provider.class, "configurationService").set(of13Provider , configurationService);
-
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "deleteTunnelPort", Node.class, String.class, InetAddress.class, InetAddress.class));
-
- assertTrue("Error, did not delete the interface correclty", of13Provider.handleInterfaceDelete(TYPE, neutronNetwork, mock(Node.class), intf, false, false));
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("deleteTunnelPort", any(Node.class), anyString(), any(InetAddress.class), any(InetAddress.class));
-
- when(southbound.isTunnel(any(OvsdbTerminationPointAugmentation.class))).thenReturn(false);
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "deletePhysicalPort", Node.class, String.class));
-
- assertTrue("Error, did not delete the interface correclty", of13Provider.handleInterfaceDelete(TYPE, neutronNetwork, mock(Node.class), intf, false, false));
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("deletePhysicalPort", any(Node.class), anyString());
-
- intfs.clear();
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "removeLocalRules", String.class, String.class, Node.class, OvsdbTerminationPointAugmentation.class, boolean.class));
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "removeVlanRules", NeutronNetwork.class, Node.class, OvsdbTerminationPointAugmentation.class, boolean.class));
- when(neutronNetwork.getProviderNetworkType()).thenReturn(NetworkHandler.NETWORK_TYPE_VLAN);
-
- assertTrue("Error, did not delete the interface correclty", of13Provider.handleInterfaceDelete(TYPE, neutronNetwork, mock(Node.class), intf, false, false));
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("removeLocalRules", anyString(), anyString(), any(Node.class), any(OvsdbTerminationPointAugmentation.class), any(boolean.class));
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("removeVlanRules", any(NeutronNetwork.class), any(Node.class), any(OvsdbTerminationPointAugmentation.class), anyBoolean());
-
- TenantNetworkManager tenantNetworkManager = mock(TenantNetworkManager.class);
- MemberModifier.field(OF13Provider.class, "tenantNetworkManager").set(of13Provider, tenantNetworkManager);
- when(tenantNetworkManager.isTenantNetworkPresentInNode(any(Node.class), eq(ID))).thenReturn(true);
-
- when(neutronNetwork.getProviderNetworkType()).thenReturn(NetworkHandler.NETWORK_TYPE_GRE);
- when(southbound.getBridgeNode(any(Node.class), anyString())).thenReturn(node);
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "removeTunnelRules", String.class, String.class, InetAddress.class, Node.class, OvsdbTerminationPointAugmentation.class, boolean.class, boolean.class, boolean.class));
-
- assertTrue("Error, did not delete the interface correclty", of13Provider.handleInterfaceDelete(TYPE, neutronNetwork, node, intf, false, false));
- PowerMockito.verifyPrivate(of13Provider, times(3)).invoke("removeTunnelRules", anyString(), anyString(), any(InetAddress.class), any(Node.class), any(OvsdbTerminationPointAugmentation.class), any(boolean.class), any(boolean.class), any(boolean.class));
- }
-
- // Problem with methods signatures: initializeFlowRules(Node) has the same signature than initializeFlowRules(Node, String)
-// @Test
-// public void testInitializeFlowRules() throws Exception {
-// MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "initializeFlowRules", Node.class, String.class));
-// MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "triggerInterfaceUpdates", Node.class));
-//
-// of13Provider.initializeFlowRules(mock(Node.class));
-//
-// PowerMockito.verifyPrivate(of13Provider, times(2)).invoke("initializeFlowRules", any(Node.class), anyString());
-// PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("triggerInterfaceUpdates", any(Node.class));
-// }
-
- @Test
- public void testInitializeOFFlowRule() throws Exception{
- Southbound southbound = mock(Southbound.class);
- when(southbound.getBridgeName(any(Node.class))).thenReturn(BR_INT);
- ConfigurationService configurationService = mock(ConfigurationService.class);
- when(configurationService.getIntegrationBridgeName()).thenReturn(BR_INT);
-
- MemberModifier.field(OF13Provider.class, "southbound").set(of13Provider , southbound);
- MemberModifier.field(OF13Provider.class, "configurationService").set(of13Provider , configurationService);
-
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "initializeFlowRules", Node.class, String.class));
- MemberModifier.suppress(MemberMatcher.method(OF13Provider.class, "triggerInterfaceUpdates", Node.class));
-
- of13Provider.initializeOFFlowRules(mock(Node.class));
-
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("initializeFlowRules", any(Node.class), anyString());
- PowerMockito.verifyPrivate(of13Provider, times(1)).invoke("triggerInterfaceUpdates", any(Node.class));
- }
-
- @Test
- public void testSetDependencies() throws Exception {
- ConfigurationService configurationService = mock(ConfigurationService.class);
- TenantNetworkManager tenantNetworkManager = mock(TenantNetworkManager.class);
- BridgeConfigurationManager bridgeConfigurationManager = mock(BridgeConfigurationManager.class);
- NodeCacheManager nodeCacheManager = mock(NodeCacheManager.class);
- ClassifierProvider classifierProvider = mock(ClassifierProvider.class);
- IngressAclProvider ingressAclProvider = mock(IngressAclProvider.class);
- EgressAclProvider egressAclProvider = mock(EgressAclProvider.class);
- L2ForwardingProvider l2ForwardingProvider = mock(L2ForwardingProvider.class);
- SecurityServicesManager securityServicesManager = mock(SecurityServicesManager.class);
- Southbound southbound = mock(Southbound.class);
-
- ServiceHelper.overrideGlobalInstance(ConfigurationService.class, configurationService);
- ServiceHelper.overrideGlobalInstance(TenantNetworkManager.class, tenantNetworkManager);
- ServiceHelper.overrideGlobalInstance(BridgeConfigurationManager.class, bridgeConfigurationManager);
- ServiceHelper.overrideGlobalInstance(NodeCacheManager.class, nodeCacheManager);
- ServiceHelper.overrideGlobalInstance(ClassifierProvider.class, classifierProvider);
- ServiceHelper.overrideGlobalInstance(IngressAclProvider.class, ingressAclProvider);
- ServiceHelper.overrideGlobalInstance(EgressAclProvider.class, egressAclProvider);
- ServiceHelper.overrideGlobalInstance(L2ForwardingProvider.class, l2ForwardingProvider);
- ServiceHelper.overrideGlobalInstance(SecurityServicesManager.class, securityServicesManager);
- ServiceHelper.overrideGlobalInstance(Southbound.class, southbound);
-
- of13Provider.setDependencies(mock(BundleContext.class), mock(ServiceReference.class));
-
- assertEquals("Error, did not return the correct object", getField("configurationService"), configurationService);
- assertEquals("Error, did not return the correct object", getField("tenantNetworkManager"), tenantNetworkManager);
- assertEquals("Error, did not return the correct object", getField("bridgeConfigurationManager"), bridgeConfigurationManager);
- assertEquals("Error, did not return the correct object", getField("nodeCacheManager"), nodeCacheManager);
- assertEquals("Error, did not return the correct object", getField("classifierProvider"), classifierProvider);
- assertEquals("Error, did not return the correct object", getField("ingressAclProvider"), ingressAclProvider);
- assertEquals("Error, did not return the correct object", getField("egressAclProvider"), egressAclProvider);
- assertEquals("Error, did not return the correct object", getField("l2ForwardingProvider"), l2ForwardingProvider);
- assertEquals("Error, did not return the correct object", getField("securityServicesManager"), securityServicesManager);
- assertEquals("Error, did not return the correct object", getField("southbound"), southbound);
- }
-
- @SuppressWarnings("unchecked")
- @Test
- public void testSetDependenciesObject() throws Exception{
- NetworkingProviderManager networkingProviderManager = mock(NetworkingProviderManager.class);
- BundleContext bundleContext = mock(BundleContext.class);
- when(bundleContext.getServiceReference(NetworkingProvider.class.getName())).thenReturn(mock(ServiceReference.class));
-
- MemberModifier.field(OF13Provider.class, "bundleContext").set(of13Provider, bundleContext);
-
- of13Provider.setDependencies(networkingProviderManager);
- verify(networkingProviderManager).providerAdded(any(ServiceReference.class), same(of13Provider));
- }
-
- private Object getField(String fieldName) throws Exception {
- Field field = OF13Provider.class.getDeclaredField(fieldName);
- field.setAccessible(true);
- return field.get(of13Provider);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2016 Inocybe Technologies. 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.netvirt.openstack.netvirt.providers.openflow13;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-import java.lang.reflect.Field;
-import java.util.concurrent.ExecutorService;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.openstack.netvirt.providers.NetvirtProvidersProvider;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-
-/**
- * Unit test for {@link PipelineOrchestratorImplTest}
- */
-@RunWith(MockitoJUnitRunner.class)
-public class PipelineOrchestratorImplTest {
- @InjectMocks private PipelineOrchestratorImpl orchestrator;
-
- @Mock private ExecutorService eventHandler;
- @Mock private Southbound southbound;
-
- /**
- * Test for method {@link PipelineOrchestratorImpl#getTableOffset()}
- */
- @Test
- public void testGetTableOffset() {
- short tableOffset = 0;
- NetvirtProvidersProvider.setTableOffset(tableOffset);
- assertEquals("tableOffset was not set", tableOffset, orchestrator.getTableOffset());
- }
-
- /**
- * Test for {@link PipelineOrchestratorImpl#getTable(Service)}
- */
- @Test
- public void testGetTableOffsetWithService() {
- short tableOffset = 0;
- NetvirtProvidersProvider.setTableOffset(tableOffset);
- assertEquals("tableOffset was not set", Service.CLASSIFIER.getTable(),
- orchestrator.getTable(Service.CLASSIFIER));
- }
-
- /***
- * Registers a mock service and verifies the registration by asking the
- * pipeline orchestrator to return the associated service from its internal
- * registry
- */
- @Test
- public void testRegisterAndUnregisterService() {
- Service service = Service.CLASSIFIER;
- ServiceReference<?> serviceReference = mock(ServiceReference.class);
- when(serviceReference.getProperty(anyString())).thenReturn(service);
-
- AbstractServiceInstance abstractServiceInstance = mock(AbstractServiceInstance.class);
-
- orchestrator.registerService(serviceReference, abstractServiceInstance);
- assertEquals("Error, registerService() service registration fails",
- abstractServiceInstance,
- orchestrator.getServiceInstance(service));
-
- orchestrator.unregisterService(serviceReference);
- assertNull("Error, unregisterService() didn't delete the service", orchestrator.getServiceInstance(service));
- }
-
- /**
- * Test method
- * {@link PipelineOrchestratorImpl#getNextServiceInPipeline(Service)}
- */
- @Test
- public void testGetNextServiceInPipeline() {
-
- assertEquals(orchestrator.getNextServiceInPipeline(Service.CLASSIFIER),
- Service.ARP_RESPONDER);
- assertEquals(
- orchestrator.getNextServiceInPipeline(Service.ARP_RESPONDER),
- Service.INBOUND_NAT);
- assertEquals(
- orchestrator.getNextServiceInPipeline(Service.INBOUND_NAT),
- Service.RESUBMIT_ACL_SERVICE);
- assertEquals(
- orchestrator.getNextServiceInPipeline(Service.RESUBMIT_ACL_SERVICE),
- Service.ACL_LEARN_SERVICE);
- assertEquals(
- orchestrator.getNextServiceInPipeline(Service.ACL_LEARN_SERVICE),
- Service.EGRESS_ACL);
- assertEquals(orchestrator.getNextServiceInPipeline(Service.EGRESS_ACL),
- Service.LOAD_BALANCER);
- assertEquals(
- orchestrator.getNextServiceInPipeline(Service.LOAD_BALANCER),
- Service.ROUTING);
- assertEquals(orchestrator.getNextServiceInPipeline(Service.ROUTING),
- Service.L3_FORWARDING);
- assertEquals(
- orchestrator.getNextServiceInPipeline(Service.L3_FORWARDING),
- Service.L2_REWRITE);
- assertEquals(orchestrator.getNextServiceInPipeline(Service.L2_REWRITE),
- Service.INGRESS_ACL);
- assertEquals(
- orchestrator.getNextServiceInPipeline(Service.INGRESS_ACL),
- Service.OUTBOUND_NAT);
- assertEquals(
- orchestrator.getNextServiceInPipeline(Service.OUTBOUND_NAT),
- Service.L2_LEARN);
- assertEquals(
- orchestrator.getNextServiceInPipeline(Service.L2_LEARN),
- Service.L2_FORWARDING);
- assertNull(orchestrator.getNextServiceInPipeline(Service.L2_FORWARDING));
- }
-
- @Test
- public void testSetDependencies() throws Exception {
- NodeCacheManager nodeCacheManager = mock(NodeCacheManager.class);
- Southbound southbound = mock(Southbound.class);
-
- ServiceHelper.overrideGlobalInstance(NodeCacheManager.class, nodeCacheManager);
- ServiceHelper.overrideGlobalInstance(Southbound.class, southbound);
-
- orchestrator.setDependencies(mock(BundleContext.class), mock(ServiceReference.class));
-
-// assertEquals("Error, did not return the correct object", getField("nodeCacheManager"), nodeCacheManager);
- assertEquals("Error, did not return the correct object", getField("southbound"), southbound);
- }
-
- private Object getField(String fieldName) throws Exception {
- Field field = PipelineOrchestratorImpl.class.getDeclaredField(fieldName);
- field.setAccessible(true);
- return field.get(orchestrator);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt.providers.openflow13;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-
-import org.junit.Before;
-import org.junit.Test;
-
-public class PipelineOrchestratorTest {
- PipelineOrchestrator orchestrator;
- @Before
- public void initialize() {
- orchestrator = new PipelineOrchestratorImpl();
- }
-
- @Test
- public void testPipeline() {
- assertEquals(orchestrator.getNextServiceInPipeline(Service.CLASSIFIER), Service.ARP_RESPONDER);
- assertEquals(orchestrator.getNextServiceInPipeline(Service.ARP_RESPONDER), Service.INBOUND_NAT);
- assertEquals(orchestrator.getNextServiceInPipeline(Service.INBOUND_NAT), Service.RESUBMIT_ACL_SERVICE);
- assertEquals(orchestrator.getNextServiceInPipeline(Service.RESUBMIT_ACL_SERVICE), Service.ACL_LEARN_SERVICE);
- assertEquals(orchestrator.getNextServiceInPipeline(Service.ACL_LEARN_SERVICE), Service.EGRESS_ACL);
- assertEquals(orchestrator.getNextServiceInPipeline(Service.EGRESS_ACL), Service.LOAD_BALANCER);
- assertEquals(orchestrator.getNextServiceInPipeline(Service.LOAD_BALANCER), Service.ROUTING);
- assertEquals(orchestrator.getNextServiceInPipeline(Service.ROUTING), Service.L3_FORWARDING);
- assertEquals(orchestrator.getNextServiceInPipeline(Service.L3_FORWARDING), Service.L2_REWRITE);
- assertEquals(orchestrator.getNextServiceInPipeline(Service.L2_REWRITE), Service.INGRESS_ACL);
- assertEquals(orchestrator.getNextServiceInPipeline(Service.INGRESS_ACL), Service.OUTBOUND_NAT);
- assertEquals(orchestrator.getNextServiceInPipeline(Service.OUTBOUND_NAT), Service.L2_LEARN);
- assertEquals(orchestrator.getNextServiceInPipeline(Service.L2_LEARN), Service.L2_FORWARDING);
- assertNull(orchestrator.getNextServiceInPipeline(Service.L2_FORWARDING));
- }
-}
+++ /dev/null
-/*
- * Copyright © 2015, 2017 Inocybe 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.netvirt.openstack.netvirt.providers.openflow13.services;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyBoolean;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import java.net.InetAddress;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.Status;
-import org.opendaylight.netvirt.openstack.netvirt.api.StatusCode;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-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.inventory.rev130819.nodes.Node;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-
-import com.google.common.util.concurrent.CheckedFuture;
-
-
-/**
- * Unit test for {@link ArpResponderService}
- */
-@RunWith(MockitoJUnitRunner.class)
-@SuppressWarnings("unchecked")
-public class ArpResponderServiceTest {
-
- @InjectMocks private ArpResponderService arpResponderService = new ArpResponderService();
-
- @Mock private DataBroker dataBroker;
-
- private static final String HOST_ADDRESS = "121.0.0.1";
- private static final String MAC_ADDRESS = "87:1D:5E:02:40:B7";
-
- @Test
- public void testProgramStaticArpEntry() throws Exception {
- arpResponderService.setService(Service.ARP_RESPONDER);
-
- InetAddress ipAddress = mock(InetAddress.class);
- when(ipAddress.getHostAddress()).thenReturn(HOST_ADDRESS);
-
- WriteTransaction transaction = mock(WriteTransaction.class);
- when(dataBroker.newWriteOnlyTransaction()).thenReturn(transaction);
- CheckedFuture<Void, TransactionCommitFailedException> commitFuture = mock(CheckedFuture.class);
- when(transaction.submit()).thenReturn(commitFuture);
-
- NodeBuilder nodeBuilder = mock(NodeBuilder.class);
- when(nodeBuilder.getKey()).thenReturn(mock(NodeKey.class));
-
- FlowBuilder flowBuilder = mock(FlowBuilder.class);
- when(flowBuilder.getKey()).thenReturn(mock(FlowKey.class));
-
- // test Action.ADD
- assertEquals("Error, did not return the expected StatusCode", new Status(StatusCode.SUCCESS), arpResponderService.programStaticArpEntry(12L, "2", MAC_ADDRESS, ipAddress, Action.ADD));
-
- verify(transaction, times(2)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class), anyBoolean());
- verify(transaction, times(1)).submit();
- verify(commitFuture, times(1)).get();
-
- // test Action.DELETE
- assertEquals("Error, did not return the expected StatusCode", new Status(StatusCode.SUCCESS), arpResponderService.programStaticArpEntry(12L, "2", MAC_ADDRESS, ipAddress, Action.DELETE));
-
- verify(transaction, times(1)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(commitFuture, times(2)).get(); // 1 + 1 above
- }
-}
+++ /dev/null
-/*
- * Copyright © 2015, 2017 Inocybe 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.netvirt.openstack.netvirt.providers.openflow13.services;
-
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyBoolean;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.PipelineOrchestrator;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-
-import com.google.common.util.concurrent.CheckedFuture;
-
-/**
- * Unit test for {@link ClassifierService}
- */
-@RunWith(MockitoJUnitRunner.class)
-@SuppressWarnings("unchecked")
-public class ClassifierServiceTest {
-
- @InjectMocks private ClassifierService classifierService = new ClassifierService(Service.ARP_RESPONDER);
-
- @Mock private DataBroker dataBroker;
-
- private static final String MAC_ADDRESS = "87:1D:5E:02:40:B7";
-
- @Mock private PipelineOrchestrator orchestrator;
-
- @Mock private WriteTransaction writeTransaction;
- @Mock private CheckedFuture<Void, TransactionCommitFailedException> commitFuture;
-
- @Before
- public void setUp() {
- when(writeTransaction.submit()).thenReturn(commitFuture);
- when(writeTransaction.submit()).thenReturn(commitFuture);
-
- when(dataBroker.newWriteOnlyTransaction()).thenReturn(writeTransaction);
-
- when(orchestrator.getNextServiceInPipeline(any(Service.class))).thenReturn(Service.ARP_RESPONDER);
- }
-
- /**
- * Test method {@link ClassifierService#programLocalInPort(Long, String, Long, String, boolean)}
- */
- @Test
- public void testProgramLocalInPort() throws Exception {
- // write
- classifierService.programLocalInPort(1212L, "2", 455L, MAC_ADDRESS, true);
- verify(writeTransaction, times(2)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class), anyBoolean());
- verify(writeTransaction, times(1)).submit();
- verify(commitFuture, times(1)).get();
-
- // remove
- classifierService.programLocalInPort(1212L, "2", 455L, MAC_ADDRESS, false);
- verify(writeTransaction, times(1)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(commitFuture, times(2)).get(); // 1 + 1 above
- }
-
- /**
- * Test method {@link ClassifierService#programLocalInPortSetVlan(Long, String, Long, String, boolean)}
- */
- @Test
- public void testProgramLocalInPortSetVlan() throws Exception {
- // write
- classifierService.programLocalInPortSetVlan(1212L, "2", 455L, MAC_ADDRESS, true);
- verify(writeTransaction, times(2)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class), anyBoolean());
- verify(writeTransaction, times(1)).submit();
- verify(commitFuture, times(1)).get();
-
- // remove
- classifierService.programLocalInPortSetVlan(1212L, "2", 455L, MAC_ADDRESS, false);
- verify(writeTransaction, times(1)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(commitFuture, times(2)).get(); // 1 + 1 above
- }
-
- /**
- * Test method {@link ClassifierService#programDropSrcIface(Long, Long, boolean)}
- */
- @Test
- public void testProgramDropSrcIface() throws Exception {
- // write
- classifierService.programDropSrcIface(1212L, 455L, true);
- verify(writeTransaction, times(2)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class), anyBoolean());
- verify(writeTransaction, times(1)).submit();
- verify(commitFuture, times(1)).get();
-
- // remove
- classifierService.programDropSrcIface(1212L, 455L, false);
- verify(writeTransaction, times(1)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(commitFuture, times(2)).get(); // 1 + 1 above
- }
-
- /**
- * Test method {@link ClassifierService#programTunnelIn(Long, String, Long, boolean)}
- */
- @Test
- public void testProgramTunnelIn() throws Exception {
- // write
- classifierService.programTunnelIn(1212L, "2", 455L, true);
- verify(writeTransaction, times(2)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class), anyBoolean());
- verify(writeTransaction, times(1)).submit();
- verify(commitFuture, times(1)).get();
-
- // remove
- classifierService.programTunnelIn(1212L, "2", 455L, false);
- verify(writeTransaction, times(1)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(commitFuture, times(2)).get(); // 1 + 1 above
- }
-
- /**
- * Test method {@link ClassifierService#programVlanIn(Long, String, Long, boolean)}
- */
- @Test
- public void testProgramVlanIn() throws Exception {
- // write
- classifierService.programVlanIn(1212L, "2", 455L, true);
- verify(writeTransaction, times(2)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class), anyBoolean());
- verify(writeTransaction, times(1)).submit();
- verify(commitFuture, times(1)).get();
-
- // remove
- classifierService.programVlanIn(1212L, "2", 455L, false);
- verify(writeTransaction, times(1)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(commitFuture, times(2)).get(); // 1 + 1 above
- }
-
- /**
- * Test method {@link ClassifierService#programLLDPPuntRule(Long)}
- */
- @Test
- public void testProgramLLDPPuntRule() throws Exception {
- // write
- classifierService.programLLDPPuntRule(1212L);
- verify(writeTransaction, times(2)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class), anyBoolean());
- verify(writeTransaction, times(1)).submit();
- verify(commitFuture, times(1)).get();
- }
-}
+++ /dev/null
-/*
- * Copyright © 2015, 2017 Inocybe 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.netvirt.openstack.netvirt.providers.openflow13.services;
-
-import static org.mockito.Matchers.any;
-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.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.stubbing.Answer;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
-import org.opendaylight.netvirt.openstack.netvirt.providers.NetvirtProvidersProvider;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityGroup;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityRule;
-import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs;
-import org.opendaylight.netvirt.openstack.netvirt.api.SecurityGroupCacheManger;
-import org.opendaylight.netvirt.openstack.netvirt.api.SecurityServicesManager;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.PipelineOrchestrator;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSecurityRuleCRUD;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.Match;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.EthernetMatch;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.Icmpv4Match;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.Icmpv6Match;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._4.match.TcpMatch;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._4.match.UdpMatch;
-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.NodeId;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.powermock.api.mockito.PowerMockito;
-import org.powermock.api.support.membermodification.MemberModifier;
-import org.powermock.modules.junit4.PowerMockRunner;
-
-import com.google.common.util.concurrent.CheckedFuture;
-/**
- * Unit test for {@link EgressAclService}
- */
-@RunWith(PowerMockRunner.class)
-@SuppressWarnings("unchecked")
-public class EgressAclServiceTest {
-
- @InjectMocks private EgressAclService egressAclService = new EgressAclService();
- private EgressAclService egressAclServiceSpy;
-
- @Mock private DataBroker dataBroker;
- @Mock private PipelineOrchestrator orchestrator;
-
- @Mock private WriteTransaction writeTransaction;
- @Mock private CheckedFuture<Void, TransactionCommitFailedException> commitFuture;
-
- @Mock private NeutronSecurityGroup securityGroup;
- @Mock private NeutronSecurityRule portSecurityRule;
- @Mock private NeutronSecurityGroup securityGroupIpv6;
- @Mock private NeutronSecurityRule portSecurityIpv6Rule;
- @Mock private INeutronSecurityRuleCRUD neutronSecurityRuleCache;
-
- @Mock private SecurityServicesManager securityServices;
- @Mock private SecurityGroupCacheManger securityGroupCacheManger;
- @Mock private NodeId nodeId;
-
- private Neutron_IPs neutron_ip_src;
- private Neutron_IPs neutron_ip_dest_1;
- private Neutron_IPs neutron_ip_dest_2;
- private Neutron_IPs neutron_ipv6_dest_1;
- private Neutron_IPs neutron_ipv6_dest_2;
- private List<Neutron_IPs> neutronSrcIpList = new ArrayList<>();
- private List<Neutron_IPs> neutronDestIpList = new ArrayList<>();
- private static final String MAC_ADDRESS = "87:1D:5E:02:40:B7";
- private static final String SRC_IP = "192.168.0.1";
- private static final String DEST_IP_1 = "192.169.0.1";
- private static final String DEST_IP_2 = "192.169.0.2";
- private static final String IPV6_DEST_IP_1 = "2001:db8:2::200";
- private static final String IPV6_DEST_IP_2 = "2001:db8:2::201";
- private static final String SECURITY_GROUP_UUID = "85cc3048-abc3-43cc-89b3-377341426ac5";
- private static final String PORT_UUID = "95cc3048-abc3-43cc-89b3-377341426ac5";
- private static final Long IPV6_ETHER_TYPE = (long) 0x86DD;
- private static final Long IPV4_ETHER_TYPE = (long) 0x0800;
- private static final String SEGMENT_ID = "2";
- private static final Long DP_ID_LONG = (long) 1554;
- private static final Long LOCAL_PORT = (long) 124;
- private static final int PORT_RANGE_MIN = 1;
- private static final int PORT_RANGE_MAX = 65535;
- private static FlowBuilder flowBuilder;
- private static NodeBuilder nodeBuilder;
-
- private static Answer<Object> answer() {
- return invocation -> {
- flowBuilder = (FlowBuilder) invocation.getArguments()[0];
- nodeBuilder = (NodeBuilder) invocation.getArguments()[1];
- return null;
- };
- }
-
- @Before
- public void setUp() throws IllegalArgumentException, IllegalAccessException {
- egressAclServiceSpy = PowerMockito.spy(egressAclService);
-
- when(writeTransaction.submit()).thenReturn(commitFuture);
-
- when(dataBroker.newWriteOnlyTransaction()).thenReturn(writeTransaction);
-
- when(orchestrator.getNextServiceInPipeline(any(Service.class))).thenReturn(Service.ARP_RESPONDER);
-
- portSecurityRule = mock(NeutronSecurityRule.class);
- portSecurityIpv6Rule = mock(NeutronSecurityRule.class);
-
- when(portSecurityRule.getSecurityRuleEthertype()).thenReturn(NeutronSecurityRule.ETHERTYPE_IPV4);
- when(portSecurityRule.getSecurityRuleDirection()).thenReturn(NeutronSecurityRule.DIRECTION_EGRESS);
- when(portSecurityIpv6Rule.getSecurityRuleEthertype()).thenReturn(NeutronSecurityRule.ETHERTYPE_IPV6);
- when(portSecurityIpv6Rule.getSecurityRuleDirection()).thenReturn(NeutronSecurityRule.DIRECTION_EGRESS);
-
- List<NeutronSecurityRule> portSecurityList = new ArrayList<>();
- portSecurityList.add(portSecurityRule);
-
- neutron_ip_src = new Neutron_IPs();
- neutron_ip_src.setIpAddress(SRC_IP);
- neutronSrcIpList.add(neutron_ip_src);
-
- neutron_ip_dest_1 = new Neutron_IPs();
- neutron_ip_dest_1.setIpAddress(DEST_IP_1);
- neutronDestIpList.add(neutron_ip_dest_1);
-
- neutron_ip_dest_2 = new Neutron_IPs();
- neutron_ip_dest_2.setIpAddress(DEST_IP_2);
- neutronDestIpList.add(neutron_ip_dest_2);
-
- List<NeutronSecurityRule> portSecurityIpv6List = new ArrayList<>();
- portSecurityIpv6List.add(portSecurityIpv6Rule);
- when(neutronSecurityRuleCache.getAllNeutronSecurityRules()).thenReturn(portSecurityIpv6List);
-
- neutron_ipv6_dest_1 = new Neutron_IPs();
- neutron_ipv6_dest_1.setIpAddress(IPV6_DEST_IP_1);
- neutronDestIpList.add(neutron_ipv6_dest_1);
-
- neutron_ipv6_dest_2 = new Neutron_IPs();
- neutron_ipv6_dest_2.setIpAddress(IPV6_DEST_IP_2);
- neutronDestIpList.add(neutron_ipv6_dest_2);
-
- when(neutronSecurityRuleCache.getAllNeutronSecurityRules()).thenReturn(portSecurityList);
- when(securityServices.getVmListForSecurityGroup(PORT_UUID, SECURITY_GROUP_UUID)).thenReturn(neutronDestIpList);
-
- NetvirtProvidersProvider netvirtProvider = mock(NetvirtProvidersProvider.class);
- MemberModifier.field(NetvirtProvidersProvider.class, "hasProviderEntityOwnership").set(netvirtProvider, new AtomicBoolean(true));
-
- }
-
- /**
- * Test method {@link EgressAclService#programPortSecurityGroup(java.lang.Long, java.lang.String,
- * java.lang.String, long, NeutronSecurityGroup,
- * java.lang.String, NodeId, boolean)} when portSecurityRule is incomplete
- */
- @Test
- public void testProgramPortSecurityGroupWithIncompleteRule() throws Exception {
- NeutronSecurityRule portSecurityRule1 = mock(NeutronSecurityRule.class);
- when(portSecurityRule1.getSecurityRuleEthertype()).thenReturn(NeutronSecurityRule.ETHERTYPE_IPV4);
- when(portSecurityRule1.getSecurityRuleDirection()).thenReturn("not_egress"); // other direction
-
- NeutronSecurityRule portSecurityRule2 = mock(NeutronSecurityRule.class);
- when(portSecurityRule2.getSecurityRuleEthertype()).thenReturn(null);
- when(portSecurityRule2.getSecurityRuleDirection()).thenReturn(NeutronSecurityRule.DIRECTION_EGRESS);
-
- NeutronSecurityRule portSecurityRule3 = mock(NeutronSecurityRule.class);
- when(portSecurityRule3.getSecurityRuleEthertype()).thenReturn(NeutronSecurityRule.ETHERTYPE_IPV4);
- when(portSecurityRule3.getSecurityRuleDirection()).thenReturn(null);
-
- NeutronSecurityRule portSecurityRule4 = mock(NeutronSecurityRule.class);
- when(portSecurityRule4.getSecurityRuleEthertype()).thenReturn(null);
- when(portSecurityRule4.getSecurityRuleDirection()).thenReturn(null);
-
- List<NeutronSecurityRule> portSecurityList = new ArrayList<>();
- portSecurityList.add(null);
- portSecurityList.add(portSecurityRule1);
- portSecurityList.add(portSecurityRule2);
- portSecurityList.add(portSecurityRule3);
- portSecurityList.add(portSecurityRule4);
-
- NeutronSecurityGroup localSecurityGroup = mock(NeutronSecurityGroup.class);
- when(neutronSecurityRuleCache.getAllNeutronSecurityRules()).thenReturn(portSecurityList);
-
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT,
- localSecurityGroup, PORT_UUID, nodeId, true);
- }
-
- /**
- * Test IPv4 add test case.
- */
- @Test
- public void testProgramPortSecurityACLRuleAddIpv4() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(null);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(null);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(null);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn(null);
-
- egressAclServiceSpy.programPortSecurityGroup(1554L, "2", MAC_ADDRESS, 124, securityGroup,PORT_UUID, nodeId, true);
-
- verify(writeTransaction, times(1)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class), eq(true));
- verify(writeTransaction, times(1)).submit();
- verify(commitFuture, times(1)).checkedGet();
- }
-
- /**
- * Test IPv6 add test case.
- */
- @Test
- public void testProgramPortSecurityACLRuleAddIpv6() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(null);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(null);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(null);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn(null);
-
- egressAclServiceSpy.programPortSecurityGroup(1554L, "2", MAC_ADDRESS, 124, securityGroupIpv6, PORT_UUID, nodeId, true);
-
- verify(writeTransaction, times(1)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class), eq(true));
- verify(writeTransaction, times(1)).submit();
- verify(commitFuture, times(1)).checkedGet();
- }
-
- /**
- * Test IPv4 remove test case.
- */
- @Test
- public void testProgramPortSecurityACLRuleRemoveIpv4() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(null);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(null);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(null);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn(null);
-
- egressAclServiceSpy.programPortSecurityGroup(1554L, "2", MAC_ADDRESS, 124, securityGroup,PORT_UUID, nodeId, false);
- verify(writeTransaction, times(1)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(writeTransaction, times(1)).submit();
- verify(commitFuture, times(1)).get();
- }
-
- /**
- * Test IPv6 remove test case.
- */
- @Test
- public void testProgramPortSecurityACLRuleRemoveIpv6() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(null);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(null);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(null);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn(null);
-
- egressAclServiceSpy.programPortSecurityGroup(1554L, "2", MAC_ADDRESS, 124, securityGroupIpv6, PORT_UUID, nodeId, false);
- verify(writeTransaction, times(1)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(writeTransaction, times(1)).submit();
- verify(commitFuture, times(1)).get();
- }
-
- /**
- * Test IPv4 TCP add with port no and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleAddTcp1() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_TCP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(20);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(20);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn("0.0.0.0/24");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof TcpMatch);
- TcpMatch layer4Match=(TcpMatch) match.getLayer4Match();
- Assert.assertEquals(20, layer4Match.getTcpDestinationPort().getValue().intValue());
- int port=portSecurityRule.getSecurityRulePortMin();
- Assert.assertEquals("Egress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS +
- "_" + port + "_0.0.0.0/24_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test IPv6 TCP add with port no and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6AddTcp1() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_TCP);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(20);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(20);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn("::/64");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof TcpMatch);
- TcpMatch layer4Match=(TcpMatch) match.getLayer4Match();
- Assert.assertEquals(20, layer4Match.getTcpDestinationPort().getValue().intValue());
- int port=portSecurityIpv6Rule.getSecurityRulePortMin();
- Assert.assertEquals("Egress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS +
- "_" + port + "_::/64_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test IPv4 TCP remove with port no and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleRemoveTcp1() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_TCP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(30);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(30);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn("0.0.0.0/24");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof TcpMatch);
- TcpMatch layer4Match = (TcpMatch) match.getLayer4Match();
- Assert.assertEquals(30, layer4Match.getTcpDestinationPort().getValue().intValue());
- int port=portSecurityRule.getSecurityRulePortMin();
- Assert.assertEquals("Egress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS +
- "_" + port + "_0.0.0.0/24_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test IPv6 TCP remove with port no and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6RemoveTcp1() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_TCP);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(30);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(30);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn("::/64");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof TcpMatch);
- TcpMatch layer4Match = (TcpMatch) match.getLayer4Match();
- Assert.assertEquals(30, layer4Match.getTcpDestinationPort().getValue().intValue());
- int port=portSecurityIpv6Rule.getSecurityRulePortMin();
- Assert.assertEquals("Egress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS +
- "_" + port + "_::/64_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test IPv4 TCP add with port no and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleAddTcp2() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_TCP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(40);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(40);
- when(portSecurityRule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof TcpMatch);
- TcpMatch layer4Match=(TcpMatch) match.getLayer4Match();
- int port=portSecurityRule.getSecurityRulePortMin();
- String expectedFlowId1 = "Egress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + port + "_" + DEST_IP_1 +
- "_Permit";
- String expectedFlowId2 = "Egress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + port + "_" + DEST_IP_2 +
- "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if(actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test IPv6 TCP add with port no and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6AddTcp2() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_TCP);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(40);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(40);
- when(portSecurityIpv6Rule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof TcpMatch);
- TcpMatch layer4Match=(TcpMatch) match.getLayer4Match();
- int port=portSecurityIpv6Rule.getSecurityRulePortMin();
- String expectedFlowId1 = "Egress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + port + "_" + IPV6_DEST_IP_1 +
- "_Permit";
- String expectedFlowId2 = "Egress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + port + "_" + IPV6_DEST_IP_2 +
- "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if(actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test IPv4 TCP remove with port no and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleRemoveTcp2() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_TCP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(50);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(50);
- when(portSecurityRule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof TcpMatch);
- TcpMatch layer4Match=(TcpMatch) match.getLayer4Match();
- int port=portSecurityRule.getSecurityRulePortMin();
- String expectedFlowId1 = "Egress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + port + "_" + DEST_IP_1 +
- "_Permit";
- String expectedFlowId2 = "Egress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + port + "_" + DEST_IP_2 +
- "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if(actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test IPv6 TCP remove with port no and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6RemoveTcp2() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_TCP);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(50);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(50);
- when(portSecurityIpv6Rule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof TcpMatch);
- TcpMatch layer4Match=(TcpMatch) match.getLayer4Match();
- int port=portSecurityIpv6Rule.getSecurityRulePortMin();
- String expectedFlowId1 = "Egress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + port + "_" + IPV6_DEST_IP_1 +
- "_Permit";
- String expectedFlowId2 = "Egress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + port + "_" + IPV6_DEST_IP_2 +
- "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if(actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test IPv4 TCP add with port range (All TCP) and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleAddTcpAll1() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_TCP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(PORT_RANGE_MAX);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(PORT_RANGE_MIN);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn("0.0.0.0/24");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- Assert.assertTrue(match.getLayer4Match() instanceof TcpMatch);
- TcpMatch layer4Match=(TcpMatch) match.getLayer4Match();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
- }
-
- /**
- * Test IPv6 TCP add with port range (All TCP) and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6AddTcpAll1() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_TCP);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(PORT_RANGE_MAX);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(PORT_RANGE_MIN);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn("::/64");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- Assert.assertTrue(match.getLayer4Match() instanceof TcpMatch);
- TcpMatch layer4Match=(TcpMatch) match.getLayer4Match();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
- }
-
- /**
- * Test IPv4 TCP remove with port range (All TCP) and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleRemoveTcpAll1() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_TCP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(PORT_RANGE_MAX);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(PORT_RANGE_MIN);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn("0.0.0.0/24");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
- Assert.assertTrue(match.getLayer4Match() instanceof TcpMatch);
- Assert.assertEquals("Egress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_0.0.0.0/24_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test IPv6 TCP remove with port range (All TCP) and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6RemoveTcpAll1() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_TCP);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(PORT_RANGE_MAX);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(PORT_RANGE_MIN);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn("::/64");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
- Assert.assertTrue(match.getLayer4Match() instanceof TcpMatch);
- Assert.assertEquals("Egress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_::/64_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test IPv4 TCP add with port range (All TCP) and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleAddTcpAll2() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_TCP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(PORT_RANGE_MAX);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(PORT_RANGE_MIN);
- when(portSecurityRule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof TcpMatch);
- String expectedFlowId1 = "Egress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_" + DEST_IP_1 + "_Permit";
- String expectedFlowId2 = "Egress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_" + DEST_IP_2 + "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if(actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test IPv6 TCP add with port range (All TCP) and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6AddTcpAll2() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_TCP);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(PORT_RANGE_MAX);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(PORT_RANGE_MIN);
- when(portSecurityIpv6Rule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof TcpMatch);
- String expectedFlowId1 = "Egress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_" + IPV6_DEST_IP_1 + "_Permit";
- String expectedFlowId2 = "Egress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_" + IPV6_DEST_IP_2 + "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if(actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test IPv4 TCP remove with port range (All TCP) and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleRemoveTcpAll2() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_TCP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(PORT_RANGE_MAX);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(PORT_RANGE_MIN);
- when(portSecurityRule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof TcpMatch);
- String expectedFlowId1 = "Egress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_" + DEST_IP_1 + "_Permit";
- String expectedFlowId2 = "Egress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_" + DEST_IP_2 + "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if(actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test IPv6 TCP remove with port range (All TCP) and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6RemoveTcpAll2() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_TCP);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(PORT_RANGE_MAX);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(PORT_RANGE_MIN);
- when(portSecurityIpv6Rule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof TcpMatch);
- String expectedFlowId1 = "Egress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_" + IPV6_DEST_IP_1 + "_Permit";
- String expectedFlowId2 = "Egress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_" + IPV6_DEST_IP_2 + "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if(actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test IPv4 UDP add with port no and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleAddUdp1() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_UDP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(50);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(50);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn("0.0.0.0/24");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof UdpMatch);
- UdpMatch layer4Match = (UdpMatch) match.getLayer4Match();
- Assert.assertEquals(50, layer4Match.getUdpDestinationPort().getValue().intValue());
- int port = portSecurityRule.getSecurityRulePortMin();
- Assert.assertEquals("Egress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS +
- "_" + port + "_0.0.0.0/24_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test IPv6 UDP add with port no and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6AddUdp1() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_UDP);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(50);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(50);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn("::/64");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof UdpMatch);
- UdpMatch layer4Match = (UdpMatch) match.getLayer4Match();
- Assert.assertEquals(50, layer4Match.getUdpDestinationPort().getValue().intValue());
- int port = portSecurityIpv6Rule.getSecurityRulePortMin();
- Assert.assertEquals("Egress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS +
- "_" + port + "_::/64_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test IPv4 UDP remove with port no and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleRemoveUdp1() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_UDP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(50);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(50);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn("0.0.0.0/24");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof UdpMatch);
- UdpMatch layer4Match = (UdpMatch) match.getLayer4Match();
- Assert.assertEquals(50, layer4Match.getUdpDestinationPort().getValue().intValue());
- int port = portSecurityRule.getSecurityRulePortMin();
- Assert.assertEquals("Egress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS +
- "_" + port + "_0.0.0.0/24_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test IPv6 UDP remove with port no and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6RemoveUdp1() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_UDP);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(50);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(50);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn("::/64");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof UdpMatch);
- UdpMatch layer4Match = (UdpMatch) match.getLayer4Match();
- Assert.assertEquals(50, layer4Match.getUdpDestinationPort().getValue().intValue());
- int port = portSecurityIpv6Rule.getSecurityRulePortMin();
- Assert.assertEquals("Egress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS +
- "_" + port + "_::/64_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test IPv4 UDP add with port no and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleAddUdp2() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_UDP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(50);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(50);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn("0.0.0.0/24");
- when(portSecurityRule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof UdpMatch);
- UdpMatch layer4Match = (UdpMatch) match.getLayer4Match();
- Assert.assertEquals(50, layer4Match.getUdpDestinationPort().getValue().intValue());
- int port = portSecurityRule.getSecurityRulePortMin();
- String expectedFlowId1 = "Egress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + port + "_" + DEST_IP_1 +
- "_Permit";
- String expectedFlowId2 = "Egress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + port + "_" + DEST_IP_2 +
- "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if(actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test IPv6 UDP add with port no and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6AddUdp2() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_UDP);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(50);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(50);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn("::/64");
- when(portSecurityIpv6Rule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof UdpMatch);
- UdpMatch layer4Match = (UdpMatch) match.getLayer4Match();
- Assert.assertEquals(50, layer4Match.getUdpDestinationPort().getValue().intValue());
- int port = portSecurityIpv6Rule.getSecurityRulePortMin();
- String expectedFlowId1 = "Egress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + port + "_" + IPV6_DEST_IP_1 +
- "_Permit";
- String expectedFlowId2 = "Egress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + port + "_" + IPV6_DEST_IP_2 +
- "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if(actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test IPv4 UDP remove with port no and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleRemoveUdp2() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_UDP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(50);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(50);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn("0.0.0.0/24");
- when(portSecurityRule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof UdpMatch);
- UdpMatch layer4Match = (UdpMatch) match.getLayer4Match();
- Assert.assertEquals(50, layer4Match.getUdpDestinationPort().getValue().intValue());
- int port = portSecurityRule.getSecurityRulePortMin();
- String expectedFlowId1 = "Egress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + port + "_" + DEST_IP_1 +
- "_Permit";
- String expectedFlowId2 = "Egress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + port + "_" + DEST_IP_2 +
- "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if(actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test IPv6 UDP remove with port no and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6RemoveUdp2() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_UDP);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(50);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(50);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn("::/64");
- when(portSecurityIpv6Rule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof UdpMatch);
- UdpMatch layer4Match = (UdpMatch) match.getLayer4Match();
- Assert.assertEquals(50, layer4Match.getUdpDestinationPort().getValue().intValue());
- int port = portSecurityIpv6Rule.getSecurityRulePortMin();
- String expectedFlowId1 = "Egress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + port + "_" + IPV6_DEST_IP_1 +
- "_Permit";
- String expectedFlowId2 = "Egress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + port + "_" + IPV6_DEST_IP_2 +
- "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if(actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test IPv4 UDP add with port (All UDP) and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleAddUdpAll1() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_UDP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(PORT_RANGE_MAX);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(PORT_RANGE_MIN);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn("0.0.0.0/24");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof UdpMatch);
- Assert.assertEquals("Egress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_0.0.0.0/24_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test IPv6 UDP add with port (All UDP) and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6AddUdpAll1() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_UDP);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(PORT_RANGE_MAX);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(PORT_RANGE_MIN);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn("::/64");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof UdpMatch);
- Assert.assertEquals("Egress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_::/64_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test IPv4 UDP remove with port (All UDP) and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleRemoveUdpAll1() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_UDP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(PORT_RANGE_MAX);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(PORT_RANGE_MIN);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn("0.0.0.0/24");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof UdpMatch);
- Assert.assertEquals("Egress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_0.0.0.0/24_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test IPv6 UDP remove with port (All UDP) and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6RemoveUdpAll1() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_UDP);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(PORT_RANGE_MAX);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(PORT_RANGE_MIN);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn("::/64");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof UdpMatch);
- Assert.assertEquals("Egress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_::/64_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test IPv4 UDP add with port (All UDP) and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleAddUdpAll2() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_UDP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(PORT_RANGE_MAX);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(PORT_RANGE_MIN);
- when(portSecurityRule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof UdpMatch);
- String expectedFlowId1 = "Egress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_" + DEST_IP_1 + "_Permit";
- String expectedFlowId2 = "Egress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_" + DEST_IP_2 + "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if(actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test IPv6 UDP add with port (All UDP) and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6AddUdpAll2() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_UDP);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(PORT_RANGE_MAX);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(PORT_RANGE_MIN);
- when(portSecurityIpv6Rule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof UdpMatch);
- String expectedFlowId1 = "Egress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_" + IPV6_DEST_IP_1 + "_Permit";
- String expectedFlowId2 = "Egress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_" + IPV6_DEST_IP_2 + "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if(actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test IPv4 UDP remove with port (All UDP) and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleRemoveUdpAll2() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_UDP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(PORT_RANGE_MAX);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(PORT_RANGE_MIN);
- when(portSecurityRule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof UdpMatch);
- String expectedFlowId1 = "Egress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_" + DEST_IP_1 + "_Permit";
- String expectedFlowId2 = "Egress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_" + DEST_IP_2 + "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if(actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test IPv6 UDP remove with port (All UDP) and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6RemoveUdpAll2() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_UDP);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(PORT_RANGE_MAX);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(PORT_RANGE_MIN);
- when(portSecurityIpv6Rule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof UdpMatch);
- String expectedFlowId1 = "Egress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_" + IPV6_DEST_IP_1 + "_Permit";
- String expectedFlowId2 = "Egress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_" + IPV6_DEST_IP_2 + "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if(actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test ICMP add with code, type and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleAddIcmp1() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_ICMP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(10);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(10);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn("0.0.0.0/24");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- Icmpv4Match icmpv4Match = match.getIcmpv4Match();
- Assert.assertEquals(10, icmpv4Match.getIcmpv4Type().shortValue());
- Assert.assertEquals(10, icmpv4Match.getIcmpv4Code().shortValue());
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
- Short type = portSecurityRule.getSecurityRulePortMin().shortValue();
- Short code = portSecurityRule.getSecurityRulePortMax().shortValue();
- Assert.assertEquals("Egress_ICMP_" + SEGMENT_ID + "_" + MAC_ADDRESS +
- "_" + type + "_" + code + "_0.0.0.0/24_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test ICMPv6 add with code, type and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6AddIcmp1() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_ICMPV6);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(10);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(10);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn("::/64");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- Icmpv6Match icmpv6Match = match.getIcmpv6Match();
- Assert.assertEquals(10, icmpv6Match.getIcmpv6Type().shortValue());
- Assert.assertEquals(10, icmpv6Match.getIcmpv6Code().shortValue());
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
- Short type = portSecurityIpv6Rule.getSecurityRulePortMin().shortValue();
- Short code = portSecurityIpv6Rule.getSecurityRulePortMax().shortValue();
- Assert.assertEquals("Egress_ICMP_" + SEGMENT_ID + "_" + MAC_ADDRESS +
- "_" + type + "_" + code + "_::/64_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test ICMP remove with code, type and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleRemoveIcmp1() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_ICMP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(20);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(20);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn("0.0.0.0/24");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- Icmpv4Match icmpv4Match = match.getIcmpv4Match();
- Assert.assertEquals(20, icmpv4Match.getIcmpv4Type().shortValue());
- Assert.assertEquals(20, icmpv4Match.getIcmpv4Code().shortValue());
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
- Short type = portSecurityRule.getSecurityRulePortMin().shortValue();
- Short code = portSecurityRule.getSecurityRulePortMax().shortValue();
- Assert.assertEquals("Egress_ICMP_" + SEGMENT_ID + "_" + MAC_ADDRESS +
- "_" + type + "_" + code + "_0.0.0.0/24_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test ICMPv6 remove with code, type and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6RemoveIcmp1() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_ICMPV6);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(20);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(20);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn("::/64");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- Icmpv6Match icmpv6Match = match.getIcmpv6Match();
- Assert.assertEquals(20, icmpv6Match.getIcmpv6Type().shortValue());
- Assert.assertEquals(20, icmpv6Match.getIcmpv6Code().shortValue());
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
- Short type = portSecurityIpv6Rule.getSecurityRulePortMin().shortValue();
- Short code = portSecurityIpv6Rule.getSecurityRulePortMax().shortValue();
- Assert.assertEquals("Egress_ICMP_" + SEGMENT_ID + "_" + MAC_ADDRESS +
- "_" + type + "_" + code + "_::/64_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test ICMP add with code, type and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleAddIcmp2() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_ICMP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(30);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(30);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn("0.0.0.0/24");
- when(portSecurityRule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- Icmpv4Match icmpv4Match = match.getIcmpv4Match();
- Assert.assertEquals(30, icmpv4Match.getIcmpv4Type().shortValue());
- Assert.assertEquals(30, icmpv4Match.getIcmpv4Code().shortValue());
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
- Short type = portSecurityRule.getSecurityRulePortMin().shortValue();
- Short code = portSecurityRule.getSecurityRulePortMax().shortValue();
- String expectedFlowId1 = "Egress_ICMP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + type + "_" + code + "_"
- + DEST_IP_1 + "_Permit";
- String expectedFlowId2 = "Egress_ICMP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + type + "_" + code + "_"
- + DEST_IP_2 + "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if(actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test ICMPv6 add with code, type and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6AddIcmp2() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_ICMPV6);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(30);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(30);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn("::/64");
- when(portSecurityIpv6Rule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- Icmpv6Match icmpv6Match = match.getIcmpv6Match();
- Assert.assertEquals(30, icmpv6Match.getIcmpv6Type().shortValue());
- Assert.assertEquals(30, icmpv6Match.getIcmpv6Code().shortValue());
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
- Short type = portSecurityIpv6Rule.getSecurityRulePortMin().shortValue();
- Short code = portSecurityIpv6Rule.getSecurityRulePortMax().shortValue();
- String expectedFlowId1 = "Egress_ICMP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + type + "_" + code + "_"
- + IPV6_DEST_IP_1 + "_Permit";
- String expectedFlowId2 = "Egress_ICMP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + type + "_" + code + "_"
- + IPV6_DEST_IP_2 + "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if(actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test ICMP remove with code, type and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleRemoveIcmp2() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_ICMP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(40);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(40);
- when(portSecurityRule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- Icmpv4Match icmpv4Match = match.getIcmpv4Match();
- Assert.assertEquals(40, icmpv4Match.getIcmpv4Type().shortValue());
- Assert.assertEquals(40, icmpv4Match.getIcmpv4Code().shortValue());
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
- Short type = portSecurityRule.getSecurityRulePortMin().shortValue();
- Short code = portSecurityRule.getSecurityRulePortMax().shortValue();
- String expectedFlowId1 = "Egress_ICMP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + type + "_" + code + "_"
- + DEST_IP_1 + "_Permit";
- String expectedFlowId2 = "Egress_ICMP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + type + "_" + code + "_"
- + DEST_IP_2 + "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if(actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test ICMPv6 remove with code, type and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6RemoveIcmp2() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_ICMPV6);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(40);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(40);
- when(portSecurityIpv6Rule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(egressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- egressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- Icmpv6Match icmpv6Match = match.getIcmpv6Match();
- Assert.assertEquals(40, icmpv6Match.getIcmpv6Type().shortValue());
- Assert.assertEquals(40, icmpv6Match.getIcmpv6Code().shortValue());
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetSource().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
- Short type = portSecurityIpv6Rule.getSecurityRulePortMin().shortValue();
- Short code = portSecurityIpv6Rule.getSecurityRulePortMax().shortValue();
- String expectedFlowId1 = "Egress_ICMP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + type + "_" + code + "_"
- + IPV6_DEST_IP_1 + "_Permit";
- String expectedFlowId2 = "Egress_ICMP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + type + "_" + code + "_"
- + IPV6_DEST_IP_2 + "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if(actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test IPv4 invalid ether type test case.
- */
- @Test
- public void testProgramPortSecurityACLRuleInvalidEther() throws Exception {
- when(portSecurityRule.getSecurityRuleEthertype()).thenReturn("IP");
-
- egressAclServiceSpy.programPortSecurityGroup(1554L, "2", MAC_ADDRESS, 124, securityGroup,PORT_UUID, nodeId, false);
-
- verify(writeTransaction, times(0)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(writeTransaction, times(0)).submit();
- verify(commitFuture, times(0)).get();
- }
-
- /**
- * Test IPv4 invalid direction type test case.
- */
- @Test
- public void testProgramPortSecurityACLRuleInvalidDirection() throws Exception {
- when(portSecurityRule.getSecurityRuleDirection()).thenReturn(NeutronSecurityRule.DIRECTION_INGRESS);
-
- egressAclServiceSpy.programPortSecurityGroup(1554L, "2", MAC_ADDRESS, 124, securityGroup,PORT_UUID, nodeId, false);
-
- verify(writeTransaction, times(0)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(writeTransaction, times(0)).submit();
- verify(commitFuture, times(0)).get();
- }
-
- /**
- * Test With isConntrackEnabled false
- */
- @Test
- public void testProgramFixedSecurityACLAdd2() throws Exception {
- when(securityServices.isConntrackEnabled()).thenReturn(false);
-
- egressAclServiceSpy.programFixedSecurityGroup(1554L, "2", MAC_ADDRESS, 1, neutronDestIpList, true);
-
- verify(writeTransaction, times(9)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class), eq(true));
- verify(writeTransaction, times(9)).submit();
- verify(commitFuture, times(9)).checkedGet();
- }
-
- /**
- * Test With isConntrackEnabled false
- */
- @Test
- public void testProgramFixedSecurityACLRemove2() throws Exception {
- when(securityServices.isConntrackEnabled()).thenReturn(false);
-
- egressAclServiceSpy.programFixedSecurityGroup(1554L, "2", MAC_ADDRESS, 1, neutronDestIpList, false);
-
- verify(writeTransaction, times(9)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(writeTransaction, times(9)).submit();
- verify(commitFuture, times(9)).get();
- }
-
- /**
- * Test With isConntrackEnabled true
- */
- @Test
- public void testProgramFixedSecurityACLAdd4() throws Exception {
- when(securityServices.isConntrackEnabled()).thenReturn(true);
-
- egressAclServiceSpy.programFixedSecurityGroup(1554L, "2", MAC_ADDRESS, 1, neutronDestIpList, true);
-
- verify(writeTransaction, times(14)).put(any(LogicalDatastoreType.class),
- any(InstanceIdentifier.class), any(Node.class), eq(true));
- verify(writeTransaction, times(14)).submit();
- verify(commitFuture, times(14)).checkedGet();
- }
-
- /**
- * Test With isConntrackEnabled true
- */
- @Test
- public void testProgramFixedSecurityACLRemove4() throws Exception {
- when(securityServices.isConntrackEnabled()).thenReturn(true);
-
- egressAclServiceSpy.programFixedSecurityGroup(1554L, "2", MAC_ADDRESS, 1, neutronDestIpList, false);
-
- verify(writeTransaction, times(14)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(writeTransaction, times(14)).submit();
- verify(commitFuture, times(14)).get();
- }
-
-}
+++ /dev/null
-/*
- * Copyright © 2016, 2017 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyBoolean;
-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 org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
-import org.opendaylight.netvirt.openstack.netvirt.api.StatusCode;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.Status;
-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.inventory.rev130819.nodes.Node;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-
-import com.google.common.util.concurrent.CheckedFuture;
-
-import java.net.InetAddress;
-
-/**
- * Unit test for {@link IcmpEchoResponderService}
- */
-@RunWith(MockitoJUnitRunner.class)
-@SuppressWarnings("unchecked")
-public class IcmpEchoResponderServiceTest {
- @InjectMocks private IcmpEchoResponderService icmpEchoResponderService = new IcmpEchoResponderService();
-
- @Mock
- private DataBroker dataBroker;
-
- private static final String HOST_ADDRESS = "121.0.0.1";
- private static final String MAC_ADDRESS = "87:1D:5E:02:40:B7";
-
- @Test
- public void testProgramIcmpEchoEntry() throws Exception {
- icmpEchoResponderService.setService(Service.ARP_RESPONDER);
-
- InetAddress ipAddress = mock(InetAddress.class);
- when(ipAddress.getHostAddress()).thenReturn(HOST_ADDRESS);
-
- WriteTransaction transaction = mock(WriteTransaction.class);
- when(dataBroker.newWriteOnlyTransaction()).thenReturn(transaction);
- CheckedFuture<Void, TransactionCommitFailedException> commitFuture = mock(CheckedFuture.class);
- when(transaction.submit()).thenReturn(commitFuture);
-
- NodeBuilder nodeBuilder = mock(NodeBuilder.class);
- when(nodeBuilder.getKey()).thenReturn(mock(NodeKey.class));
-
- FlowBuilder flowBuilder = mock(FlowBuilder.class);
- when(flowBuilder.getKey()).thenReturn(mock(FlowKey.class));
-
- // test Action.ADD
- assertEquals("Error, did not return the expected StatusCode", new Status(StatusCode.SUCCESS), icmpEchoResponderService.programIcmpEchoEntry(12L, "2", MAC_ADDRESS, ipAddress, Action.ADD));
-
- verify(transaction, times(2)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class), anyBoolean());
- verify(transaction, times(1)).submit();
- verify(commitFuture, times(1)).get();
-
- // test Action.DELETE
- assertEquals("Error, did not return the expected StatusCode", new Status(StatusCode.SUCCESS), icmpEchoResponderService.programIcmpEchoEntry(12L, "2", MAC_ADDRESS, ipAddress, Action.DELETE));
-
- verify(transaction, times(1)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(commitFuture, times(2)).get(); // 1 + 1 above
- }
-}
+++ /dev/null
-/*
- * Copyright © 2015, 2017 Inocybe 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.netvirt.openstack.netvirt.providers.openflow13.services;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyBoolean;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import java.net.InetAddress;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.Status;
-import org.opendaylight.netvirt.openstack.netvirt.api.StatusCode;
-import org.opendaylight.netvirt.openstack.netvirt.providers.NetvirtProvidersProvider;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.PipelineOrchestrator;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.powermock.api.support.membermodification.MemberModifier;
-
-import com.google.common.util.concurrent.CheckedFuture;
-
-/**
- * Unit test for {@link InboundNatService}
- */
-@RunWith(MockitoJUnitRunner.class)
-@SuppressWarnings("unchecked")
-public class InboundNatServiceTest {
-
- @InjectMocks private InboundNatService inboundNatService = new InboundNatService(Service.ARP_RESPONDER);
-
- @Mock private DataBroker dataBroker;
- @Mock private PipelineOrchestrator orchestrator;
-
- @Mock private WriteTransaction writeTransaction;
- @Mock private CheckedFuture<Void, TransactionCommitFailedException> commitFuture;
-
- private static final String HOST_ADDRESS = "127.0.0.1";
- private static final String HOST_ADDRESS_PREFIX = "127.0.0.1/32";
-
- @Before
- public void setUp() throws IllegalArgumentException, IllegalAccessException {
- when(writeTransaction.submit()).thenReturn(commitFuture);
-
- when(dataBroker.newWriteOnlyTransaction()).thenReturn(writeTransaction);
-
- when(orchestrator.getNextServiceInPipeline(any(Service.class))).thenReturn(Service.ARP_RESPONDER);
-
- NetvirtProvidersProvider netvirtProvider = mock(NetvirtProvidersProvider.class);
- MemberModifier.field(NetvirtProvidersProvider.class, "hasProviderEntityOwnership").set(netvirtProvider, new AtomicBoolean(true));
-
- }
-
- /**
- * Test method {@link InboundNatService#programIpRewriteRule(Long, Long, String, InetAddress, InetAddress, Action)}
- */
- @Test
- public void testProgramIpRewriteRule() throws Exception {
- InetAddress rewriteAddress = mock(InetAddress.class);
- when(rewriteAddress.getHostAddress()).thenReturn(HOST_ADDRESS);
- InetAddress matchAddress = mock(InetAddress.class);
- when(matchAddress.getHostAddress()).thenReturn(HOST_ADDRESS);
-
- assertEquals("Error, did not return the expected StatusCode",
- new Status(StatusCode.SUCCESS),
- inboundNatService.programIpRewriteRule(123L, 2L, "2", // FIXME: describe params
- matchAddress, rewriteAddress, Action.ADD));
- verify(writeTransaction, times(2)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class), anyBoolean());
- verify(writeTransaction, times(1)).submit();
- verify(commitFuture, times(1)).get();
-
- assertEquals("Error, did not return the expected StatusCode",
- new Status(StatusCode.SUCCESS),
- inboundNatService.programIpRewriteRule(123L, 2L, "2", // FIXME: describe params
- matchAddress, rewriteAddress, Action.DELETE));
- verify(writeTransaction, times(1)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(writeTransaction, times(2)).submit();
- verify(commitFuture, times(2)).get(); // 1 + 1 above
- }
-
- /**
- * Test method {@link InboundNatService#programIpRewriteExclusion(Long, String, String, Action)}
- */
- @Test
- public void testProgramIpRewriteExclusion() throws Exception {
- assertEquals("Error, did not return the expected StatusCode",
- new Status(StatusCode.SUCCESS),
- inboundNatService.programIpRewriteExclusion(123L, "2", HOST_ADDRESS_PREFIX, Action.ADD));
- verify(writeTransaction, times(2)).put(any(LogicalDatastoreType.class),
- any(InstanceIdentifier.class), any(Node.class), anyBoolean());
- verify(writeTransaction, times(1)).submit();
- verify(commitFuture, times(1)).get();
-
- assertEquals("Error, did not return the expected StatusCode",
- new Status(StatusCode.SUCCESS),
- inboundNatService.programIpRewriteExclusion(123L, "2",
- HOST_ADDRESS_PREFIX, Action.DELETE));
- verify(writeTransaction, times(1)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(writeTransaction, times(2)).submit();
- verify(commitFuture, times(2)).get(); // 1 + 1 above
- }
-}
+++ /dev/null
-/*
- * Copyright © 2015, 2017 Inocybe 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.netvirt.openstack.netvirt.providers.openflow13.services;
-
-import static org.mockito.Matchers.any;
-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.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
-import org.opendaylight.netvirt.openstack.netvirt.api.SecurityServicesManager;
-import org.opendaylight.netvirt.openstack.netvirt.providers.NetvirtProvidersProvider;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.PipelineOrchestrator;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityGroup;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityRule;
-import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs;
-import org.opendaylight.netvirt.openstack.netvirt.api.SecurityGroupCacheManger;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSecurityRuleCRUD;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.Match;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.EthernetMatch;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.Icmpv4Match;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.Icmpv6Match;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._4.match.TcpMatch;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._4.match.UdpMatch;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.powermock.api.mockito.PowerMockito;
-import org.powermock.api.support.membermodification.MemberModifier;
-import org.powermock.modules.junit4.PowerMockRunner;
-
-import com.google.common.util.concurrent.CheckedFuture;
-
-/**
- * Unit test fort {@link IngressAclService}
- */
-@RunWith(PowerMockRunner.class)
-@SuppressWarnings("unchecked")
-public class IngressAclServiceTest {
-
- @InjectMocks private IngressAclService ingressAclService = new IngressAclService();
- private IngressAclService ingressAclServiceSpy;
-
- @Mock private DataBroker dataBroker;
- @Mock private PipelineOrchestrator orchestrator;
-
- @Mock private WriteTransaction writeTransaction;
- @Mock private CheckedFuture<Void, TransactionCommitFailedException> commitFuture;
-
- @Mock private NeutronSecurityGroup securityGroup;
- @Mock private NeutronSecurityRule portSecurityRule;
- @Mock private NeutronSecurityGroup securityGroupIpv6;
- @Mock private NeutronSecurityRule portSecurityIpv6Rule;
- @Mock private SecurityServicesManager securityServices;
- @Mock private SecurityGroupCacheManger securityGroupCacheManger;
- @Mock private INeutronSecurityRuleCRUD neutronSecurityRuleCache;
- @Mock private NodeId nodeId;
-
- private List<Neutron_IPs> neutronSrcIpList = new ArrayList<>();
- private List<Neutron_IPs> neutronDestIpList = new ArrayList<>();
- private Neutron_IPs neutron_ip_src;
- private Neutron_IPs neutron_ip_dest_1;
- private Neutron_IPs neutron_ip_dest_2;
- private Neutron_IPs neutron_ipv6_dest_1;
- private Neutron_IPs neutron_ipv6_dest_2;
-
- private static final String MAC_ADDRESS = "87:1D:5E:02:40:B8";
- private static final String DHCP_MAC_ADDRESS = "87:1D:5E:02:40:B9";
- private static final String SRC_IP = "192.168.0.1";
- private static final String DEST_IP_1 = "192.169.0.1";
- private static final String DEST_IP_2 = "192.169.0.2";
- private static final String IPV6_DEST_IP_1 = "2001:db8:2::200";
- private static final String IPV6_DEST_IP_2 = "2001:db8:2::201";
- private static final Long IPV6_ETHER_TYPE = (long) 0x86DD;
- private static final Long IPV4_ETHER_TYPE = (long) 0x0800;
- private static final String SECURITY_GROUP_UUID = "85cc3048-abc3-43cc-89b3-377341426ac5";
- private static final String PORT_UUID = "95cc3048-abc3-43cc-89b3-377341426ac5";
- private static final String SEGMENT_ID = "2";
- private static final Long DP_ID_LONG = (long) 1554;
- private static final Long LOCAL_PORT = (long) 124;
- private static final int PORT_RANGE_MIN = 1;
- private static final int PORT_RANGE_MAX = 65535;
- private static FlowBuilder flowBuilder;
- private static NodeBuilder nodeBuilder;
-
- private static Answer<Object> answer() {
- return invocation -> {
- flowBuilder = (FlowBuilder) invocation.getArguments()[0];
- nodeBuilder = (NodeBuilder) invocation.getArguments()[1];
- return null;
- };
- }
-
- @Before
- public void setUp() throws IllegalArgumentException, IllegalAccessException{
- ingressAclServiceSpy = PowerMockito.spy(ingressAclService);
-
- when(writeTransaction.submit()).thenReturn(commitFuture);
-
- when(dataBroker.newWriteOnlyTransaction()).thenReturn(writeTransaction);
-
- when(orchestrator.getNextServiceInPipeline(any(Service.class))).thenReturn(Service.ARP_RESPONDER);
-
- portSecurityRule = mock(NeutronSecurityRule.class);
- when(portSecurityRule.getSecurityRuleEthertype()).thenReturn(NeutronSecurityRule.ETHERTYPE_IPV4);
- when(portSecurityRule.getSecurityRuleDirection()).thenReturn(NeutronSecurityRule.DIRECTION_INGRESS);
-
- List<NeutronSecurityRule> portSecurityList = new ArrayList<>();
- portSecurityList.add(portSecurityRule);
-
- neutron_ip_src = new Neutron_IPs();
- neutron_ip_src.setIpAddress(SRC_IP);
- neutronSrcIpList.add(neutron_ip_src);
-
- neutron_ip_dest_1 = new Neutron_IPs();
- neutron_ip_dest_1.setIpAddress(DEST_IP_1);
- neutronDestIpList.add(neutron_ip_dest_1);
-
- neutron_ip_dest_2 = new Neutron_IPs();
- neutron_ip_dest_2.setIpAddress(DEST_IP_2);
- neutronDestIpList.add(neutron_ip_dest_2);
-
- portSecurityIpv6Rule = mock(NeutronSecurityRule.class);
- when(portSecurityIpv6Rule.getSecurityRuleEthertype()).thenReturn(NeutronSecurityRule.ETHERTYPE_IPV6);
- when(portSecurityIpv6Rule.getSecurityRuleDirection()).thenReturn(NeutronSecurityRule.DIRECTION_INGRESS);
-
- List<NeutronSecurityRule> portSecurityIpv6List = new ArrayList<>();
- portSecurityIpv6List.add(portSecurityIpv6Rule);
- when(neutronSecurityRuleCache.getAllNeutronSecurityRules()).thenReturn(portSecurityIpv6List);
-
- neutron_ipv6_dest_1 = new Neutron_IPs();
- neutron_ipv6_dest_1.setIpAddress(IPV6_DEST_IP_1);
- neutronDestIpList.add(neutron_ipv6_dest_1);
-
- neutron_ipv6_dest_2 = new Neutron_IPs();
- neutron_ipv6_dest_2.setIpAddress(IPV6_DEST_IP_2);
- neutronDestIpList.add(neutron_ipv6_dest_2);
-
- when(neutronSecurityRuleCache.getAllNeutronSecurityRules()).thenReturn(portSecurityList);
- when(securityServices.getVmListForSecurityGroup
- (PORT_UUID, SECURITY_GROUP_UUID)).thenReturn(neutronDestIpList);
- NetvirtProvidersProvider netvirtProvider = mock(NetvirtProvidersProvider.class);
- MemberModifier.field(NetvirtProvidersProvider.class, "hasProviderEntityOwnership").set(netvirtProvider, new AtomicBoolean(true));
-
- }
- /**
- * Test method {@link EgressAclService#programPortSecurityGroup(java.lang.Long, java.lang.String,
- * java.lang.String, long, NeutronSecurityGroup,
- * java.lang.String, NodeId, boolean)} when portSecurityRule is incomplete
- */
- @Test
- public void testProgramPortSecurityGroupWithIncompleteRule() throws Exception {
- NeutronSecurityRule portSecurityRule1 = mock(NeutronSecurityRule.class);
- when(portSecurityRule1.getSecurityRuleEthertype()).thenReturn(NeutronSecurityRule.ETHERTYPE_IPV4);
- when(portSecurityRule1.getSecurityRuleDirection()).thenReturn("not_ingress"); // other direction
-
- NeutronSecurityRule portSecurityRule2 = mock(NeutronSecurityRule.class);
- when(portSecurityRule2.getSecurityRuleEthertype()).thenReturn(null);
- when(portSecurityRule2.getSecurityRuleDirection()).thenReturn(NeutronSecurityRule.DIRECTION_INGRESS);
-
- NeutronSecurityRule portSecurityRule3 = mock(NeutronSecurityRule.class);
- when(portSecurityRule3.getSecurityRuleEthertype()).thenReturn(NeutronSecurityRule.ETHERTYPE_IPV4);
- when(portSecurityRule3.getSecurityRuleDirection()).thenReturn(null);
-
- NeutronSecurityRule portSecurityRule4 = mock(NeutronSecurityRule.class);
- when(portSecurityRule4.getSecurityRuleEthertype()).thenReturn(null);
- when(portSecurityRule4.getSecurityRuleDirection()).thenReturn(null);
-
- List<NeutronSecurityRule> portSecurityList = new ArrayList<>();
- portSecurityList.add(null);
- portSecurityList.add(portSecurityRule1);
- portSecurityList.add(portSecurityRule2);
- portSecurityList.add(portSecurityRule3);
- portSecurityList.add(portSecurityRule4);
-
- NeutronSecurityGroup localSecurityGroup = mock(NeutronSecurityGroup.class);
- when(neutronSecurityRuleCache.getAllNeutronSecurityRules()).thenReturn(portSecurityList);
-
- ingressAclServiceSpy.programPortSecurityGroup(
- 1554L, "2", MAC_ADDRESS, 124, localSecurityGroup, PORT_UUID, nodeId, false);
- }
-
- /**
- * Test IPv4 add test case.
- */
- @Test
- public void testProgramPortSecurityACLRuleAddIpv4() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(null);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(null);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(null);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn(null);
-
- ingressAclServiceSpy.programPortSecurityGroup(1554L, "2", MAC_ADDRESS, 124, securityGroup,PORT_UUID, nodeId, true);
-
- verify(writeTransaction, times(1)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class), eq(true));
- verify(writeTransaction, times(1)).submit();
- verify(commitFuture, times(1)).checkedGet();
- }
-
- /**
- * Test IPv6 add test case.
- */
- @Test
- public void testProgramPortSecurityACLRuleAddIpv6() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(null);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(null);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(null);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn(null);
-
- ingressAclServiceSpy.programPortSecurityGroup(1554L, "2", MAC_ADDRESS, 124, securityGroupIpv6, PORT_UUID, nodeId, true);
-
- verify(writeTransaction, times(1)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class), eq(true));
- verify(writeTransaction, times(1)).submit();
- verify(commitFuture, times(1)).checkedGet();
- }
-
- /**
- * Test IPv4 remove test case.
- */
- @Test
- public void testProgramPortSecurityACLRuleRemoveIpv4() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(null);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(null);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(null);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn(null);
-
- ingressAclServiceSpy.programPortSecurityGroup(1554L, "2", MAC_ADDRESS, 124, securityGroup,PORT_UUID, nodeId, false);
-
- verify(writeTransaction, times(1)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(writeTransaction, times(1)).submit();
- verify(commitFuture, times(1)).get();
- }
-
- /**
- * Test IPv6 remove test case.
- */
- @Test
- public void testProgramPortSecurityACLRuleRemoveIpv6() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(null);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(null);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(null);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn(null);
-
- ingressAclServiceSpy.programPortSecurityGroup(1554L, "2", MAC_ADDRESS, 124, securityGroupIpv6, PORT_UUID, nodeId, false);
-
- verify(writeTransaction, times(1)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(writeTransaction, times(1)).submit();
- verify(commitFuture, times(1)).get();
- }
-
- /**
- * Test IPv4 TCP add with port no and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleAddTcp1() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_TCP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(20);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(20);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn("0.0.0.0/24");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof TcpMatch);
- TcpMatch layer4Match = (TcpMatch) match.getLayer4Match();
- Assert.assertEquals(20, layer4Match.getTcpDestinationPort().getValue().intValue());
- int port = portSecurityRule.getSecurityRulePortMin();
- Assert.assertEquals("Ingress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS +
- "_" + port + "_0.0.0.0/24_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test IPv6 TCP add with port no and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6AddTcp1() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_TCP);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(20);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(20);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn("::/64");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof TcpMatch);
- TcpMatch layer4Match = (TcpMatch) match.getLayer4Match();
- Assert.assertEquals(20, layer4Match.getTcpDestinationPort().getValue().intValue());
- int port = portSecurityIpv6Rule.getSecurityRulePortMin();
- Assert.assertEquals("Ingress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS +
- "_" + port + "_::/64_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test IPv4 TCP remove with port no and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleRemoveTcp1() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_TCP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(15);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(15);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn("0.0.0.0/24");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof TcpMatch);
- TcpMatch layer4Match = (TcpMatch) match.getLayer4Match();
- Assert.assertEquals(15, layer4Match.getTcpDestinationPort().getValue().intValue());
- int port = portSecurityRule.getSecurityRulePortMin();
- Assert.assertEquals("Ingress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS +
- "_" + port + "_0.0.0.0/24_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test IPv6 TCP remove with port no and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6RemoveTcp1() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_TCP);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(15);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(15);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn("::/64");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof TcpMatch);
- TcpMatch layer4Match = (TcpMatch) match.getLayer4Match();
- Assert.assertEquals(15, layer4Match.getTcpDestinationPort().getValue().intValue());
- int port = portSecurityIpv6Rule.getSecurityRulePortMin();
- Assert.assertEquals("Ingress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS +
- "_" + port + "_::/64_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test IPv4 TCP add with port no and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleAddTcp2() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_TCP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(50);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(50);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn("0.0.0.0/24");
- when(portSecurityRule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof TcpMatch);
- TcpMatch layer4Match = (TcpMatch) match.getLayer4Match();
- Assert.assertEquals(50, layer4Match.getTcpDestinationPort().getValue().intValue());
- int port = portSecurityRule.getSecurityRulePortMin();
- String expectedFlowId1 = "Ingress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + port + "_" + DEST_IP_1 +
- "_Permit";
- String expectedFlowId2 = "Ingress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + port + "_" + DEST_IP_2 +
- "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if (actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test IPv6 TCP add with port no and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6AddTcp2() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_TCP);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(50);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(50);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn("::/64");
- when(portSecurityIpv6Rule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof TcpMatch);
- TcpMatch layer4Match = (TcpMatch) match.getLayer4Match();
- Assert.assertEquals(50, layer4Match.getTcpDestinationPort().getValue().intValue());
- int port = portSecurityIpv6Rule.getSecurityRulePortMin();
- String expectedFlowId1 = "Ingress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + port + "_" + IPV6_DEST_IP_1 +
- "_Permit";
- String expectedFlowId2 = "Ingress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + port + "_" + IPV6_DEST_IP_2 +
- "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if (actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test IPv4 TCP remove with port no and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleRemoveTcp2() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_TCP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(50);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(50);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn("0.0.0.0/24");
- when(portSecurityRule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof TcpMatch);
- TcpMatch layer4Match = (TcpMatch) match.getLayer4Match();
- Assert.assertEquals(50, layer4Match.getTcpDestinationPort().getValue().intValue());
- int port = portSecurityRule.getSecurityRulePortMin();
- String expectedFlowId1 = "Ingress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + port + "_" + DEST_IP_1 +
- "_Permit";
- String expectedFlowId2 = "Ingress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + port + "_" + DEST_IP_2 +
- "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if (actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
-
- /**
- * Test IPv6 TCP remove with port no and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6RemoveTcp2() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_TCP);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(50);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(50);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn("::/64");
- when(portSecurityIpv6Rule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof TcpMatch);
- TcpMatch layer4Match = (TcpMatch) match.getLayer4Match();
- Assert.assertEquals(50, layer4Match.getTcpDestinationPort().getValue().intValue());
- int port = portSecurityIpv6Rule.getSecurityRulePortMin();
- String expectedFlowId1 = "Ingress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + port + "_" + IPV6_DEST_IP_1 +
- "_Permit";
- String expectedFlowId2 = "Ingress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + port + "_" + IPV6_DEST_IP_2 +
- "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if (actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test IPv4 TCP add with port (All TCP) and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleAddTcpAll1() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_TCP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(PORT_RANGE_MAX);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(PORT_RANGE_MIN);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn("0.0.0.0/24");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof TcpMatch);
- Assert.assertEquals("Ingress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_0.0.0.0/24_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test IPv6 TCP add with port (All TCP) and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6AddTcpAll1() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_TCP);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(PORT_RANGE_MAX);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(PORT_RANGE_MIN);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn("::/64");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof TcpMatch);
- Assert.assertEquals("Ingress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_::/64_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test IPv4 TCP remove with port (All TCP) and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleRemoveTcpAll1() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_TCP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(PORT_RANGE_MAX);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(PORT_RANGE_MIN);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn("0.0.0.0/24");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof TcpMatch);
- Assert.assertEquals("Ingress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_0.0.0.0/24_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test IPv6 TCP remove with port (All TCP) and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6RemoveTcpAll1() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_TCP);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(PORT_RANGE_MAX);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(PORT_RANGE_MIN);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn("::/64");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof TcpMatch);
- Assert.assertEquals("Ingress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_::/64_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test IPv4 TCP add with port (All TCP) and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleAddTcpAll2() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_TCP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(PORT_RANGE_MAX);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(PORT_RANGE_MIN);
- when(portSecurityRule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof TcpMatch);
- String expectedFlowId1 = "Ingress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_" + DEST_IP_1 + "_Permit";
- String expectedFlowId2 = "Ingress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_" + DEST_IP_2 + "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if (actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test IPv6 TCP add with port (All TCP) and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6AddTcpAll2() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_TCP);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(PORT_RANGE_MAX);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(PORT_RANGE_MIN);
- when(portSecurityIpv6Rule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof TcpMatch);
- String expectedFlowId1 = "Ingress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_" + IPV6_DEST_IP_1 + "_Permit";
- String expectedFlowId2 = "Ingress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_" + IPV6_DEST_IP_2 + "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if (actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test IPv4 TCP remove with port (All TCP) and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleRemoveTcpAll2() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_TCP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(PORT_RANGE_MAX);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(PORT_RANGE_MIN);
- when(portSecurityRule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof TcpMatch);
- TcpMatch layer4Match = (TcpMatch) match.getLayer4Match();
- String expectedFlowId1 = "Ingress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_" + DEST_IP_1 + "_Permit";
- String expectedFlowId2 = "Ingress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_" + DEST_IP_2 + "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if (actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test IPv6 TCP remove with port (All TCP) and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6RemoveTcpAll2() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_TCP);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(PORT_RANGE_MAX);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(PORT_RANGE_MIN);
- when(portSecurityIpv6Rule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof TcpMatch);
- TcpMatch layer4Match = (TcpMatch) match.getLayer4Match();
- String expectedFlowId1 = "Ingress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_" + IPV6_DEST_IP_1 + "_Permit";
- String expectedFlowId2 = "Ingress_TCP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_" + IPV6_DEST_IP_2 + "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if (actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test IPv4 UDP add with port no and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleAddUdp1() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_UDP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(50);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(50);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn("0.0.0.0/24");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof UdpMatch);
- UdpMatch layer4Match = (UdpMatch) match.getLayer4Match();
- Assert.assertEquals(50, layer4Match.getUdpDestinationPort().getValue().intValue());
- int port = portSecurityRule.getSecurityRulePortMin();
- Assert.assertEquals("Ingress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS +
- "_" + port + "_0.0.0.0/24_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test IPv6 UDP add with port no and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6AddUdp1() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_UDP);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(50);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(50);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn("::/64");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof UdpMatch);
- UdpMatch layer4Match = (UdpMatch) match.getLayer4Match();
- Assert.assertEquals(50, layer4Match.getUdpDestinationPort().getValue().intValue());
- int port = portSecurityIpv6Rule.getSecurityRulePortMin();
- Assert.assertEquals("Ingress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS +
- "_" + port + "_::/64_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test IPv4 UDP remove with port no and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleRemoveUdp1() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_UDP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(50);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(50);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn("0.0.0.0/24");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof UdpMatch);
- UdpMatch layer4Match = (UdpMatch) match.getLayer4Match();
- Assert.assertEquals(50, layer4Match.getUdpDestinationPort().getValue().intValue());
- int port = portSecurityRule.getSecurityRulePortMin();
- Assert.assertEquals("Ingress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS +
- "_" + port + "_0.0.0.0/24_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test IPv6 UDP remove with port no and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6RemoveUdp1() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_UDP);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(50);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(50);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn("::/64");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof UdpMatch);
- UdpMatch layer4Match = (UdpMatch) match.getLayer4Match();
- Assert.assertEquals(50, layer4Match.getUdpDestinationPort().getValue().intValue());
- int port = portSecurityIpv6Rule.getSecurityRulePortMin();
- Assert.assertEquals("Ingress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS +
- "_" + port + "_::/64_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test IPv4 UDP add with port no and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleAddUdp2() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_UDP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(50);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(50);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn("0.0.0.0/24");
- when(portSecurityRule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof UdpMatch);
- UdpMatch layer4Match = (UdpMatch) match.getLayer4Match();
- Assert.assertEquals(50, layer4Match.getUdpDestinationPort().getValue().intValue());
- int port = portSecurityRule.getSecurityRulePortMin();
- String expectedFlowId1 = "Ingress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + port + "_" + DEST_IP_1 +
- "_Permit";
- String expectedFlowId2 = "Ingress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + port + "_" + DEST_IP_2 +
- "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if (actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test IPv6 UDP add with port no and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6AddUdp2() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_UDP);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(50);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(50);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn("::/64");
- when(portSecurityIpv6Rule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof UdpMatch);
- UdpMatch layer4Match = (UdpMatch) match.getLayer4Match();
- Assert.assertEquals(50, layer4Match.getUdpDestinationPort().getValue().intValue());
- int port = portSecurityIpv6Rule.getSecurityRulePortMin();
- String expectedFlowId1 = "Ingress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + port + "_" + IPV6_DEST_IP_1 +
- "_Permit";
- String expectedFlowId2 = "Ingress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + port + "_" + IPV6_DEST_IP_2 +
- "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if (actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test IPv4 UDP remove with port no and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleRemoveUdp2() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_UDP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(50);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(50);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn("0.0.0.0/24");
- when(portSecurityRule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof UdpMatch);
- UdpMatch layer4Match = (UdpMatch) match.getLayer4Match();
- Assert.assertEquals(50, layer4Match.getUdpDestinationPort().getValue().intValue());
- int port = portSecurityRule.getSecurityRulePortMin();
- String expectedFlowId1 = "Ingress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + port + "_" + DEST_IP_1 +
- "_Permit";
- String expectedFlowId2 = "Ingress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + port + "_" + DEST_IP_2 +
- "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if (actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test IPv6 UDP remove with port no and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6RemoveUdp2() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_UDP);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(50);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(50);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn("::/64");
- when(portSecurityIpv6Rule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof UdpMatch);
- UdpMatch layer4Match = (UdpMatch) match.getLayer4Match();
- Assert.assertEquals(50, layer4Match.getUdpDestinationPort().getValue().intValue());
- int port = portSecurityIpv6Rule.getSecurityRulePortMin();
- String expectedFlowId1 = "Ingress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + port + "_" + IPV6_DEST_IP_1 +
- "_Permit";
- String expectedFlowId2 = "Ingress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + port + "_" + IPV6_DEST_IP_2 +
- "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if (actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test IPv4 UDP add with ports (All UDP) and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleAddUdpAll1() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_UDP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(PORT_RANGE_MAX);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(PORT_RANGE_MIN);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn("0.0.0.0/24");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof UdpMatch);
- Assert.assertEquals("Ingress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_0.0.0.0/24_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test IPv6 UDP add with ports (All UDP) and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIPv6AddUdpAll1() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_UDP);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(PORT_RANGE_MAX);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(PORT_RANGE_MIN);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn("::/64");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof UdpMatch);
- Assert.assertEquals("Ingress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_::/64_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test IPv4 UDP remove with ports (All UDP) and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleRemoveUdpAll1() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_UDP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(PORT_RANGE_MAX);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(PORT_RANGE_MIN);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn("0.0.0.0/24");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof UdpMatch);
- Assert.assertEquals("Ingress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_0.0.0.0/24_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test IPv6 UDP remove with ports (All UDP) and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6RemoveUdpAll1() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_UDP);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(PORT_RANGE_MAX);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(PORT_RANGE_MIN);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn("::/64");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof UdpMatch);
- Assert.assertEquals("Ingress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_::/64_Permit", flowBuilder.getFlowName());
- }
-
- /**
- * Test IPv4 UDP add with ports (All UDP) and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleAddUdpAll2() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_UDP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(PORT_RANGE_MAX);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(PORT_RANGE_MIN);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn("0.0.0.0/24");
- when(portSecurityRule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof UdpMatch);
- String expectedFlowId1 = "Ingress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_" + DEST_IP_1 + "_Permit";
- String expectedFlowId2 = "Ingress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_" + DEST_IP_2 + "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if (actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test IPv6 UDP add with ports (All UDP) and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6AddUdpAll2() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_UDP);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(PORT_RANGE_MAX);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(PORT_RANGE_MIN);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn("::/64");
- when(portSecurityIpv6Rule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof UdpMatch);
- String expectedFlowId1 = "Ingress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_" + IPV6_DEST_IP_1 + "_Permit";
- String expectedFlowId2 = "Ingress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_" + IPV6_DEST_IP_2 + "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if (actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test IPv4 UDP remove with ports (All UDP) and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleRemoveUdpAll2() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_UDP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(PORT_RANGE_MAX);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(PORT_RANGE_MIN);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn("0.0.0.0/24");
- when(portSecurityRule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroup,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof UdpMatch);
- String expectedFlowId1 = "Ingress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_" + DEST_IP_1 + "_Permit";
- String expectedFlowId2 = "Ingress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_" + DEST_IP_2 + "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if (actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test IPv6 UDP remove with ports (All UDP) and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6RemoveUdpAll2() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_UDP);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(PORT_RANGE_MAX);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(PORT_RANGE_MIN);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn("::/64");
- when(portSecurityIpv6Rule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID, MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6,
- PORT_UUID, nodeId, false);
-
- Match match = flowBuilder.getMatch();
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Assert.assertTrue(match.getLayer4Match() instanceof UdpMatch);
- String expectedFlowId1 = "Ingress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_" + IPV6_DEST_IP_1 + "_Permit";
- String expectedFlowId2 = "Ingress_UDP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + PORT_RANGE_MIN + "_" +
- PORT_RANGE_MAX + "_" + IPV6_DEST_IP_2 + "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if (actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test ICMP add with code, type and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleAddIcmp1() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_ICMP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(10);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(10);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn("0.0.0.0/24");
-
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID,
- MAC_ADDRESS, LOCAL_PORT, securityGroup, PORT_UUID, nodeId, true);
- Match match = flowBuilder.getMatch();
- Icmpv4Match icmpv4Match = match.getIcmpv4Match();
- Assert.assertEquals(10, icmpv4Match.getIcmpv4Type().shortValue());
- Assert.assertEquals(10, icmpv4Match.getIcmpv4Code().shortValue());
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
- Short type = portSecurityRule.getSecurityRulePortMin().shortValue();
- Short code = portSecurityRule.getSecurityRulePortMax().shortValue();
- Assert.assertEquals("Ingress_ICMP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + type + "_" + code
- + "_0.0.0.0/24_Permit",
- flowBuilder.getFlowName());
- }
-
- /**
- * Test ICMPv6 add with code, type and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6AddIcmp1() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_ICMPV6);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(10);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(10);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn("::/64");
-
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID,
- MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6, PORT_UUID, nodeId, true);
-
- Match match = flowBuilder.getMatch();
- Icmpv6Match icmpv6Match = match.getIcmpv6Match();
- Assert.assertEquals(10, icmpv6Match.getIcmpv6Type().shortValue());
- Assert.assertEquals(10, icmpv6Match.getIcmpv6Code().shortValue());
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
- Short type = portSecurityIpv6Rule.getSecurityRulePortMin().shortValue();
- Short code = portSecurityIpv6Rule.getSecurityRulePortMax().shortValue();
- Assert.assertEquals("Ingress_ICMP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + type + "_" + code
- + "_::/64_Permit",
- flowBuilder.getFlowName());
- }
-
- /**
- * Test ICMP remove with code, type and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleRemoveIcmp1() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_ICMP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(20);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(20);
- when(portSecurityRule.getSecurityRuleRemoteIpPrefix()).thenReturn("0.0.0.0/24");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID,
- MAC_ADDRESS, LOCAL_PORT, securityGroup, PORT_UUID, nodeId, false);
- Match match = flowBuilder.getMatch();
- Icmpv4Match icmpv4Match = match.getIcmpv4Match();
- Assert.assertEquals(20, icmpv4Match.getIcmpv4Type().shortValue());
- Assert.assertEquals(20, icmpv4Match.getIcmpv4Code().shortValue());
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
- Short type = portSecurityRule.getSecurityRulePortMin().shortValue();
- Short code = portSecurityRule.getSecurityRulePortMax().shortValue();
- Assert.assertEquals("Ingress_ICMP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + type + "_" + code
- + "_0.0.0.0/24_Permit",
- flowBuilder.getFlowName());
- }
-
- /**
- * Test ICMPv6 remove with code, type and CIDR selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6RemoveIcmp1() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_ICMPV6);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(20);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(20);
- when(portSecurityIpv6Rule.getSecurityRuleRemoteIpPrefix()).thenReturn("::/64");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "removeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID,
- MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6, PORT_UUID, nodeId, false);
- Match match = flowBuilder.getMatch();
- Icmpv6Match icmpv6Match = match.getIcmpv6Match();
- Assert.assertEquals(20, icmpv6Match.getIcmpv6Type().shortValue());
- Assert.assertEquals(20, icmpv6Match.getIcmpv6Code().shortValue());
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
- Short type = portSecurityIpv6Rule.getSecurityRulePortMin().shortValue();
- Short code = portSecurityIpv6Rule.getSecurityRulePortMax().shortValue();
- Assert.assertEquals("Ingress_ICMP_" + SEGMENT_ID + "_" + MAC_ADDRESS + "_" + type + "_" + code
- + "_::/64_Permit",
- flowBuilder.getFlowName());
- }
-
- /**
- * Test ICMP add with code, type and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleAddIcmp2() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_ICMP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(30);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(30);
- when(portSecurityRule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID,
- MAC_ADDRESS, LOCAL_PORT, securityGroup, PORT_UUID, nodeId, true);
- Match match = flowBuilder.getMatch();
- Icmpv4Match icmpv4Match =match.getIcmpv4Match();
- Assert.assertEquals(30, icmpv4Match.getIcmpv4Type().shortValue());
- Assert.assertEquals(30, icmpv4Match.getIcmpv4Code().shortValue());
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
- Short type = portSecurityRule.getSecurityRulePortMin().shortValue();
- Short code = portSecurityRule.getSecurityRulePortMax().shortValue();
- String expectedFlowId1 = "Ingress_ICMP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + type + "_" + code + "_"
- + DEST_IP_1 + "_Permit";
- String expectedFlowId2 = "Ingress_ICMP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + type + "_" + code + "_"
- + DEST_IP_2 + "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if(actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test ICMPv6 add with code, type and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6AddIcmp2() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_ICMPV6);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(30);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(30);
- when(portSecurityIpv6Rule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer()).when(ingressAclServiceSpy, "writeFlow", any(FlowBuilder.class),
- any(NodeBuilder.class));
-
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID,
- MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6, PORT_UUID, nodeId, true);
- Match match = flowBuilder.getMatch();
- Icmpv6Match icmpv6Match =match.getIcmpv6Match();
- Assert.assertEquals(30, icmpv6Match.getIcmpv6Type().shortValue());
- Assert.assertEquals(30, icmpv6Match.getIcmpv6Code().shortValue());
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
-
- Short type = portSecurityIpv6Rule.getSecurityRulePortMin().shortValue();
- Short code = portSecurityIpv6Rule.getSecurityRulePortMax().shortValue();
- String expectedFlowId1 = "Ingress_ICMP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + type + "_" + code + "_"
- + IPV6_DEST_IP_1 + "_Permit";
- String expectedFlowId2 = "Ingress_ICMP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + type + "_" + code + "_"
- + IPV6_DEST_IP_2 + "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if(actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test ICMP remove with code, type and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleRemoveIcmp2() throws Exception {
- when(portSecurityRule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_ICMP);
- when(portSecurityRule.getSecurityRulePortMax()).thenReturn(40);
- when(portSecurityRule.getSecurityRulePortMin()).thenReturn(40);
- when(portSecurityRule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer())
- .when(ingressAclServiceSpy, "removeFlow", any(FlowBuilder.class), any(NodeBuilder.class));
-
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID,
- MAC_ADDRESS, LOCAL_PORT, securityGroup, PORT_UUID, nodeId, false);
- Match match = flowBuilder.getMatch();
- Icmpv4Match icmpv4Match = match.getIcmpv4Match();
- Assert.assertEquals(40, icmpv4Match.getIcmpv4Type().shortValue());
- Assert.assertEquals(40, icmpv4Match.getIcmpv4Code().shortValue());
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV4_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
- Short type = portSecurityRule.getSecurityRulePortMin().shortValue();
- Short code = portSecurityRule.getSecurityRulePortMax().shortValue();
- String expectedFlowId1 = "Ingress_ICMP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + type + "_" + code + "_"
- + DEST_IP_1 + "_Permit";
- String expectedFlowId2 = "Ingress_ICMP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + type + "_" + code + "_"
- + DEST_IP_2 + "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if(actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test ICMPv6 remove with code, type and remote SG selected.
- */
- @Test
- public void testProgramPortSecurityACLRuleIpv6RemoveIcmp2() throws Exception {
- when(portSecurityIpv6Rule.getSecurityRuleProtocol()).thenReturn(NeutronSecurityRule.PROTOCOL_ICMPV6);
- when(portSecurityIpv6Rule.getSecurityRulePortMax()).thenReturn(40);
- when(portSecurityIpv6Rule.getSecurityRulePortMin()).thenReturn(40);
- when(portSecurityIpv6Rule.getSecurityRemoteGroupID()).thenReturn("85cc3048-abc3-43cc-89b3-377341426ac5");
- PowerMockito.doAnswer(answer())
- .when(ingressAclServiceSpy, "removeFlow", any(FlowBuilder.class), any(NodeBuilder.class));
-
- ingressAclServiceSpy.programPortSecurityGroup(DP_ID_LONG, SEGMENT_ID,
- MAC_ADDRESS, LOCAL_PORT, securityGroupIpv6, PORT_UUID, nodeId, false);
- Match match = flowBuilder.getMatch();
- Icmpv6Match icmpv6Match = match.getIcmpv6Match();
- Assert.assertEquals(40, icmpv6Match.getIcmpv6Type().shortValue());
- Assert.assertEquals(40, icmpv6Match.getIcmpv6Code().shortValue());
- EthernetMatch ethMatch = match.getEthernetMatch();
- Assert.assertEquals(MAC_ADDRESS, ethMatch.getEthernetDestination().getAddress().getValue());
- Assert.assertEquals((long) IPV6_ETHER_TYPE, (long) ethMatch.getEthernetType().getType().getValue());
- Short type = portSecurityIpv6Rule.getSecurityRulePortMin().shortValue();
- Short code = portSecurityIpv6Rule.getSecurityRulePortMax().shortValue();
- String expectedFlowId1 = "Ingress_ICMP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + type + "_" + code + "_"
- + IPV6_DEST_IP_1 + "_Permit";
- String expectedFlowId2 = "Ingress_ICMP_" + SEGMENT_ID + "_" + MAC_ADDRESS +"_" + type + "_" + code + "_"
- + IPV6_DEST_IP_2 + "_Permit";
- String actualFlowId = flowBuilder.getFlowName();
- if(actualFlowId.equals(expectedFlowId1) || actualFlowId.equals(expectedFlowId2)) {
- Assert.assertTrue(true);
- } else {
- Assert.assertTrue(false);
- }
- }
-
- /**
- * Test IPv4 invalid ether type test case.
- */
- @Test
- public void testProgramPortSecurityACLRuleInvalidEther() throws Exception {
- when(portSecurityRule.getSecurityRuleEthertype()).thenReturn("IP");
-
- ingressAclServiceSpy.programPortSecurityGroup(1554L, "2", MAC_ADDRESS, 124, securityGroup,PORT_UUID, nodeId, false);
-
- verify(writeTransaction, times(0)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(writeTransaction, times(0)).submit();
- verify(commitFuture, times(0)).get();
- }
-
- /**
- * Test IPv4 invalid direction type test case.
- */
- @Test
- public void testProgramPortSecurityACLRuleInvalidDirection() throws Exception {
- when(portSecurityRule.getSecurityRuleDirection()).thenReturn("edgress");
-
- ingressAclServiceSpy.programPortSecurityGroup(1554L, "2", MAC_ADDRESS, 124, securityGroup,PORT_UUID, nodeId, false);
-
- verify(writeTransaction, times(0)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(writeTransaction, times(0)).submit();
- verify(commitFuture, times(0)).get();
- }
-
- /**
- * Test With isConntrackEnabled false
- */
- @Test
- public void testProgramFixedSecurityACLAdd2() throws Exception {
- when(securityServices.isConntrackEnabled()).thenReturn(false);
-
- ingressAclServiceSpy.programFixedSecurityGroup(1554L, "2", DHCP_MAC_ADDRESS, 1, MAC_ADDRESS, true);
-
- verify(writeTransaction, times(3)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class), eq(true));
- verify(writeTransaction, times(3)).submit();
- verify(commitFuture, times(3)).checkedGet();
- }
- /**
- * Test With isConntrackEnabled false
- */
- @Test
- public void testProgramFixedSecurityACLRemove2() throws Exception {
- when(securityServices.isConntrackEnabled()).thenReturn(false);
-
- ingressAclServiceSpy.programFixedSecurityGroup(1554L, "2", DHCP_MAC_ADDRESS, 1, MAC_ADDRESS, false);
-
- verify(writeTransaction, times(3)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(writeTransaction, times(3)).submit();
- verify(commitFuture, times(3)).get();
- }
- /**
- * Test With isConntrackEnabled true
- */
- @Test
- public void testProgramFixedSecurityACLAdd4() throws Exception {
- when(securityServices.isConntrackEnabled()).thenReturn(true);
-
- ingressAclServiceSpy.programFixedSecurityGroup(1554L, "2", DHCP_MAC_ADDRESS, 1, MAC_ADDRESS, true);
-
- verify(writeTransaction, times(8)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class), eq(true));
- verify(writeTransaction, times(8)).submit();
- verify(commitFuture, times(8)).checkedGet();
- }
- /**
- * Test With isConntrackEnabled true
- */
- @Test
- public void testProgramFixedSecurityACLRemove4() throws Exception {
- when(securityServices.isConntrackEnabled()).thenReturn(true);
-
- ingressAclServiceSpy.programFixedSecurityGroup(1554L, "2", DHCP_MAC_ADDRESS, 1, MAC_ADDRESS, false);
-
- verify(writeTransaction, times(8)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(writeTransaction, times(8)).submit();
- verify(commitFuture, times(8)).get();
- }
-
-}
+++ /dev/null
-/*
- * Copyright © 2015, 2017 Inocybe 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.netvirt.openstack.netvirt.providers.openflow13.services;
-
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyBoolean;
-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.util.concurrent.atomic.AtomicBoolean;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
-import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
-import org.opendaylight.netvirt.openstack.netvirt.providers.NetvirtProvidersProvider;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.PipelineOrchestrator;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.powermock.api.support.membermodification.MemberModifier;
-
-import com.google.common.base.Optional;
-import com.google.common.util.concurrent.CheckedFuture;
-
-/**
- * Unit test fort {@link L2ForwardingService}
- */
-@RunWith(MockitoJUnitRunner.class)
-@SuppressWarnings("unchecked")
-public class L2FowardingServiceTest {
-
- @InjectMocks private L2ForwardingService l2ForwardingService = new L2ForwardingService(Service.ARP_RESPONDER);
-
- @Mock private DataBroker dataBroker;
- @Mock private PipelineOrchestrator orchestrator;
-
- @Mock private WriteTransaction writeTransaction;
- @Mock private ReadOnlyTransaction readOnlyTransaction;
- @Mock private CheckedFuture<Void, TransactionCommitFailedException> commitFuture;
-
- private static final String SEGMENTATION_ID = "2";
- private static final String MAC_ADDRESS = "87:1D:5E:02:40:B8";
- private static final Long DPID = 122L;
- private static final Long LOCAL_PORT = 451L;
- private static final Long ETH_PORT = 564L;
- private static final Long OF_PORT_OUT = 5698L;
-
- @Before
- public void setUp() throws Exception {
- when(writeTransaction.submit()).thenReturn(commitFuture);
-
- when(dataBroker.newWriteOnlyTransaction()).thenReturn(writeTransaction);
- when(dataBroker.newReadOnlyTransaction()).thenReturn(readOnlyTransaction);
-
- CheckedFuture future = mock(CheckedFuture.class);
- when(readOnlyTransaction.read(any(LogicalDatastoreType.class), any(InstanceIdentifier.class))).thenReturn(future);
-
- Optional<Flow> data = mock(Optional.class);
- when(future.get()).thenReturn(data);
-
- //when(mdsalConsumer.getDataBroker()).thenReturn(dataBroker);
-
- when(orchestrator.getNextServiceInPipeline(any(Service.class))).thenReturn(Service.ARP_RESPONDER);
-
- NetvirtProvidersProvider netvirtProvider = mock(NetvirtProvidersProvider.class);
- MemberModifier.field(NetvirtProvidersProvider.class, "hasProviderEntityOwnership").set(netvirtProvider, new AtomicBoolean(true));
-
- }
-
- /**
- * Test method {@link L2ForwardingService#programLocalUcastOut(Long, String, Long, String, boolean)}
- */
- @Test
- public void testProgramLoacalUcastOut() throws Exception {
- l2ForwardingService.programLocalUcastOut(DPID, SEGMENTATION_ID, LOCAL_PORT, MAC_ADDRESS, true);
- verify(writeTransaction, times(2)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class), anyBoolean());
- verify(writeTransaction, times(1)).submit();
- verify(commitFuture, times(1)).get();
-
- l2ForwardingService.programLocalUcastOut(DPID, SEGMENTATION_ID, LOCAL_PORT, MAC_ADDRESS, false);
- verify(writeTransaction, times(1)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(writeTransaction, times(2)).submit();
- verify(commitFuture, times(2)).get(); // 1 + 1 above
- }
-
- /**
- * Test method {@link L2ForwardingService#programLocalVlanUcastOut(Long, String, Long, String, boolean)}
- */
- @Test
- public void testProgramLocalVlanUcastOut() throws Exception {
- l2ForwardingService.programLocalVlanUcastOut(DPID, SEGMENTATION_ID, 124L, MAC_ADDRESS, true);
- verify(writeTransaction, times(2)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class), anyBoolean());
- verify(writeTransaction, times(1)).submit();
- verify(commitFuture, times(1)).get();
-
- l2ForwardingService.programLocalVlanUcastOut(DPID, SEGMENTATION_ID, LOCAL_PORT, MAC_ADDRESS, false);
- verify(writeTransaction, times(1)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(writeTransaction, times(2)).submit();
- verify(commitFuture, times(2)).get(); // 1 + 1 above
- }
-
- /**
- * Test method {@link L2ForwardingService#programLocalBcastOut(Long, String, Long, boolean)}
- */
- @Test
- public void testProgramLocalBcastOut() throws Exception {
- l2ForwardingService.programLocalBcastOut(DPID, SEGMENTATION_ID, LOCAL_PORT, true);
- verify(writeTransaction, times(2)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class), anyBoolean());
- verify(writeTransaction, times(1)).submit();
- verify(commitFuture, times(1)).get();
-
- l2ForwardingService.programLocalBcastOut(DPID, SEGMENTATION_ID, LOCAL_PORT, false);
- verify(writeTransaction, times(1)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(writeTransaction, times(2)).submit();
- verify(commitFuture, times(2)).get(); // 1 + 1 above
- }
-
- /**--------------------------------- TODO go deeper in test
- * Test method {@link L2ForwardingService#programLocalVlanBcastOut(Long, String, Long, Long, boolean)}
- */
- @Test
- public void testProgramLocalVlanBcastOut() throws Exception {
- l2ForwardingService.programLocalVlanBcastOut(DPID, SEGMENTATION_ID, LOCAL_PORT, ETH_PORT, true);
- verify(writeTransaction, times(2)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class), anyBoolean());
- verify(writeTransaction, times(1)).submit();
- verify(commitFuture, times(1)).get();
-
- l2ForwardingService.programLocalVlanBcastOut(DPID, SEGMENTATION_ID, LOCAL_PORT, ETH_PORT, false);
- verify(writeTransaction, times(1)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(writeTransaction, times(2)).submit();
- verify(commitFuture, times(2)).get(); // 1 + 1 above
- }
-
- /**
- * Test method {@link L2ForwardingService#programLocalVlanTableMiss(Long, String, boolean)}
- */
- @Test
- public void testProgramLocalVlanTableMiss() throws Exception {
- l2ForwardingService.programLocalVlanTableMiss(DPID, SEGMENTATION_ID, true);
- verify(writeTransaction, times(2)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class), anyBoolean());
- verify(writeTransaction, times(1)).submit();
- verify(commitFuture, times(1)).get();
-
- l2ForwardingService.programLocalVlanTableMiss(DPID, SEGMENTATION_ID, false);
- verify(writeTransaction, times(1)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(writeTransaction, times(2)).submit();
- verify(commitFuture, times(2)).get(); // 1 + 1 above
- }
-
- /**
- * Test method {@link L2ForwardingService#programTunnelOut(Long, String, Long, String, boolean)}
- */
- @Test
- public void testProgramTunnelOut() throws Exception {
- l2ForwardingService.programTunnelOut(DPID, SEGMENTATION_ID, OF_PORT_OUT, MAC_ADDRESS, true);
- verify(writeTransaction, times(2)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class), anyBoolean());
- verify(writeTransaction, times(1)).submit();
- verify(commitFuture, times(1)).get();
-
- l2ForwardingService.programTunnelOut(DPID, SEGMENTATION_ID, OF_PORT_OUT, MAC_ADDRESS, false);
- verify(writeTransaction, times(1)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(writeTransaction, times(2)).submit();
- verify(commitFuture, times(2)).get(); // 1 + 1 above
- }
-
- /**
- * Test method {@link L2ForwardingService#programVlanOut(Long, String, Long, String, boolean)}
- */
- @Test
- public void testProgramVlanOut() throws Exception {
- l2ForwardingService.programVlanOut(DPID, SEGMENTATION_ID, ETH_PORT, MAC_ADDRESS, true);
- verify(writeTransaction, times(2)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class), anyBoolean());
- verify(writeTransaction, times(1)).submit();
- verify(commitFuture, times(1)).get();
-
- l2ForwardingService.programVlanOut(DPID, SEGMENTATION_ID, ETH_PORT, MAC_ADDRESS, false);
- verify(writeTransaction, times(1)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(writeTransaction, times(2)).submit();
- verify(commitFuture, times(2)).get(); // 1 + 1 above
- }
-
- /**--------------------------------- TODO go deeper in test
- * Test method {@link L2ForwardingService#programTunnelFloodOut(Long, String, Long, boolean)}
- */
- @Test
- public void testProgramTunnelFloodOut() throws Exception {
- l2ForwardingService.programTunnelFloodOut(DPID, SEGMENTATION_ID, OF_PORT_OUT, true);
- verify(writeTransaction, times(2)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class), anyBoolean());
- verify(writeTransaction, times(1)).submit();
- verify(commitFuture, times(1)).get();
-
- l2ForwardingService.programTunnelFloodOut(DPID, SEGMENTATION_ID, OF_PORT_OUT, false);
- verify(writeTransaction, times(1)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(writeTransaction, times(2)).submit();
- verify(commitFuture, times(2)).get(); // 1 + 1 above
- }
-
- /**
- * Test method {@link L2ForwardingService#programVlanMiss(Long, String, Long, boolean)}
- */
- @Test
- public void testProgramVlanMiss() throws Exception {
- l2ForwardingService.programVlanMiss(DPID, SEGMENTATION_ID, ETH_PORT, true);
- verify(writeTransaction, times(2)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class), anyBoolean());
- verify(writeTransaction, times(1)).submit();
- verify(commitFuture, times(1)).get();
-
- l2ForwardingService.programVlanMiss(DPID, SEGMENTATION_ID, ETH_PORT, false);
- verify(writeTransaction, times(1)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(writeTransaction, times(2)).submit();
- verify(commitFuture, times(2)).get(); // 1 + 1 above
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Inocybe 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.netvirt.openstack.netvirt.providers.openflow13.services;
-
-import org.junit.Test;
-
-/**
- * Unit test for {@link L2RewriteService}
- */
-public class L2RewriteServiceTest {
-
- @Test
- public void test() {
- // TODO nothing has been done in L2RewriteService class yet.
- }
-
-}
+++ /dev/null
-/*
- * Copyright © 2015, 2017 Inocybe 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.netvirt.openstack.netvirt.providers.openflow13.services;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyBoolean;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import java.net.InetAddress;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
-import org.opendaylight.netvirt.openstack.netvirt.api.StatusCode;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.Status;
-import org.opendaylight.netvirt.openstack.netvirt.providers.NetvirtProvidersProvider;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.PipelineOrchestrator;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.powermock.api.support.membermodification.MemberModifier;
-
-import com.google.common.util.concurrent.CheckedFuture;
-
-/**
- * Unit test fort {@link L3ForwardingService}
- */
-@RunWith(MockitoJUnitRunner.class)
-@SuppressWarnings("unchecked")
-public class L3FowardingServiceTest {
-
- @InjectMocks private L3ForwardingService l3ForwardingService = new L3ForwardingService();
-
- @Mock private DataBroker dataBroker;
- @Mock private PipelineOrchestrator orchestrator;
-
- @Mock private WriteTransaction writeTransaction;
- @Mock private CheckedFuture<Void, TransactionCommitFailedException> commitFuture;
-
- private static final String SEGMENTATION_ID = "2";
- private static final String HOST_ADDRESS = "127.0.0.1";
- private static final String MAC_ADDRESS = "87:1D:5E:02:40:B7";
-
- @Before
- public void setUp() throws Exception {
- when(writeTransaction.submit()).thenReturn(commitFuture);
-
- when(dataBroker.newWriteOnlyTransaction()).thenReturn(writeTransaction);
-
- when(orchestrator.getNextServiceInPipeline(any(Service.class))).thenReturn(Service.ARP_RESPONDER);
-
- NetvirtProvidersProvider netvirtProvider = mock(NetvirtProvidersProvider.class);
- MemberModifier.field(NetvirtProvidersProvider.class, "hasProviderEntityOwnership").set(netvirtProvider, new AtomicBoolean(true));
-
- }
-
- /**
- * Test method {@link L3ForwardingService#programForwardingTableEntry(Long, String, InetAddress, String, Action)}
- */
- @Test
- public void testProgramForwardingTableEntry() throws Exception {
- InetAddress address = mock(InetAddress.class);
- when(address.getHostAddress()).thenReturn(HOST_ADDRESS);
-
- assertEquals("Error, did not return the expected StatusCode",
- new Status(StatusCode.SUCCESS),
- l3ForwardingService.programForwardingTableEntry(123L,
- SEGMENTATION_ID, address, MAC_ADDRESS, Action.ADD));
- verify(writeTransaction, times(2)).put(any(LogicalDatastoreType.class),
- any(InstanceIdentifier.class), any(Node.class), anyBoolean());
- verify(writeTransaction, times(1)).submit();
- verify(commitFuture, times(1)).get();
-
- assertEquals("Error, did not return the expected StatusCode",
- new Status(StatusCode.SUCCESS),
- l3ForwardingService.programForwardingTableEntry(123L,
- SEGMENTATION_ID, address, MAC_ADDRESS, Action.DELETE));
- verify(writeTransaction, times(1)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(writeTransaction, times(2)).submit();
- verify(commitFuture, times(2)).get(); // 1 + 1 above
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Inocybe 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.netvirt.openstack.netvirt.providers.openflow13.services;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyBoolean;
-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.util.HashMap;
-import java.util.Map;
-
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
-import org.opendaylight.netvirt.openstack.netvirt.NetworkHandler;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.LoadBalancerConfiguration;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.openstack.netvirt.api.Status;
-import org.opendaylight.netvirt.openstack.netvirt.api.StatusCode;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.PipelineOrchestrator;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-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 com.google.common.util.concurrent.CheckedFuture;
-import org.powermock.api.support.membermodification.MemberModifier;
-
-/**
- * Unit test fort {@link LoadBalancerService}
- */
-@RunWith(MockitoJUnitRunner.class)
-@SuppressWarnings("unchecked")
-public class LoadBalancerServiceTest {
-
- @InjectMocks private LoadBalancerService loadBalancerService = new LoadBalancerService(Service.ARP_RESPONDER);
-
- @Mock private DataBroker dataBroker;
- @Mock private PipelineOrchestrator orchestrator;
-
- @Mock private WriteTransaction writeTransaction;
- @Mock private CheckedFuture<Void, TransactionCommitFailedException> commitFuture;
-
- @Mock private LoadBalancerConfiguration lbConfig;
- @Mock private LoadBalancerConfiguration.LoadBalancerPoolMember member;
- @Mock private Node node;
-
- private static final String SEGMENTATION_ID = "2";
- private static final String HOST_ADDRESS = "127.0.0.1";
- private static final String MAC_ADDRESS = "87:1D:5E:02:40:B7";
-
- @Before
- public void setUp() throws Exception {
- when(writeTransaction.submit()).thenReturn(commitFuture);
-
- when(dataBroker.newWriteOnlyTransaction()).thenReturn(writeTransaction);
-
- when(orchestrator.getNextServiceInPipeline(any(Service.class))).thenReturn(Service.ARP_RESPONDER);
-
- Map<String, LoadBalancerConfiguration.LoadBalancerPoolMember> members = new HashMap<>();
- members.put("key", member);
-
- when(lbConfig.isValid()).thenReturn(true);
- when(lbConfig.getVip()).thenReturn(HOST_ADDRESS);
- when(lbConfig.getMembers()).thenReturn(members);
- when(lbConfig.getProviderNetworkType()).thenReturn(NetworkHandler.NETWORK_TYPE_VXLAN, NetworkHandler.NETWORK_TYPE_VLAN);
- when(lbConfig.getProviderSegmentationId()).thenReturn(SEGMENTATION_ID);
-
- when(member.getIP()).thenReturn(HOST_ADDRESS);
- when(member.getIndex()).thenReturn(1);
- when(member.getMAC()).thenReturn(MAC_ADDRESS);
-
- Southbound southbound = mock(Southbound.class);
- when(southbound.getDataPathId(any(Node.class))).thenReturn(123L);
- MemberModifier.field(LoadBalancerService.class, "southbound").set(loadBalancerService, southbound);
- }
- /**
- * Test method {@link LoadBalancerService#programLoadBalancerPoolMemberRules(Node, LoadBalancerConfiguration, LoadBalancerConfiguration.LoadBalancerPoolMember, Action)}
- */
- @Test
- public void testprogramLoadBalancerPoolMemberRules() throws Exception {
- Assert.assertEquals("Error, did not return the expected StatusCode", new Status(StatusCode.BADREQUEST), loadBalancerService.programLoadBalancerPoolMemberRules(node, null, null, Action.ADD));
-
- Assert.assertEquals("Error, did not return the expected StatusCode", new Status(StatusCode.NOTIMPLEMENTED), loadBalancerService.programLoadBalancerPoolMemberRules(node, lbConfig, member, Action.DELETE));
- verify(writeTransaction, times(2)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class), anyBoolean());
- verify(writeTransaction, times(1)).submit();
- verify(commitFuture, times(1)).get();
-
- Assert.assertEquals("Error, did not return the expected StatusCode", new Status(StatusCode.SUCCESS), loadBalancerService.programLoadBalancerPoolMemberRules(node, lbConfig, member, Action.ADD));
- verify(writeTransaction, times(8)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class), anyBoolean());
- verify(writeTransaction, times(4)).submit();
- verify(commitFuture, times(4)).get();
- }
-
- /**
- * Test method {@link LoadBalancerService#programLoadBalancerRules(Node, LoadBalancerConfiguration, Action)}
- */
- @Test
- public void testProgramLoadBalancerRules() throws Exception {
- Assert.assertEquals("Error, did not return the expected StatusCode", new Status(StatusCode.BADREQUEST), loadBalancerService.programLoadBalancerRules(node, null, Action.ADD));
-
- Assert.assertEquals("Error, did not return the expected StatusCode", new Status(StatusCode.NOTIMPLEMENTED), loadBalancerService.programLoadBalancerRules(node, lbConfig, Action.UPDATE));
-
- Assert.assertEquals("Error, did not return the expected StatusCode", new Status(StatusCode.SUCCESS), loadBalancerService.programLoadBalancerRules(node, lbConfig, Action.ADD));
- verify(writeTransaction, times(6)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class), anyBoolean());
- verify(writeTransaction, times(3)).submit();
- verify(commitFuture, times(3)).get();
-
- Assert.assertEquals("Error, did not return the expected StatusCode", new Status(StatusCode.SUCCESS), loadBalancerService.programLoadBalancerRules(node, lbConfig, Action.DELETE));
- verify(writeTransaction, times(3)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(writeTransaction, times(6)).submit();
- verify(commitFuture, times(6)).get(); // 3 + 3 before
- }
-}
+++ /dev/null
-/*
- * Copyright © 2015, 2017 Inocybe 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.netvirt.openstack.netvirt.providers.openflow13.services;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyBoolean;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import java.net.InetAddress;
-
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.Status;
-import org.opendaylight.netvirt.openstack.netvirt.api.StatusCode;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.PipelineOrchestrator;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-
-import com.google.common.util.concurrent.CheckedFuture;
-
-/**
- * Unit test fort {@link OutboundNatService}
- */
-@RunWith(MockitoJUnitRunner.class)
-@SuppressWarnings("unchecked")
-public class OutboundNatServiceTest {
-
- @InjectMocks private OutboundNatService outboundNatService = new OutboundNatService();
-
- @Mock private DataBroker dataBroker;
- @Mock private PipelineOrchestrator orchestrator;
-
- @Mock private WriteTransaction writeTransaction;
- @Mock private CheckedFuture<Void, TransactionCommitFailedException> commitFuture;
-
- private static final String SEGMENTATION_ID = "2";
- private static final String HOST_ADDRESS = "127.0.0.1";
- private static final String HOST_ADDRESS_PREFIX = "127.0.0.1/24";
- private static final String MAC_ADDRESS = "87:1D:5E:02:40:B7";
-
- @Before
- public void setUp() throws Exception {
- when(writeTransaction.submit()).thenReturn(commitFuture);
- when(writeTransaction.submit()).thenReturn(commitFuture);
-
- when(dataBroker.newWriteOnlyTransaction()).thenReturn(writeTransaction);
-
- when(orchestrator.getNextServiceInPipeline(any(Service.class))).thenReturn(Service.ARP_RESPONDER);
- }
-
- /**
- * Test method {@link OutboundNatService#programIpRewriteRule(Long, String, String, InetAddress, String, String, InetAddress, Long, Action)}
- */
- @Test
- public void testProgramIpRewriteRule() throws Exception {
- InetAddress address = mock(InetAddress.class);
- when(address.getHostAddress()).thenReturn(HOST_ADDRESS);
-
- Assert.assertEquals("Error, did not return the expected StatusCode", new Status(StatusCode.SUCCESS),
- outboundNatService.programIpRewriteRule(123L, SEGMENTATION_ID, MAC_ADDRESS, address,
- MAC_ADDRESS, MAC_ADDRESS, address,
- 10L, Action.ADD));
- verify(writeTransaction, times(2)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class), anyBoolean());
- verify(writeTransaction, times(1)).submit();
- verify(commitFuture, times(1)).get();
-
- Assert.assertEquals("Error, did not return the expected StatusCode", new Status(StatusCode.SUCCESS),
- outboundNatService.programIpRewriteRule(123L, SEGMENTATION_ID, MAC_ADDRESS, address,
- MAC_ADDRESS, MAC_ADDRESS, address,
- 10L, Action.DELETE));
- verify(writeTransaction, times(1)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(writeTransaction, times(2)).submit();
- verify(commitFuture, times(2)).get(); // 1 + 1 above
- }
-
- /**
- * Test method {@link OutboundNatService#programIpRewriteExclusion(Long, String, String, Action)}
- */
- @Test
- public void testProgramIpRewriteExclusion() throws Exception {
- Assert.assertEquals("Error, did not return the expected StatusCode", new Status(StatusCode.SUCCESS), outboundNatService.programIpRewriteExclusion(123L, SEGMENTATION_ID, HOST_ADDRESS_PREFIX, Action.ADD));
- verify(writeTransaction, times(2)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class), anyBoolean());
- verify(writeTransaction, times(1)).submit();
- verify(commitFuture, times(1)).get();
-
- Assert.assertEquals("Error, did not return the expected StatusCode", new Status(StatusCode.SUCCESS), outboundNatService.programIpRewriteExclusion(123L, SEGMENTATION_ID, HOST_ADDRESS_PREFIX, Action.DELETE));
- verify(writeTransaction, times(1)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(writeTransaction, times(2)).submit();
- verify(commitFuture, times(2)).get(); // 1 + 1 above
- }
-}
+++ /dev/null
-/*
- * Copyright © 2015, 2017 Inocybe 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.netvirt.openstack.netvirt.providers.openflow13.services;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyBoolean;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import java.net.InetAddress;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.Status;
-import org.opendaylight.netvirt.openstack.netvirt.api.StatusCode;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.PipelineOrchestrator;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-
-import com.google.common.util.concurrent.CheckedFuture;
-
-/**
- * Unit test fort {@link RoutingService}
- */
-@RunWith(MockitoJUnitRunner.class)
-@SuppressWarnings("unchecked")
-public class RoutingServiceTest {
-
- @InjectMocks private RoutingService routingService = new RoutingService();
-
- @Mock private DataBroker dataBroker;
- @Mock private PipelineOrchestrator orchestrator;
-
- @Mock private WriteTransaction writeTransaction;
- @Mock private CheckedFuture<Void, TransactionCommitFailedException> commitFuture;
-
- private static final String SEGMENTATION_ID = "2";
- private static final String HOST_ADDRESS = "127.0.0.1";
- private static final String MAC_ADDRESS = "87:1D:5E:02:40:B8";
-
- @Before
- public void setUp() throws Exception {
- when(writeTransaction.submit()).thenReturn(commitFuture);
-
- when(dataBroker.newWriteOnlyTransaction()).thenReturn(writeTransaction);
-
- when(orchestrator.getNextServiceInPipeline(any(Service.class))).thenReturn(Service.ARP_RESPONDER);
- }
-
- /**
- * Test method {@link RoutingService#programRouterInterface(Long, String, String, String, InetAddress, int, Action)}
- */
- @Test
- public void testProgramRouterInterface() throws Exception {
- InetAddress address = mock(InetAddress.class);
- when(address.getHostAddress()).thenReturn(HOST_ADDRESS);
-
- assertEquals("Error, did not return the expected StatusCode",
- new Status(StatusCode.SUCCESS),
- routingService.programRouterInterface(123L,
- SEGMENTATION_ID, SEGMENTATION_ID, MAC_ADDRESS, address, 1, Action.ADD));
- verify(writeTransaction, times(2)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class), anyBoolean());
- verify(writeTransaction, times(1)).submit();
- verify(commitFuture, times(1)).get();
-
- assertEquals("Error, did not return the expected StatusCode",
- new Status(StatusCode.SUCCESS),
- routingService.programRouterInterface(123L,
- SEGMENTATION_ID, SEGMENTATION_ID, MAC_ADDRESS, address, 1, Action.DELETE));
- verify(writeTransaction, times(1)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(writeTransaction, times(2)).submit();
- verify(commitFuture, times(2)).get(); // 1 + 1 above
- }
-
- /**
- * Test method {@link RoutingService#programDefaultRouteEntry(Long, String, String, InetAddress, Action)}
- */
- @Test
- public void testProgramDefaultRouteEntry() throws Exception {
- InetAddress address = mock(InetAddress.class);
- when(address.getHostAddress()).thenReturn(HOST_ADDRESS);
-
- assertEquals("Error, did not return the expected StatusCode",
- new Status(StatusCode.SUCCESS),
- routingService.programDefaultRouteEntry(123L,
- SEGMENTATION_ID, MAC_ADDRESS, address, Action.ADD));
- verify(writeTransaction, times(2)).put(any(LogicalDatastoreType.class),
- any(InstanceIdentifier.class), any(Node.class), anyBoolean());
- verify(writeTransaction, times(1)).submit();
- verify(commitFuture, times(1)).get();
-
- assertEquals("Error, did not return the expected StatusCode",
- new Status(StatusCode.SUCCESS),
- routingService.programDefaultRouteEntry(123L,
- SEGMENTATION_ID, MAC_ADDRESS, address, Action.DELETE));
- verify(writeTransaction, times(1)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(writeTransaction, times(2)).submit();
- verify(commitFuture, times(2)).get(); // 1 + 1 above
- }
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-Copyright © 2015 Red Hat, Inc. and others. All rights reserved.
-
-This program and the accompanying materials are made available under the
-terms of the Eclipse Public License v1.0 which accompanies this distribution,
-and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <parent>
- <groupId>org.opendaylight.mdsal</groupId>
- <artifactId>binding-parent</artifactId>
- <version>0.11.0-SNAPSHOT</version>
- <relativePath/>
- </parent>
-
- <modelVersion>4.0.0</modelVersion>
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>openstack.net-virt-sfc-api</artifactId>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>bundle</packaging>
-
- <properties>
- <sfc.project.version>0.5.0-SNAPSHOT</sfc.project.version>
- </properties>
-
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>ietf-inet-types-2013-07-15</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>ietf-yang-types-20130715</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>yang-ext</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>ietf-access-control-list</artifactId>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <extensions>true</extensions>
- <configuration>
- <instructions>
- <Export-Package>
- org.opendaylight.yang.gen.v1.*,
- org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.acl.rev150105,
- org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.classifier.rev150105,
- org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.classifier.rev150105.Classifiers,
- org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.rev150105,
- </Export-Package>
- </instructions>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-module netvirt-sfc-acl {
- yang-version 1;
- namespace "urn:opendaylight:params:xml:ns:yang:netvirt:sfc:acl";
- prefix "acl";
-
- import ietf-access-control-list { prefix ietf-acl; revision-date 2016-02-18; }
- import yang-ext { prefix ext; }
-
- revision "2015-01-05" {
- description "Initial revision of netvirt extensions to ietf-acl model";
- }
-
- augment "/ietf-acl:access-lists/ietf-acl:acl/ietf-acl:access-list-entries/ietf-acl:ace/ietf-acl:matches" {
- description "Neutron network uuid";
- ext:augment-identifier "neutron-network";
- leaf network-uuid {
- type string;
- }
- }
-
- grouping netvirtsfc-acl-actions {
- leaf sfc-name {
- type string;
- }
- leaf sfp-name {
- type string;
- }
- leaf rsp-name {
- type string;
- }
- leaf render-rsp {
- type boolean;
- default "false";
- }
- }
-
- augment "/ietf-acl:access-lists/ietf-acl:acl/ietf-acl:access-list-entries/ietf-acl:ace/ietf-acl:actions" {
- description "Redirect traffic to SFC identified by either SFC, SFP or RSP";
- ext:augment-identifier "redirect-to-sfc";
- uses netvirtsfc-acl-actions;
- }
-}
+++ /dev/null
-module netvirt-sfc-classifier {
- yang-version 1;
- namespace "urn:opendaylight:params:xml:ns:yang:netvirt:sfc:classifier";
- prefix "classifier";
-
- import ietf-inet-types { prefix inet;}
- import ietf-yang-types { prefix yang;}
-
- revision "2015-01-05" {
- description "Initial revision of netvirt classifier model";
- }
-
- container classifiers {
- description "Classifier container which represents the ACL being applied,
- attachment point and the associated chain";
-
- list classifier {
- description "A list of SFC classifiers";
- key "name";
- leaf name {
- type string;
- }
- leaf acl {
- type string;
- }
- container sffs {
- list sff {
- description "The classifier will be attached to these SFFs";
- key "name";
- leaf name {
- type string;
- }
- }
- }
- container bridges {
- list bridge {
- key "name";
- leaf name {
- type string;
- }
- leaf direction {
- type enumeration {
- enum ingress;
- enum egress;
- }
- }
- }
- }
- }
- }
-}
+++ /dev/null
-module netvirt-sfc {
- yang-version 1;
- namespace "urn:opendaylight:params:xml:ns:yang:netvirt:sfc";
- prefix "netvirt-sfc";
-
- revision "2015-01-05" {
- description "Initial revision of the netvirt sfc model";
- }
-
- container sfc {
- leaf name {
- type string;
- }
- }
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-Copyright © 2015 Red Hat, Inc. and others. All rights reserved.
-
-This program and the accompanying materials are made available under the
-terms of the Eclipse Public License v1.0 which accompanies this distribution,
-and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>odlparent-lite</artifactId>
- <version>2.0.0</version>
- <relativePath/>
- </parent>
-
- <modelVersion>4.0.0</modelVersion>
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>openstack.net-virt-sfc-artifacts</artifactId>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>pom</packaging>
-
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>openstack.net-virt-sfc-api</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>openstack.net-virt-sfc-impl</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>openstack.net-virt-sfc-features</artifactId>
- <version>${project.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- </dependencies>
- </dependencyManagement>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-Copyright © 2015 Red Hat, Inc. and others. All rights reserved.
-
-This program and the accompanying materials are made available under the
-terms of the Eclipse Public License v1.0 which accompanies this distribution,
-and is available at http://www.eclipse.org/legal/epl-v10.html INTERNAL
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>features-parent</artifactId>
- <version>1.9.0</version>
- <relativePath/>
- </parent>
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>openstack.net-virt-sfc-features</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <modelVersion>4.0.0</modelVersion>
- <properties>
- <configfile.directory>etc/opendaylight/karaf</configfile.directory>
- <controller.mdsal.version>1.6.0-SNAPSHOT</controller.mdsal.version>
- <dluxapps.version>0.6.0-SNAPSHOT</dluxapps.version>
- <mdsal.model.version>0.11.0-SNAPSHOT</mdsal.model.version>
- <openflowplugin.version>0.5.0-SNAPSHOT</openflowplugin.version>
- <ovsdb.version>1.5.0-SNAPSHOT</ovsdb.version>
- <restconf.version>1.6.0-SNAPSHOT</restconf.version>
- <sfc.version>0.6.0-SNAPSHOT</sfc.version>
- </properties>
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.dluxapps</groupId>
- <artifactId>features-dluxapps</artifactId>
- <classifier>features</classifier>
- <version>${dluxapps.version}</version>
- <type>xml</type>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>features-mdsal</artifactId>
- <version>${controller.mdsal.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>features-mdsal-model</artifactId>
- <version>${mdsal.model.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.netconf</groupId>
- <artifactId>features-restconf</artifactId>
- <version>${restconf.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.openflowplugin</groupId>
- <artifactId>features-openflowplugin</artifactId>
- <version>${openflowplugin.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>features-netvirt</artifactId>
- <version>${project.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.ovsdb</groupId>
- <artifactId>southbound-features</artifactId>
- <version>${ovsdb.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.openflowplugin</groupId>
- <artifactId>features-openflowplugin-extension</artifactId>
- <version>${openflowplugin.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.sfc</groupId>
- <artifactId>features-sfc</artifactId>
- <version>${sfc.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>openstack.net-virt-sfc-impl</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>openstack.net-virt-sfc-api</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>utils.mdsal-utils</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>utils.mdsal-openflow</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>utils.servicehelper</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>utils.netvirt-it-utils</artifactId>
- <version>${project.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.ovsdb</groupId>
- <artifactId>utils.ovsdb-it-utils</artifactId>
- <version>${ovsdb.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.ovsdb</groupId>
- <artifactId>utils.mdsal-utils</artifactId>
- <version>${ovsdb.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.ovsdb</groupId>
- <artifactId>utils.southbound-utils</artifactId>
- <version>${ovsdb.version}</version>
- </dependency>
- </dependencies>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- vi: set et smarttab sw=4 tabstop=4: -->
-<!--
-Copyright © 2015 Red Hat, Inc. and others. All rights reserved.
-
-This program and the accompanying materials are made available under the
-terms of the Eclipse Public License v1.0 which accompanies this distribution,
-and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-<features name="odl-ovsdb-sfc-${project.version}" xmlns="http://karaf.apache.org/xmlns/features/v1.2.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://karaf.apache.org/xmlns/features/v1.2.0 http://karaf.apache.org/xmlns/features/v1.2.0">
- <repository>mvn:org.opendaylight.controller/features-mdsal/{{VERSION}}/xml/features</repository>
- <repository>mvn:org.opendaylight.dluxapps/features-dluxapps/{{VERSION}}/xml/features</repository>
- <repository>mvn:org.opendaylight.mdsal.model/features-mdsal-model/{{VERSION}}/xml/features</repository>
- <repository>mvn:org.opendaylight.netconf/features-restconf/{{VERSION}}/xml/features</repository>
- <repository>mvn:org.opendaylight.netvirt/features-netvirt/{{VERSION}}/xml/features</repository>
- <repository>mvn:org.opendaylight.openflowplugin/features-openflowplugin/{{VERSION}}/xml/features</repository>
- <repository>mvn:org.opendaylight.openflowplugin/features-openflowplugin-extension/{{VERSION}}/xml/features</repository>
- <repository>mvn:org.opendaylight.ovsdb/southbound-features/{{VERSION}}/xml/features</repository>
- <repository>mvn:org.opendaylight.sfc/features-sfc/{{VERSION}}/xml/features</repository>
- <feature name='odl-ovsdb-sfc-api' version='${project.version}' description='OpenDaylight :: ovsdb-sfc :: api'>
- <feature version='${mdsal.model.version}'>odl-mdsal-models</feature>
- <bundle>mvn:org.opendaylight.netvirt/openstack.net-virt-sfc-api/{{VERSION}}</bundle>
- </feature>
- <feature name='odl-ovsdb-sfc' version='${project.version}' description='OpenDaylight :: ovsdb-sfc'>
- <feature version='${controller.mdsal.version}'>odl-mdsal-broker</feature>
- <feature version="${openflowplugin.version}">odl-openflowplugin-flow-services</feature>
- <feature version='${openflowplugin.version}'>odl-openflowplugin-nxm-extensions</feature>
- <feature version='${ovsdb.version}'>odl-ovsdb-southbound-impl</feature>
- <feature version='${project.version}'>odl-ovsdb-openstack</feature>
- <feature version='${sfc.version}'>odl-sfc-openflow-renderer</feature>
- <feature version='${project.version}'>odl-ovsdb-sfc-api</feature>
- <bundle>mvn:org.opendaylight.netvirt/utils.servicehelper/{{VERSION}}</bundle>
- <bundle>mvn:org.opendaylight.netvirt/utils.mdsal-utils/{{VERSION}}</bundle>
- <bundle>mvn:org.opendaylight.ovsdb/utils.mdsal-utils/{{VERSION}}</bundle>
- <bundle>mvn:org.opendaylight.ovsdb/utils.southbound-utils/{{VERSION}}</bundle>
- <bundle>mvn:org.opendaylight.netvirt/openstack.net-virt-sfc-impl/{{VERSION}}</bundle>
- </feature>
- <feature name='odl-ovsdb-sfc-rest' version='${project.version}' description='OpenDaylight :: ovsdb-sfc :: REST'>
- <feature version="${project.version}">odl-ovsdb-sfc</feature>
- <feature version="${restconf.version}">odl-restconf</feature>
- </feature>
- <feature name='odl-ovsdb-sfc-ui' version='${project.version}' description='OpenDaylight :: ovsdb-sfc :: UI'>
- <feature version="${project.version}">odl-ovsdb-sfc-rest</feature>
- <feature version="${restconf.version}">odl-mdsal-apidocs</feature>
- <feature version="${dluxapps.version}">odl-dluxapps-yangman</feature>
- </feature>
- <feature name='odl-ovsdb-sfc-test' version='${project.version}' description='OpenDaylight :: ovsdb-sfc-test'>
- <bundle>mvn:org.opendaylight.netvirt/utils.netvirt-it-utils/{{VERSION}}</bundle>
- <bundle>mvn:org.opendaylight.ovsdb/utils.ovsdb-it-utils/{{VERSION}}</bundle>
- <bundle>mvn:org.opendaylight.netvirt/utils.mdsal-utils/{{VERSION}}</bundle>
- <bundle>mvn:org.opendaylight.ovsdb/utils.mdsal-utils/{{VERSION}}</bundle>
- <bundle>mvn:org.opendaylight.ovsdb/utils.southbound-utils/{{VERSION}}</bundle>
- <feature version='${project.version}'>odl-ovsdb-sfc</feature>
- </feature>
-</features>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright © 2017 Red Hat, Inc. and others.
-
- 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
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>feature-repo-parent</artifactId>
- <version>1.9.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>openstack.net-virt-sfc-features4</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>feature</packaging>
-
- <name>ODL :: netvirt :: ${project.artifactId}</name>
-
- <dependencies>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-ovsdb-sfc-api</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-ovsdb-sfc</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-ovsdb-sfc-rest</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-ovsdb-sfc-ui</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-ovsdb-sfc-test</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- </dependencies>
-</project>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright © 2017 Red Hat, Inc. and others.
-
- 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
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>single-feature-parent</artifactId>
- <version>1.9.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>odl-ovsdb-sfc-api</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>feature</packaging>
-
- <name>OpenDaylight :: ovsdb-sfc :: api</name>
-
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>odl-mdsal-models</artifactId>
- <version>0.11.0-SNAPSHOT</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>openstack.net-virt-sfc-api</artifactId>
- <version>${project.version}</version>
- </dependency>
- </dependencies>
-</project>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright © 2017 Red Hat, Inc. and others.
-
- 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
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>single-feature-parent</artifactId>
- <version>1.9.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>odl-ovsdb-sfc-rest</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>feature</packaging>
-
- <name>OpenDaylight :: ovsdb-sfc :: REST</name>
-
- <dependencies>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-ovsdb-sfc</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.netconf</groupId>
- <artifactId>odl-restconf</artifactId>
- <version>1.6.0-SNAPSHOT</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- </dependencies>
-</project>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright © 2017 Red Hat, Inc. and others.
-
- 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
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>single-feature-parent</artifactId>
- <version>1.9.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>odl-ovsdb-sfc-test</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>feature</packaging>
-
- <name>OpenDaylight :: ovsdb-sfc-test</name>
-
- <dependencies>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-ovsdb-sfc</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>utils.netvirt-it-utils</artifactId>
- <version>${project.version}</version>
- </dependency>
- </dependencies>
-</project>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright © 2017 Red Hat, Inc. and others.
-
- 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
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>single-feature-parent</artifactId>
- <version>1.9.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>odl-ovsdb-sfc-ui</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>feature</packaging>
-
- <name>OpenDaylight :: ovsdb-sfc :: UI</name>
-
- <dependencies>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-ovsdb-sfc-rest</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.netconf</groupId>
- <artifactId>odl-mdsal-apidocs</artifactId>
- <version>1.6.0-SNAPSHOT</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.dluxapps</groupId>
- <artifactId>odl-dluxapps-yangman</artifactId>
- <version>0.6.0-SNAPSHOT</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- </dependencies>
-</project>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright © 2017 Red Hat, Inc. and others.
-
- 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
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>single-feature-parent</artifactId>
- <version>1.9.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>odl-ovsdb-sfc</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>feature</packaging>
-
- <name>OpenDaylight :: ovsdb-sfc</name>
-
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>odl-mdsal-broker</artifactId>
- <version>1.6.0-SNAPSHOT</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.openflowplugin</groupId>
- <artifactId>odl-openflowplugin-flow-services</artifactId>
- <version>0.5.0-SNAPSHOT</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.openflowplugin</groupId>
- <artifactId>odl-openflowplugin-nxm-extensions</artifactId>
- <version>0.5.0-SNAPSHOT</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.ovsdb</groupId>
- <artifactId>odl-ovsdb-southbound-impl</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-ovsdb-openstack</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.sfc</groupId>
- <artifactId>odl-sfc-openflow-renderer</artifactId>
- <version>0.6.0-SNAPSHOT</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-ovsdb-sfc-api</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>utils.servicehelper</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>utils.mdsal-utils</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.ovsdb</groupId>
- <artifactId>utils.mdsal-utils</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.ovsdb</groupId>
- <artifactId>utils.southbound-utils</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>openstack.net-virt-sfc-impl</artifactId>
- <version>${project.version}</version>
- </dependency>
- </dependencies>
-</project>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright © 2017 Red Hat, Inc. and others.
-
- 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
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>odlparent-lite</artifactId>
- <version>2.0.0</version>
- <relativePath/>
- </parent>
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>openstack.net-virt-sfc-features-aggregator</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <packaging>pom</packaging>
-
- <modules>
- <module>net-virt-sfc-features</module>
- <module>net-virt-sfc-features4</module>
- <module>odl-ovsdb-sfc-api</module>
- <module>odl-ovsdb-sfc</module>
- <module>odl-ovsdb-sfc-rest</module>
- <module>odl-ovsdb-sfc-ui</module>
- <module>odl-ovsdb-sfc-test</module>
- </modules>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- vi: set et smarttab sw=4 tabstop=4: -->
-<!--
-Copyright © 2015, 2016 Red Hat, Inc. and others. All rights reserved.
-
-This program and the accompanying materials are made available under the
-terms of the Eclipse Public License v1.0 which accompanies this distribution,
-and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
-
- <parent>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-parent</artifactId>
- <version>0.7.0-SNAPSHOT</version>
- <relativePath/>
- </parent>
-
- <modelVersion>4.0.0</modelVersion>
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>openstack.net-virt-sfc-impl</artifactId>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>bundle</packaging>
-
- <properties>
- <openflowplugin.version>0.5.0-SNAPSHOT</openflowplugin.version>
- <ovsdb.version>1.5.0-SNAPSHOT</ovsdb.version>
- <sfc.version>0.6.0-SNAPSHOT</sfc.version>
- <sonar.jacoco.itReportPath>../it/target/jacoco-it.exec</sonar.jacoco.itReportPath>
- </properties>
-
- <dependencies>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>openstack.net-virt</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>openstack.net-virt-providers</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.ovsdb</groupId>
- <artifactId>southbound-api</artifactId>
- <version>${ovsdb.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.ovsdb</groupId>
- <artifactId>southbound-impl</artifactId>
- <version>${ovsdb.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>utils.mdsal-utils</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>utils.mdsal-openflow</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>utils.servicehelper</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.openflowplugin</groupId>
- <artifactId>openflowplugin-extension-nicira</artifactId>
- <version>${openflowplugin.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.openflowplugin</groupId>
- <artifactId>openflowjava-extension-nicira</artifactId>
- <version>${openflowplugin.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.openflowplugin.model</groupId>
- <artifactId>model-flow-base</artifactId>
- <version>${openflowplugin.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.openflowplugin.model</groupId>
- <artifactId>model-flow-service</artifactId>
- <version>${openflowplugin.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>ietf-topology</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>ietf-packet-fields</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>iana-if-type-2014-05-08</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.sfc</groupId>
- <artifactId>sfc-model</artifactId>
- <version>${sfc.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.sfc</groupId>
- <artifactId>sfc-provider</artifactId>
- <version>${sfc.version}</version>
- </dependency>
- <dependency>
- <groupId>org.codehaus.sonar-plugins.java</groupId>
- <artifactId>sonar-jacoco-listeners</artifactId>
- <version>${sonar-jacoco-listeners.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-simple</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-core</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>openstack.net-virt-sfc-api</artifactId>
- <version>${project.version}</version>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <extensions>true</extensions>
- <configuration>
- <instructions>
- <Embed-Dependency>utils.mdsal-openflow;type=!pom;inline=false</Embed-Dependency>
- <Embed-Transitive>true</Embed-Transitive>
- <Export-Package>
- org.opendaylight.netvirt.openstack.netvirt.sfc,
- org.opendaylight.netvirt.openstack.netvirt.sfc.workaround.services
- </Export-Package>
- </instructions>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <!--<propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>-->
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
- <configuration>
- <properties>
- <property>
- <name>listener</name>
- <value>org.sonar.java.jacoco.JUnitListener</value>
- </property>
- </properties>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-/*
- * Copyright (c) 2013, 2016 Dell, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc;
-
-import java.util.Collection;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ThreadFactory;
-
-import javax.annotation.Nonnull;
-
-import com.google.common.base.Preconditions;
-import com.google.common.util.concurrent.ThreadFactoryBuilder;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
-import org.opendaylight.controller.md.sal.binding.api.DataTreeChangeListener;
-import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
-import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Data-tree listener which delegates data processing to a {@link INetvirtSfcDataProcessor}.
- */
-public class DelegatingDataTreeListener<T extends DataObject> implements AutoCloseable, DataTreeChangeListener<T> {
- private static final Logger LOG = LoggerFactory.getLogger(DelegatingDataTreeListener.class);
- protected INetvirtSfcOF13Provider provider;
- private static final ThreadFactory threadFactory = new ThreadFactoryBuilder()
- .setNameFormat("NV-SfcDTL-%d").build();
- private final ExecutorService executorService = Executors.newFixedThreadPool(1, threadFactory);
- private final INetvirtSfcDataProcessor<T> dataProcessor;
- private ListenerRegistration<DelegatingDataTreeListener<T>> listenerRegistration;
-
- public DelegatingDataTreeListener(INetvirtSfcOF13Provider provider, INetvirtSfcDataProcessor<T> dataProcessor,
- DataBroker db, DataTreeIdentifier<T> treeId) {
- this.provider = Preconditions.checkNotNull(provider, "provider can not be null!");
- this.dataProcessor = Preconditions.checkNotNull(dataProcessor, "Data processor can not be null!");
- registerListener(Preconditions.checkNotNull(db, "Data broker can not be null!"),
- Preconditions.checkNotNull(treeId, "Tree identifier can not be null!"));
- }
-
- private void registerListener(final DataBroker db, DataTreeIdentifier<T> treeId) {
- try {
- LOG.info("Registering Data Change Listener for {}", getClass().getSimpleName());
- listenerRegistration = db.registerDataTreeChangeListener(treeId, this);
- } catch (final Exception e) {
- LOG.warn("{} DataChange listener registration fail!", getClass().getSimpleName(), e);
- throw new IllegalStateException("DataTreeListener startup fail! System needs restart.", e);
- }
- }
-
- private void processChanges(Collection<DataTreeModification<T>> changes) {
- LOG.info("onDataTreeChanged: Received Data Tree Changed ...", changes);
- for (DataTreeModification<T> change : changes) {
- final InstanceIdentifier<T> key = change.getRootPath().getRootIdentifier();
- final DataObjectModification<T> mod = change.getRootNode();
- LOG.info("onDataTreeChanged: Received Data Tree Changed Update of Type={} for Key={}",
- mod.getModificationType(), key);
- switch (mod.getModificationType()) {
- case DELETE:
- dataProcessor.remove(key, mod.getDataBefore());
- break;
- case SUBTREE_MODIFIED:
- dataProcessor.update(key, mod.getDataBefore(), mod.getDataAfter());
- break;
- case WRITE:
- if (mod.getDataBefore() == null) {
- dataProcessor.add(key, mod.getDataAfter());
- } else {
- dataProcessor.update(key, mod.getDataBefore(), mod.getDataAfter());
- }
- break;
- default:
- throw new IllegalArgumentException("Unhandled modification type " + mod.getModificationType());
- }
- }
- }
-
- @Override
- public void onDataTreeChanged(@Nonnull final Collection<DataTreeModification<T>> changes) {
- Preconditions.checkNotNull(changes, "Changes may not be null!");
- executorService.submit(() -> processChanges(changes));
- }
-
- @Override
- public void close() {
- if (listenerRegistration != null) {
- listenerRegistration.close();
- listenerRegistration = null;
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2016 Dell, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc;
-
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-
-/**
- * netvirt-sfc-dcl processor
- * org.opendaylight.ovsdb.openstack.netvirt.sfc
- */
-public interface INetvirtSfcDataProcessor<D extends DataObject> {
-
- /**
- * Method removes DataObject which is identified by InstanceIdentifier.
- *
- * @param identifier - the whole path to DataObject
- * @param del - DataObject for removing
- */
- void remove(InstanceIdentifier<D> identifier, D del);
-
- /**
- * Method updates the original DataObject to the update DataObject.
- * Both are identified by same InstanceIdentifier.
- *
- * @param identifier - the whole path to DataObject
- * @param original - original DataObject (for update)
- * @param update - changed DataObject (contain updates)
- */
- void update(InstanceIdentifier<D> identifier, D original, D update);
-
- /**
- * Method adds the DataObject which is identified by InstanceIdentifier
- * to device.
- *
- * @param identifier - the whole path to new DataObject
- * @param add - new DataObject
- */
- void add(InstanceIdentifier<D> identifier, D add);
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Dell, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc;
-
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.rendered.service.paths.RenderedServicePath;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.Acl;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.classifier.rev150105.classifiers.classifier.Bridges;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.classifier.rev150105.classifiers.classifier.bridges.Bridge;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.classifier.rev150105.classifiers.classifier.sffs.Sff;
-import org.osgi.framework.ServiceReference;
-
-/**
- * Open vSwitch OpenFlow 1.3 Networking Provider for Netvirt SFC
- * @author Arun Yerra
- */
-public interface INetvirtSfcOF13Provider {
-
- /**
- * Method installs the OF rules corresponding to rules within ACL
- * on a given Service Function Forwarder. DataObject which is identified by InstanceIdentifier.
- *
- * @param bridge - Service Function Forwarder
- * @param acl - Access list includes rules that need to be installed in a SFF.
- */
- void addClassifierRules(Bridge bridge, Acl acl);
- void addClassifierRules(Bridges bridges, Acl acl);
-
- /**
- * Method removes the OF rules corresponding to rules within ACL
- * on a given Service Function Forwarder. DataObject which is identified by InstanceIdentifier.
- *
- * @param sff - Service Function Forwarder
- * @param acl - Access list includes rules that need to be installed in a SFF.
- */
- void removeClassifierRules(Sff sff, Acl acl);
-
- void addClassifierRules(Acl acl);
- void removeClassifierRules(Acl acl);
- void setSfcClassifierService(ISfcClassifierService sfcClassifierService);
- void setDependencies(ServiceReference serviceReference);
- void updateRsp(RenderedServicePath change);
- void removeRsp(RenderedServicePath change);
- void addRsp(RenderedServicePath change);
-}
+++ /dev/null
-/*
- * Copyright © 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc;
-
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.Matches;
-
-public interface ISfcClassifierService {
- void programIngressClassifier(long dataPathId, String ruleName, Matches matches, long nsp, short nsi,
- NshUtils nshHeader, long vxGpeOfPort, String rspName, boolean write);
-
- void programSfcTable(long dataPathId, long vxGpeOfPort, short goToTableId, boolean write);
-
- void programEgressClassifier1(long dataPathId, long vxGpeOfPort, long nsp, short nsi,
- int tunnelOfPort, int tunnelId, short gotoTableId, boolean write);
-
- void programEgressClassifier(long dataPathId, long vxGpeOfPort, long nsp, short nsi,
- long sfOfPort, int tunnelId, String rspName, boolean write);
-
- void programEgressClassifierBypass(long dataPathId, long vxGpeOfPort, long nsp, short nsi,
- long sfOfPort, int tunnelId, String rspName, boolean write);
-
- void program_sfEgress(long dataPathId, int dstPort, String rspName, boolean write);
-
- void program_sfIngress(long dataPathId, int dstPort, long sfOfPort,
- String ipAddress, String sfDplName, String rspName, boolean write);
-
- void programStaticArpEntry(long dataPathId, long ofPort, String macAddressStr,
- String ipAddress, String rspName, boolean write);
-
- void clearFlows(DataBroker dataBroker, String rspName);
-}
+++ /dev/null
-/*
- * Copyright © 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc;
-
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.Matches;
-
-public interface ISfcStandaloneClassifierService {
- void programIngressClassifier(long dataPathId, String ruleName, Matches matches,
- NshUtils nshHeader, long vxGpeOfPort, boolean write);
-
- void programSfcTable(long dataPathId, long vxGpeOfPort, short goToTableId, boolean write);
-
- void programEgressClassifier1(long dataPathId, long vxGpeOfPort, long nsp, short nsi,
- int tunnelOfPort, int tunnelId, short gotoTableId, boolean write);
-
- void programEgressClassifier(long dataPathId, long vxGpeOfPort, long nsp, short nsi,
- long sfOfPort, int tunnelId, boolean write);
-
- void programEgressClassifierBypass(long dataPathId, long vxGpeOfPort, long nsp, short nsi,
- long sfOfPort, int tunnelId, boolean write);
-
- void program_sfEgress(long dataPathId, int dstPort, boolean write);
-
- void program_sfIngress(long dataPathId, int dstPort, long sfOfPort,
- String ipAddress, String sfDplName, boolean write);
-
- void programStaticArpEntry(long dataPathId, long ofPort, String macAddressStr,
- String ipAddress, boolean write);
-}
+++ /dev/null
-/*
- * Copyright © 2015, 2016 Dell, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc;
-
-import com.google.common.base.Preconditions;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.Acl;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-
-/**
- * Data processor for AccessList.
- */
-public class NetvirtSfcAclDataProcessor implements INetvirtSfcDataProcessor<Acl> {
- private final INetvirtSfcOF13Provider provider;
-
- /**
- * {@link NetvirtSfcAclDataProcessor} constructor.
- * @param provider OpenFlow 1.3 Provider
- */
- public NetvirtSfcAclDataProcessor(final INetvirtSfcOF13Provider provider) {
- this.provider = Preconditions.checkNotNull(provider, "Provider can not be null!");
- }
-
- @Override
- public void remove(final InstanceIdentifier<Acl> identifier,
- final Acl change) {
- Preconditions.checkNotNull(change, "Removed object can not be null!");
- provider.removeClassifierRules(change);
- }
-
- @Override
- public void update(final InstanceIdentifier<Acl> identifier,
- final Acl original, final Acl change) {
- Preconditions.checkNotNull(original, "Updated original object can not be null!");
- Preconditions.checkNotNull(original, "Updated update object can not be null!");
- remove(identifier, original);
- provider.addClassifierRules(change);
- }
-
- @Override
- public void add(final InstanceIdentifier<Acl> identifier,
- final Acl change) {
- Preconditions.checkNotNull(change, "Added object can not be null!");
- provider.addClassifierRules(change);
- }
-}
+++ /dev/null
-/*
- * Copyright © 2015, 2016 Dell, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc;
-
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.AccessLists;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.Acl;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-
-/**
- * Data tree listener for AccessList.
- */
-public class NetvirtSfcAclListener extends DelegatingDataTreeListener<Acl> {
- /**
- * {@link NetvirtSfcAclListener} constructor.
- * @param provider OpenFlow 1.3 Provider
- * @param db MdSal {@link DataBroker}
- */
- public NetvirtSfcAclListener(final INetvirtSfcOF13Provider provider, final DataBroker db) {
- super(provider, new NetvirtSfcAclDataProcessor(provider), db,
- new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION,
- InstanceIdentifier.create(AccessLists.class).child(Acl.class)));
- }
-}
+++ /dev/null
-/*
- * Copyright © 2015, 2016 Dell, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc;
-
-import com.google.common.base.Preconditions;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.netvirt.utils.mdsal.utils.MdsalUtils;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.AccessLists;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.AclBase;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.Acl;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.AclKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.classifier.rev150105.classifiers
- .Classifier;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Data processor for Classifier.
- */
-public class NetvirtSfcClassifierDataProcessor implements INetvirtSfcDataProcessor<Classifier> {
- private static final Logger LOG = LoggerFactory.getLogger(NetvirtSfcClassifierDataProcessor.class);
- private final MdsalUtils mdsalUtils;
- private final INetvirtSfcOF13Provider provider;
-
- /**
- * {@link NetvirtSfcClassifierDataProcessor} constructor.
- * @param provider OpenFlow 1.3 Provider
- * @param db MdSal {@link DataBroker}
- */
- public NetvirtSfcClassifierDataProcessor(final INetvirtSfcOF13Provider provider, final DataBroker db) {
- this.provider = Preconditions.checkNotNull(provider, "Provider can not be null!");
- Preconditions.checkNotNull(db, "DataBroker can not be null!");
- mdsalUtils = new MdsalUtils(db);
- }
-
- @Override
- public void remove(final InstanceIdentifier<Classifier> identifier,
- final Classifier change) {
- Preconditions.checkNotNull(change, "Added object can not be null!");
- String aclName = change.getAcl();
- // Read the ACL information from data store and make sure it exists.
- Acl acl = mdsalUtils.read(LogicalDatastoreType.CONFIGURATION, getIetfAclIid(aclName));
- if (acl == null) {
- LOG.debug("IETF ACL with name ={} is not yet configured. skip this operation", aclName);
- return;
- }
-
- provider.removeClassifierRules(acl);
- }
-
- @Override
- public void update(final InstanceIdentifier<Classifier> identifier,
- final Classifier original, final Classifier change) {
- //TODO
-
- }
-
- @Override
- public void add(final InstanceIdentifier<Classifier> identifier,
- final Classifier change) {
- Preconditions.checkNotNull(change, "Added object can not be null!");
- String aclName = change.getAcl();
- // Read the ACL information from data store and make sure it exists.
- Acl acl = mdsalUtils.read(LogicalDatastoreType.CONFIGURATION, getIetfAclIid(aclName));
- if (acl == null) {
- LOG.debug("IETF ACL with name ={} is not yet configured. skip this operation", aclName);
- return;
- }
-
- provider.addClassifierRules(acl);
- }
-
- private InstanceIdentifier<Acl> getIetfAclIid(String aclName) {
- return InstanceIdentifier.create(AccessLists.class).child(Acl.class, new AclKey(aclName, AclBase.class));
- }
-}
+++ /dev/null
-/*
- * Copyright © 2015, 2016 Dell, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc;
-
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.classifier.rev150105.Classifiers;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.classifier.rev150105.classifiers.Classifier;
-
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-
-/**
- * Data tree listener for Classifier.
- *
- * @author Arun Yerra
- */
-public class NetvirtSfcClassifierListener extends DelegatingDataTreeListener<Classifier> {
- /**
- * {@link NetvirtSfcClassifierListener} constructor.
- * @param provider OpenFlow 1.3 Provider
- * @param db MdSal {@link DataBroker}
- */
- public NetvirtSfcClassifierListener(final INetvirtSfcOF13Provider provider, final DataBroker db) {
- super(provider, new NetvirtSfcClassifierDataProcessor(provider, db), db,
- new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION,
- InstanceIdentifier.create(Classifiers.class).child(Classifier.class)));
- }
-}
+++ /dev/null
-/*
- * Copyright © 2015, 2016 Dell, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc;
-
-import com.google.common.base.Preconditions;
-import java.util.Dictionary;
-import java.util.Hashtable;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.AbstractServiceInstance;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.OF13Provider;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.netvirt.openstack.netvirt.sfc.standalone.openflow13.NetvirtSfcStandaloneOF13Provider;
-import org.opendaylight.netvirt.openstack.netvirt.sfc.standalone.openflow13.services.SfcClassifierService;
-import org.opendaylight.netvirt.openstack.netvirt.sfc.workaround.NetvirtSfcWorkaroundOF13Provider;
-import org.opendaylight.netvirt.utils.mdsal.utils.MdsalUtils;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.impl.config.rev160517.NetvirtSfcConfig;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class NetvirtSfcProvider implements AutoCloseable {
- private static final Logger LOG = LoggerFactory.getLogger(NetvirtSfcProvider.class);
-
- private AutoCloseable aclListener;
- private AutoCloseable classifierListener;
- private AutoCloseable rspListener;
-
- private final Boolean addSfFlows;
- private final String of13Provider;
-
- private final DataBroker dataBroker;
- private final BundleContext bundleContext;
-
- private ServiceRegistration<?> reg;
-
- public NetvirtSfcProvider(final DataBroker dataBroker, final NetvirtSfcConfig netvirtSfcConfig, final BundleContext bundleContext) {
- LOG.info("NetvirtSfcProvider started");
- this.dataBroker = dataBroker;
- this.addSfFlows = Preconditions.checkNotNull(netvirtSfcConfig.isAddsflows(), "AddsFlow must be configured");
- this.of13Provider = Preconditions.checkNotNull(netvirtSfcConfig.getOf13provider(), " Provider type must be configured");
- this.bundleContext = bundleContext;
- }
-
- public void start() {
- LOG.info("NetvirtSfcProvider Session Initiated");
-
- MdsalUtils mdsalUtils = new MdsalUtils(dataBroker);
- SfcUtils sfcUtils = new SfcUtils(mdsalUtils);
-
- // Allocate provider based on config
- INetvirtSfcOF13Provider provider;
- if (of13Provider.equals("standalone")) {
- provider = new NetvirtSfcStandaloneOF13Provider(dataBroker);
- } else {
- provider = new NetvirtSfcWorkaroundOF13Provider(dataBroker, mdsalUtils, sfcUtils, addSfFlows);
- }
- aclListener = new NetvirtSfcAclListener(provider, dataBroker);
- classifierListener = new NetvirtSfcClassifierListener(provider, dataBroker);
- rspListener = new RspListener(provider, dataBroker);
-
- addToPipeline(provider);
- provider.setDependencies(null);
- }
-
- @Override
- public void close() throws Exception {
- LOG.info("NetvirtSfcProvider Closed");
- if (aclListener != null) {
- aclListener.close();
- }
- if (classifierListener != null) {
- classifierListener.close();
- }
- if (rspListener != null) {
- rspListener.close();
- }
- if (reg != null) {
- reg.unregister();
- }
- }
-
- private void addToPipeline(INetvirtSfcOF13Provider provider) {
- if (provider instanceof NetvirtSfcStandaloneOF13Provider) {
- SfcClassifierService sfcClassifierService =
- new SfcClassifierService();
- reg = registerService(bundleContext, ISfcClassifierService.class.getName(),
- sfcClassifierService, Service.SFC_CLASSIFIER);
- sfcClassifierService.setDependencies(bundleContext, null);
- } else {
- org.opendaylight.netvirt.openstack.netvirt.sfc.workaround.services.SfcClassifierService sfcClassifierService =
- new org.opendaylight.netvirt.openstack.netvirt.sfc.workaround.services.SfcClassifierService();
- reg = registerService(bundleContext, ISfcClassifierService.class.getName(),
- sfcClassifierService, Service.SFC_CLASSIFIER);
- sfcClassifierService.setDependencies(bundleContext, null);
- }
-
- //provider.setSfcClassifierService(sfcClassifierService);
- }
-
- private ServiceRegistration<?> registerService(BundleContext bundleContext, String[] interfaces,
- Dictionary<String, Object> properties, Object impl) {
- ServiceRegistration<?> serviceRegistration = bundleContext.registerService(interfaces, impl, properties);
- return serviceRegistration;
- }
-
- private ServiceRegistration<?> registerService(BundleContext bundleContext, String interfaceClassName,
- Object impl, Object serviceProperty) {
- Dictionary<String, Object> properties = new Hashtable<>();
- properties.put(AbstractServiceInstance.SERVICE_PROPERTY, serviceProperty);
- properties.put(Constants.PROVIDER_NAME_PROPERTY, OF13Provider.NAME);
- return registerService(bundleContext,
- new String[] {AbstractServiceInstance.class.getName(),interfaceClassName},
- properties, impl);
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (c) 2015 Dell, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc;
-
-import com.google.common.net.InetAddresses;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
-
-
-/**
- * Open Vswitch DB OpenFlow 1.3 Networking Provider for Netvirt SFC Utilities.
- * @author Arun Yerra
- */
-public class NshUtils {
- private Ipv4Address nshTunIpDst;
- private PortNumber nshTunUdpPort;
- private long nshNsp;
- private short nshNsi;
- private long nshMetaC1;
- private long nshMetaC2;
-
- public NshUtils() {
- super();
- }
-
- /**
- * {@link NshUtils} constructor.
- * @param nshTunIpDst Tunnel Destination IP
- * @param nshTunUdpPort Tunnel Transport Port
- * @param nshNsp Service Path Id
- * @param nshNsi Service Path Index
- * @param nshMetaC1 End point ID
- * @param nshMetaC2 Tunnel Id.
- */
- public NshUtils(Ipv4Address nshTunIpDst, PortNumber nshTunUdpPort,
- long nshNsp, short nshNsi, long nshMetaC1,
- long nshMetaC2) {
- super();
- this.nshTunIpDst = nshTunIpDst;
- this.nshTunUdpPort = nshTunUdpPort;
- this.nshNsp = nshNsp;
- this.nshNsi = nshNsi;
- this.nshMetaC1 = nshMetaC1;
- this.nshMetaC2 = nshMetaC2;
- }
-
- /*
- * @return the nshTunIpDst
- */
- public Ipv4Address getNshTunIpDst() {
- return nshTunIpDst;
- }
-
- /*
- * @param nshTunIpDst the nshTunIpDst to set
- */
- public void setNshTunIpDst(Ipv4Address nshTunIpDst) {
- this.nshTunIpDst = nshTunIpDst;
- }
-
- /*
- * @return the nshTunUdpPort
- */
- public PortNumber getNshTunUdpPort() {
- return nshTunUdpPort;
- }
-
- /*
- * @param nshTunUdpPort the nshTunUdpPort to set
- */
- public void setNshTunUdpPort(PortNumber nshTunUdpPort) {
- this.nshTunUdpPort = nshTunUdpPort;
- }
-
- /*
- * @return the nshNsp
- */
- public long getNshNsp() {
- return nshNsp;
- }
-
- /*
- * @param nshNsp the nshNsp to set
- */
- public void setNshNsp(long nshNsp) {
- this.nshNsp = nshNsp;
- }
-
- /*
- * @return the nshNsi
- */
- public short getNshNsi() {
- return nshNsi;
- }
-
- /*
- * @param nshNsi the nshNsi to set
- */
- public void setNshNsi(short nshNsi) {
- this.nshNsi = nshNsi;
- }
-
- /*
- * @return the nshMetaC1
- */
- public long getNshMetaC1() {
- return nshMetaC1;
- }
-
- /*
- * @param nshMetaC1 the nshMetaC1 to set
- */
- public void setNshMetaC1(long nshMetaC1) {
- this.nshMetaC1 = nshMetaC1;
- }
-
- /*
- * @return the nshMetaC2
- */
- public long getNshMetaC2() {
- return nshMetaC2;
- }
-
- /*
- * @param nshMetaC2 the nshMetaC2 to set
- */
- public void setNshMetaC2(long nshMetaC2) {
- this.nshMetaC2 = nshMetaC2;
- }
-
- public static Long convertIpAddressToLong(Ipv4Address ipv4Address) {
- return (InetAddresses.coerceToInteger(InetAddresses.forString(ipv4Address.getValue()))) & 0xFFFFFFFFL;
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#toString()
- */
- @Override
- public String toString() {
- return "NshUtils [nshTunIpDst=" + nshTunIpDst + ", nshTunUdpPort=" + nshTunUdpPort + ", nshNsp=" + nshNsp
- + ", nshNsi=" + nshNsi + ", nshMetaC1=" + nshMetaC1 + ", nshMetaC2=" + nshMetaC2 + "]";
- }
-}
+++ /dev/null
-/*
- * Copyright © 2015, 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt.sfc;
-
-import com.google.common.base.Preconditions;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.rendered.service.paths.RenderedServicePath;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-
-/**
- * Data processor for {@link RenderedServicePath}
- */
-public class RspDataProcessor implements INetvirtSfcDataProcessor<RenderedServicePath> {
- private final INetvirtSfcOF13Provider provider;
-
- public RspDataProcessor(final INetvirtSfcOF13Provider provider) {
- this.provider = Preconditions.checkNotNull(provider, "Provider can not be null!");
- }
-
- @Override
- public void remove(final InstanceIdentifier<RenderedServicePath> identifier, final RenderedServicePath change) {
- Preconditions.checkNotNull(change, "Removed object can not be null!");
- provider.removeRsp(change);
- }
-
- @Override
- public void update(final InstanceIdentifier<RenderedServicePath> identifier, final RenderedServicePath original,
- RenderedServicePath change) {
- Preconditions.checkNotNull(original, "Updated original object can not be null!");
- Preconditions.checkNotNull(original, "Updated update object can not be null!");
- remove(identifier, original);
- provider.addRsp(change);
- }
-
- @Override
- public void add(final InstanceIdentifier<RenderedServicePath> identifier, final RenderedServicePath change) {
- Preconditions.checkNotNull(change, "Created object can not be null!");
- provider.addRsp(change);
- }
-}
+++ /dev/null
-/*
- * Copyright © 2015, 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt.sfc;
-
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.RenderedServicePaths;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.rendered.service.paths.RenderedServicePath;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-
-/**
- * Data tree listener for {@link RenderedServicePath}
- */
-public class RspListener extends DelegatingDataTreeListener<RenderedServicePath> {
- public RspListener(final INetvirtSfcOF13Provider provider, final DataBroker db) {
- super(provider, new RspDataProcessor(provider), db, new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL,
- InstanceIdentifier.create(RenderedServicePaths.class).child(RenderedServicePath.class)));
- }
-}
+++ /dev/null
-/*
- * Copyright © 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc;
-
-import java.util.List;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.netvirt.utils.mdsal.utils.MdsalUtils;
-import org.opendaylight.sfc.provider.api.SfcProviderServiceForwarderAPI;
-import org.opendaylight.sfc.provider.api.SfcProviderServiceFunctionAPI;
-import org.opendaylight.sfc.provider.api.SfcProviderServicePathAPI;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.RspName;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.SfName;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.SffName;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.RenderedServicePaths;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.rendered.service.paths.RenderedServicePath;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.rendered.service.paths.RenderedServicePathKey;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.rendered.service.paths.rendered.service.path.RenderedServicePathHop;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sf.rev140701.ServiceFunctions;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sf.rev140701.service.functions.ServiceFunction;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sf.rev140701.service.functions.ServiceFunctionKey;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.service.function.forwarders.ServiceFunctionForwarder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfp.rev140701.ServiceFunctionPaths;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfp.rev140701.service.function.paths.ServiceFunctionPath;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sl.rev140701.data.plane.locator.locator.type.Ip;
-import org.opendaylight.yang.gen.v1.urn.ericsson.params.xml.ns.yang.sfc.sf.ovs.rev160107.SfDplOvsAugmentation;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.AccessLists;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.Acl;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.AccessListEntries;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.Ace;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.acl.rev150105.RedirectToSfc;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.classifier.rev150105.Classifiers;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class SfcUtils {
- private static final Logger LOG = LoggerFactory.getLogger(SfcUtils.class);
- private MdsalUtils mdsalUtils;
-
- public SfcUtils(MdsalUtils mdsalUtils) {
- this.mdsalUtils = mdsalUtils;
- }
-
- public InstanceIdentifier<Classifiers> getClassifierIid() {
- return InstanceIdentifier.create(Classifiers.class);
- }
-
- public InstanceIdentifier<RenderedServicePaths> getRspsId() {
- return InstanceIdentifier.builder(RenderedServicePaths.class).build();
- }
-
- public InstanceIdentifier<RenderedServicePath> getRspId(String rspName) {
- return InstanceIdentifier.builder(RenderedServicePaths.class)
- .child(RenderedServicePath.class, new RenderedServicePathKey(new RspName(rspName))).build();
- }
-
- public InstanceIdentifier<ServiceFunction> getSfId(String sfName) {
- return InstanceIdentifier.builder(ServiceFunctions.class)
- .child(ServiceFunction.class, new ServiceFunctionKey(SfName.getDefaultInstance(sfName))).build();
- }
-
- public RenderedServicePath getRsp(String rspName) {
- return mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, getRspId(rspName));
- }
-
- public RenderedServicePath getRspforSfp(String sfpName) {
- RenderedServicePath rspFound = null;
- RenderedServicePaths rsps = mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, this.getRspsId());
- if (rsps != null) {
- for (RenderedServicePath rsp : rsps.getRenderedServicePath()) {
- if (rsp.getParentServiceFunctionPath() != null) {
- if (rsp.getParentServiceFunctionPath().getValue().equals(sfpName)) {
- rspFound = rsp;
- }
- }
- }
- }
- return rspFound;
- }
-
- public ServiceFunctionPath getSfp(String sfcName) {
- ServiceFunctionPath sfpFound = null;
- ServiceFunctionPaths sfps = SfcProviderServicePathAPI.readAllServiceFunctionPaths();
- if (sfps != null) {
- for (ServiceFunctionPath sfp: sfps.getServiceFunctionPath()) {
- if (sfp.getServiceChainName().getValue().equalsIgnoreCase(sfcName)) {
- sfpFound = sfp;
- }
- }
- }
- return sfpFound;
- }
-
- private AccessLists readAccessLists() {
- InstanceIdentifier<AccessLists> path = InstanceIdentifier.create(AccessLists.class);
- return mdsalUtils.read(LogicalDatastoreType.CONFIGURATION, path);
- }
-
- public Ace getAce(RenderedServicePath rsp) {
- return getAce(rsp.getName().getValue(), rsp.getParentServiceFunctionPath().getValue(),
- rsp.getServiceChainName().getValue());
- }
-
- // TODO: optimize this by adding a ACL to RSP mapping in the netvirt-classifier when the ACL is processed
- @SuppressWarnings("unchecked")
- public Ace getAce(String rspName, String sfpName, String sfcName) {
- Ace aceFound = null;
- AccessLists accessLists = readAccessLists();
- if (accessLists != null) {
- List<Acl> acls = accessLists.getAcl();
- if (acls != null) {
- for (Acl acl : acls) {
- AccessListEntries accessListEntries = acl.getAccessListEntries();
- if (accessListEntries != null) {
- List<Ace> aces = accessListEntries.getAce();
- for (Ace ace : aces) {
- RedirectToSfc sfcRedirect = ace.getActions().getAugmentation(RedirectToSfc.class);
- if (sfcRedirect != null) {
- if ((sfcRedirect.getRspName() != null && sfcRedirect.getRspName().equals(rspName)) ||
- (sfcRedirect.getSfcName() != null && sfcRedirect.getSfcName().equals(sfcName)) ||
- (sfcRedirect.getSfpName() != null && sfcRedirect.getSfpName().equals(sfpName))) {
- aceFound = ace;
- break;
- }
- }
- }
- }
- if (aceFound != null) {
- break;
- }
- }
- }
- }
-
- LOG.info("getAce: {}", aceFound);
- return aceFound;
- }
-
- public IpAddress getSfIpAddress(String sfname) {
- ServiceFunction serviceFunction =
- SfcProviderServiceFunctionAPI.readServiceFunction(SfName.getDefaultInstance(sfname));
-
- if (serviceFunction == null) {
- LOG.info("Failed to read ServiceFunction: {}", sfname);
- return null;
- }
-
- return getSfIpAddress(serviceFunction);
- }
-
- public IpAddress getSfIpAddress(ServiceFunction serviceFunction) {
- if (serviceFunction == null) {
- LOG.info("getSfIp: Servicefunction is null");
- return null;
- }
-
- Ip ipLocator = (Ip) serviceFunction.getSfDataPlaneLocator().get(0).getLocatorType();
- return ipLocator.getIp();
- }
-
- public PortNumber getSfPort(ServiceFunction serviceFunction) {
- if (serviceFunction == null) {
- LOG.info("getSfIp: Servicefunction is null");
- return null;
- }
-
- Ip ipLocator = (Ip) serviceFunction.getSfDataPlaneLocator().get(0).getLocatorType();
- return ipLocator.getPort();
- }
-
- public Ip getSfIp(ServiceFunction serviceFunction) {
- if (serviceFunction == null) {
- LOG.info("getSfIp: Servicefunction is null");
- return null;
- }
-
- return (Ip)serviceFunction.getSfDataPlaneLocator().get(0).getLocatorType();
- }
-
- public String getSfDplName(ServiceFunction serviceFunction) {
- String sfDplName = null;
- if (serviceFunction == null) {
- LOG.warn("getSfDplName: Servicefunction is null");
- return null;
- }
-
- sfDplName = serviceFunction.getSfDataPlaneLocator().get(0).getName().getValue();
- return sfDplName;
- }
-
- public String getSfDplPortId(ServiceFunction serviceFunction) {
- String sfDplName = null;
- if (serviceFunction != null &&
- serviceFunction.getSfDataPlaneLocator() != null &&
- serviceFunction.getSfDataPlaneLocator().get(0) != null &&
- serviceFunction.getSfDataPlaneLocator().get(0).getAugmentation(SfDplOvsAugmentation.class) != null ) {
-
- SfDplOvsAugmentation sfDplOvsAugmentation =
- serviceFunction.getSfDataPlaneLocator().get(0).getAugmentation(SfDplOvsAugmentation.class);
- if (sfDplOvsAugmentation.getOvsPort() != null) {
- sfDplName = sfDplOvsAugmentation.getOvsPort().getPortId();
- } else {
- LOG.warn("getSfDplPortId: OvsPort is null");
- }
- } else {
- LOG.warn("getSfDplPortId: ServiceFunction is null");
- }
-
- return sfDplName;
- }
-
- public Ip getSffIp(ServiceFunctionForwarder serviceFunctionForwarder) {
- if (serviceFunctionForwarder != null &&
- serviceFunctionForwarder.getSffDataPlaneLocator() != null &&
- serviceFunctionForwarder.getSffDataPlaneLocator().get(0) != null &&
- serviceFunctionForwarder.getSffDataPlaneLocator().get(0).getDataPlaneLocator() != null) {
- return (Ip)serviceFunctionForwarder.getSffDataPlaneLocator().get(0)
- .getDataPlaneLocator().getLocatorType();
- } else {
- LOG.info("getSffIp: ServiceFunctionForwarder is null");
- return null;
- }
- }
-
- public Ip getSffIp(SffName sffName) {
- ServiceFunctionForwarder serviceFunctionForwarder =
- SfcProviderServiceForwarderAPI.readServiceFunctionForwarder(sffName);
- return getSffIp(serviceFunctionForwarder);
- }
-
- public RenderedServicePathHop getFirstHop(RenderedServicePath rsp) {
- List<RenderedServicePathHop> pathHopList = rsp.getRenderedServicePathHop();
- if (pathHopList.isEmpty()) {
- LOG.warn("handleRenderedServicePath: RSP {} has empty hops!!", rsp.getName());
- return null;
- }
-
- return pathHopList.get(0);
- }
-
- public RenderedServicePathHop getLastHop(RenderedServicePath rsp) {
- List<RenderedServicePathHop> pathHopList = rsp.getRenderedServicePathHop();
- if (pathHopList.isEmpty()) {
- LOG.warn("handleRenderedServicePath: RSP {} has empty hops!!", rsp.getName());
- return null;
- }
-
- return pathHopList.get(pathHopList.size()-1);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Dell, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc.standalone.openflow13;
-
-import com.google.common.base.Preconditions;
-
-import com.google.common.collect.Iterables;
-import java.util.List;
-import java.util.StringTokenizer;
-
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheManager;
-import org.opendaylight.netvirt.openstack.netvirt.sfc.NshUtils;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.openstack.netvirt.sfc.INetvirtSfcOF13Provider;
-import org.opendaylight.netvirt.openstack.netvirt.sfc.ISfcClassifierService;
-import org.opendaylight.netvirt.utils.mdsal.utils.MdsalUtils;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.opendaylight.sfc.provider.api.SfcProviderRenderedPathAPI;
-import org.opendaylight.sfc.provider.api.SfcProviderServicePathAPI;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.RspName;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.CreateRenderedPathInput;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.CreateRenderedPathInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.RenderedServicePaths;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.rendered.service.path.first.hop.info.RenderedServicePathFirstHop;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.rendered.service.paths.RenderedServicePath;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.rendered.service.paths.RenderedServicePathKey;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.rendered.service.paths.rendered.service.path.RenderedServicePathHop;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfp.rev140701.ServiceFunctionPaths;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfp.rev140701.service.function.paths.ServiceFunctionPath;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.Acl;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.Ace;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.Matches;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.matches.ace.type.AceIp;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.matches.ace.type.ace.ip.ace.ip.version.AceIpv4;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.acl.rev150105.RedirectToSfc;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.classifier.rev150105.Classifiers;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.classifier.rev150105.classifiers.Classifier;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.classifier.rev150105.classifiers.classifier.Bridges;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.classifier.rev150105.classifiers.classifier.bridges.Bridge;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.classifier.rev150105.classifiers.classifier.sffs.Sff;
-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.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Open vSwitch OpenFlow 1.3 Networking Provider for Netvirt SFC
- * @author Arun Yerra
- */
-public class NetvirtSfcStandaloneOF13Provider implements INetvirtSfcOF13Provider {
- private static final Logger LOG = LoggerFactory.getLogger(NetvirtSfcStandaloneOF13Provider.class);
- private static final short TABLE_0_CLASSIFIER = 0;
- private static final short TABLE_3_INGR_ACL = 50;
-
- private volatile NodeCacheManager nodeCacheManager;
- private volatile Southbound southbound;
- private MdsalUtils mdsalUtils;
- private SfcClassifier sfcClassifier;
-
- // TBD:: Remove these constants after integrating with openstack.
- private static final String TUNNEL_DST = "192.168.50.75";
- private static final String TUNNEL_VNID = "10";
- private static final String CLIENT_PORT_NAME = "vethl-h35_2";
- private static final String SERVER_PORT_NAME = "vethl-h35_4";
- private static final String CLIENT_GPE_PORT_NAME = "sw1-vxlangpe-0";
- private static final String SERVER_GPE_PORT_NAME = "sw6-vxlangpe-0";
- private static final String INTERFACE_TYPE_VXLAN_GPE = "vxlangpe";
-
- /**
- * {@link NetvirtSfcStandaloneOF13Provider} constructor.
- * @param dataBroker MdSal {@link DataBroker}
- */
- public NetvirtSfcStandaloneOF13Provider(final DataBroker dataBroker) {
- Preconditions.checkNotNull(dataBroker, "Input dataBroker cannot be NULL!");
- mdsalUtils = new MdsalUtils(dataBroker);
- //this.setDependencies(null);
- sfcClassifier = new SfcClassifier(dataBroker, southbound, mdsalUtils);
- }
-
- public void removeClassifierRules(Sff sff, Acl acl) {
- // TODO Auto-generated method stub
- }
-
- @Override
- public void addClassifierRules(Acl acl) {
- String aclName = acl.getAclName();
- Classifiers classifiers = mdsalUtils.read(LogicalDatastoreType.CONFIGURATION, getClassifierIid());
- if (classifiers == null) {
- LOG.debug("add: No Classifiers found");
- return;
- }
-
- LOG.debug("add: Classifiers: {}", classifiers);
- for (Classifier classifier : classifiers.getClassifier()) {
- if (classifier.getAcl().equals(aclName) && classifier.getBridges() != null) {
- addClassifierRules(classifier.getBridges(), acl);
- }
- }
- }
-
- @Override
- public void removeClassifierRules(Acl acl) {
- String aclName = acl.getAclName();
- Classifiers classifiers = mdsalUtils.read(LogicalDatastoreType.CONFIGURATION, getClassifierIid());
- if (classifiers != null) {
- for (Classifier classifier : classifiers.getClassifier()) {
- if (classifier.getAcl().equalsIgnoreCase(aclName) && classifier.getSffs() != null) {
- for (Sff sff : classifier.getSffs().getSff()) {
- removeClassifierRules(sff, acl);
- }
- }
- }
- }
- }
-
- @Override
- public void setSfcClassifierService(ISfcClassifierService sfcClassifierService) {
-
- }
-
- @Override
- public void addClassifierRules(Bridge bridge, Acl acl) {
-
- }
-
- @Override
- public void addClassifierRules(Bridges bridges, Acl acl) {
- Preconditions.checkNotNull(bridges, "Input bridges cannot be NULL!");
- Preconditions.checkNotNull(acl, "Input accesslist cannot be NULL!");
-
- for (Ace ace : acl.getAccessListEntries().getAce()) {
- processAclEntry(ace, bridges, true);
- }
- }
-
- private void processAclEntry(Ace entry, Bridges bridges, boolean write) {
- Matches matches = entry.getMatches();
- if (matches == null) {
- LOG.warn("processAclEntry: matches not found");
- return;
- }
-
- RenderedServicePath rsp = getRenderedServicePath(entry);
- if (rsp == null) {
- LOG.warn("Failed to get renderedServicePatch for entry: {}", entry);
- return;
- }
-
- LOG.info("processAclEntry: RSP: {}", rsp);
- List<RenderedServicePathHop> pathHopList = rsp.getRenderedServicePathHop();
- if (pathHopList.isEmpty()) {
- LOG.warn("Service Path = {} has empty hops!!", rsp.getName());
- return;
- }
-
- for (Bridge bridge : bridges.getBridge()) {
- if (bridge.getDirection().getIntValue() == 0) {
- Node bridgeNode = getBridgeNode(bridge.getName());
- if (bridgeNode == null) {
- LOG.debug("processAclEntry: bridge {} not yet configured. Skip processing !!", bridge.getName());
- continue;
- }
-
- long tunnelOfPort = southbound.getOFPort(bridgeNode, CLIENT_GPE_PORT_NAME);
- if (tunnelOfPort == 0L) {
- LOG.error("programAclEntry: Could not identify tunnel port {} -> OF ({}) on {}",
- CLIENT_GPE_PORT_NAME, tunnelOfPort, bridgeNode);
- return;
- }
-
- long localOfPort = southbound.getOFPort(bridgeNode, CLIENT_PORT_NAME);
- if (localOfPort == 0L) {
- LOG.error("programAclEntry: Could not identify local port {} -> OF ({}) on {}",
- CLIENT_PORT_NAME, localOfPort, bridgeNode);
- return;
- }
-
- // Find the first Hop within an RSP.
- // The classifier flow needs to send all matched traffic to this first hop SFF.
- RenderedServicePathFirstHop firstRspHop = SfcProviderRenderedPathAPI
- .readRenderedServicePathFirstHop(new RspName(rsp.getName()));
-
- LOG.debug("First Hop IPAddress = {}, Port = {}", firstRspHop.getIp().getIpv4Address().getValue(),
- firstRspHop.getPort().getValue());
-
- NshUtils nshHeader = new NshUtils();
- // C1 is the normal overlay dest ip and c2 is the vnid
- // Hardcoded for now, netvirt integration will have those values
- nshHeader.setNshMetaC1(NshUtils.convertIpAddressToLong(new Ipv4Address(TUNNEL_DST)));
- nshHeader.setNshMetaC2(Long.parseLong(TUNNEL_VNID));
- nshHeader.setNshNsp(rsp.getPathId());
-
- RenderedServicePathHop firstHop = pathHopList.get(0);
- nshHeader.setNshNsi(firstHop.getServiceIndex());
- nshHeader.setNshTunIpDst(firstRspHop.getIp().getIpv4Address());
- nshHeader.setNshTunUdpPort(firstRspHop.getPort());
- LOG.debug("The Nsh Header = {}", nshHeader);
-
- handleLocalInPort(southbound.getDataPathId(bridgeNode), rsp.getPathId().toString(), localOfPort,
- TABLE_0_CLASSIFIER, TABLE_3_INGR_ACL, matches, true);
-
- handleSfcClassiferFlows(southbound.getDataPathId(bridgeNode), TABLE_3_INGR_ACL, entry.getRuleName(),
- matches, nshHeader, tunnelOfPort, true);
- } else {
- Node bridgeNode = getBridgeNode(bridge.getName());
- if (bridgeNode == null) {
- LOG.debug("processAclEntry: bridge {} not yet configured. Skip processing !!", bridge.getName());
- continue;
- }
-
- long tunnelOfPort = southbound.getOFPort(bridgeNode, SERVER_GPE_PORT_NAME);
- if (tunnelOfPort == 0L) {
- LOG.error("programAclEntry: Could not identify tunnel port {} -> OF ({}) on {}",
- SERVER_GPE_PORT_NAME, tunnelOfPort, bridgeNode);
- return;
- }
-
- long localOfPort = southbound.getOFPort(bridgeNode, SERVER_PORT_NAME);
- if (localOfPort == 0L) {
- LOG.error("programAclEntry: Could not identify local port {} -> OF ({}) on {}",
- SERVER_PORT_NAME, localOfPort, bridgeNode);
- return;
- }
-
- RenderedServicePathHop lastRspHop = Iterables.getLast(rsp.getRenderedServicePathHop());
-
- LOG.debug("programAclEntry: Last Hop #: {}, nsi: {}", lastRspHop.getHopNumber().intValue(),
- lastRspHop.getServiceIndex().intValue() - 1);
-
- NshUtils nshHeader = new NshUtils();
- nshHeader.setNshNsp(rsp.getPathId());
- nshHeader.setNshNsi((short)(lastRspHop.getServiceIndex().intValue() - 1));
- nshHeader.setNshMetaC2(Long.parseLong(TUNNEL_VNID));
- LOG.debug("programAclEntry: The Nsh Header = {}", nshHeader);
-
- //handleLocalEgressPort(southbound.getDataPathId(bridgeNode), rsp.getPathId().toString(), localOfPort,
- // TABLE_0_CLASSIFIER, TABLE_3_INGR_ACL, true);
-
- handleEgressSfcClassiferFlows(southbound.getDataPathId(bridgeNode),
- TABLE_0_CLASSIFIER, entry.getRuleName(), matches, nshHeader, tunnelOfPort, localOfPort, true);
- }
- }
- }
-
- private RenderedServicePath getRenderedServicePath (Ace entry) {
- RenderedServicePath rsp = null;
- RedirectToSfc sfcRedirect = entry.getActions().getAugmentation(RedirectToSfc.class);
- LOG.debug("Processing ACL entry = {} sfcRedirect = {}", entry.getRuleName(), sfcRedirect);
- if (sfcRedirect == null) {
- LOG.warn("processAClEntry: sfcRedirect is null");
- return null;
- }
-
- if (sfcRedirect.getRspName() != null) {
- rsp = getRenderedServicePathFromRsp(sfcRedirect.getRspName());
- } else if (sfcRedirect.getSfpName() != null) {
- LOG.warn("getRenderedServicePath: sfp not handled yet");
- } else {
- rsp = getRenderedServicePathFromSfc(entry);
- }
- LOG.info("getRenderedServicePath: rsp: {}", rsp);
- return rsp;
- }
-
- private RenderedServicePath getRenderedServicePathFromRsp(String rspName) {
- return null;//getRsp(rspName);
- }
-
- private RenderedServicePath getRenderedServicePathFromSfc (Ace entry) {
- RedirectToSfc sfcRedirect = entry.getActions().getAugmentation(RedirectToSfc.class);
- LOG.debug("Processing ACL entry = {} sfcRedirect = {}", entry.getRuleName(), sfcRedirect);
- if (sfcRedirect == null) {
- LOG.warn("processAClEntry: sfcRedirect is null");
- return null;
- }
-
- String sfcName = sfcRedirect.getSfcName();
- ServiceFunctionPath sfp = getSfp(sfcName);
- if (sfp == null || sfp.getName() == null) {
- LOG.warn("There is no configured SFP with sfcName = {}; so skip installing the ACL entry!!", sfcName);
- return null;
- }
-
- LOG.debug("Processing Redirect to SFC = {}, SFP = {}", sfcName, sfp);
- // If RSP doesn't exist, create an RSP.
- String sfpName = sfp.getName().getValue();
- RenderedServicePath rsp = getRspforSfp(sfpName);
- String rspName = sfp.getName().getValue() + "_rsp";
- if (rsp == null) {
- LOG.info("No configured RSP corresponding to SFP = {}, Creating new RSP = {}", sfpName, rspName);
- CreateRenderedPathInput rspInput = new CreateRenderedPathInputBuilder()
- .setParentServiceFunctionPath(sfpName)
- .setName(rspName)
- .setSymmetric(sfp.isSymmetric())
- .build();
- rsp = SfcProviderRenderedPathAPI.createRenderedServicePathAndState(sfp, rspInput);
- if (rsp == null) {
- LOG.warn("failed to add RSP");
- return null;
- }
-
- // If SFP is symmetric, create RSP in the reverse direction.
- if (sfp.isSymmetric()) {
- LOG.info("SFP = {} is symmetric, installing RSP in the reverse direction!!", sfpName);
- String rspNameRev = rspName + "-Reverse";
- RenderedServicePath rspReverse = mdsalUtils.read(LogicalDatastoreType.OPERATIONAL,
- getRspId(rspNameRev));
- if (rspReverse == null) {
- rspReverse = SfcProviderRenderedPathAPI.createSymmetricRenderedServicePathAndState(rsp);
- if (rspReverse == null) {
- LOG.warn("failed to add reverse RSP");
- return null;
- }
- }
- }
- }
- return rsp;
- }
-
- private void handleLocalEgressPort(long dataPathId, String s, long localOfPort, short writeTable,
- short gotoTable, boolean write) {
-
- }
-
- private void handleEgressSfcClassiferFlows(long dataPathId, short writeTable, String ruleName,
- Matches matches, NshUtils nshHeader, long tunnelOfPort,
- long outOfPort, boolean write) {
- sfcClassifier.programEgressSfcClassiferFlows(dataPathId, writeTable, ruleName, matches, nshHeader,
- tunnelOfPort, outOfPort, write);
- }
-
- private void handleSfcClassiferFlows(long dataPathId, short writeTable, String ruleName,
- Matches matches, NshUtils nshHeader, long tunnelOfPort,
- boolean write) {
- sfcClassifier.programSfcClassiferFlows(dataPathId, writeTable, ruleName, matches, nshHeader,
- tunnelOfPort, write);
- }
-
- private InstanceIdentifier<RenderedServicePaths> getRspsId() {
- return InstanceIdentifier.builder(RenderedServicePaths.class).build();
- }
-
- private InstanceIdentifier<RenderedServicePath> getRspId(String rspName) {
- return InstanceIdentifier.builder(RenderedServicePaths.class)
- .child(RenderedServicePath.class, new RenderedServicePathKey(new RspName(rspName))).build();
- }
-
- public Node getBridgeNode(String bridgeName) {
- Node nodeFound = null;
- final List<Node> nodes = nodeCacheManager.getBridgeNodes();
- if (nodes != null && !nodes.isEmpty()) {
- for (Node node : nodes) {
- if (southbound.getBridge(node, bridgeName) != null) {
- nodeFound = node;
- break;
- }
- }
- }
- return nodeFound;
- }
-
- public RenderedServicePath getRspforSfp(String sfpName) {
- RenderedServicePath rspFound = null;
- RenderedServicePaths rsps = mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, this.getRspsId());
- if (rsps != null) {
- for (RenderedServicePath rsp : rsps.getRenderedServicePath()) {
- if (rsp.getParentServiceFunctionPath() != null) {
- if (rsp.getParentServiceFunctionPath().getValue().equals(sfpName)) {
- rspFound = rsp;
- }
- }
- }
- }
- return rspFound;
- }
-
- public ServiceFunctionPath getSfp(String redirectSfc) {
- ServiceFunctionPath sfpFound = null;
- ServiceFunctionPaths sfps = SfcProviderServicePathAPI.readAllServiceFunctionPaths();
- if (sfps != null) {
- for (ServiceFunctionPath sfp: sfps.getServiceFunctionPath()) {
- if (sfp.getServiceChainName().getValue().equalsIgnoreCase(redirectSfc)) {
- sfpFound = sfp;
- }
- }
- }
- return sfpFound;
- }
-
-/*
- * (TABLE:0) EGRESS VM TRAFFIC TOWARDS TEP
- * MATCH: DESTINATION ETHERNET ADDR AND OPENFLOW INPORT
- * INSTRUCTION: SET TUNNELID AND GOTO TABLE TUNNEL TABLE (N)
- * TABLE=0,IN_PORT=2,DL_SRC=00:00:00:00:00:01 \
- * ACTIONS=SET_FIELD:5->TUN_ID,GOTO_TABLE=1"
- */
- public String getDestIp(Matches match) {
- if (match.getAceType() instanceof AceIp) {
- AceIp aceIp = (AceIp)match.getAceType();
- if (aceIp.getAceIpVersion() instanceof AceIpv4) {
- AceIpv4 aceIpv4 = (AceIpv4) aceIp.getAceIpVersion();
- if (aceIpv4.getDestinationIpv4Network() != null) {
- String ipAddrPrefix = aceIpv4.getDestinationIpv4Network().getValue();
- return new StringTokenizer(ipAddrPrefix, "/").nextToken();
- }
- }
- }
- return null;
- }
-
- public String getSourceIp(Matches match) {
- if (match.getAceType() instanceof AceIp) {
- AceIp aceIp = (AceIp)match.getAceType();
- if (aceIp.getAceIpVersion() instanceof AceIpv4) {
- AceIpv4 aceIpv4 = (AceIpv4) aceIp.getAceIpVersion();
- if (aceIpv4.getSourceIpv4Network() != null) {
- //String ipAddr = new StringTokenizer(ipAddrPrefix, "/").nextToken();
- return aceIpv4.getSourceIpv4Network().getValue();
- }
- }
- }
- return null;
- }
-
- private InstanceIdentifier<Classifiers> getClassifierIid() {
- return InstanceIdentifier.create(Classifiers.class);
- }
-
- public void handleLocalInPort(long dpidLong, String segmentationId, Long inPort,
- short writeTable, short goToTableId, Matches matches, boolean write) {
- sfcClassifier.programLocalInPort(dpidLong, segmentationId, inPort, writeTable, goToTableId, matches, write);
- }
-
- @Override
- public void setDependencies(ServiceReference serviceReference) {
- nodeCacheManager = (NodeCacheManager) ServiceHelper.getGlobalInstance(NodeCacheManager.class, this);
- southbound = (Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this);
- }
-
- @Override
- public void removeRsp(RenderedServicePath change) {
- LOG.warn("removeRsp is not implemented yet");
- }
-
- @Override
- public void addRsp(RenderedServicePath change) {
- LOG.warn("addRsp is not implemented yet");
- }
-
- @Override
- public void updateRsp(RenderedServicePath change) {
- LOG.warn("updateRsp is not implemented yet");
- }
-}
+++ /dev/null
-/*
- * Copyright © 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc.standalone.openflow13;
-
-import java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.List;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.netvirt.openstack.netvirt.sfc.NshUtils;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.utils.mdsal.openflow.ActionUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.FlowUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.InstructionUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.MatchUtils;
-import org.opendaylight.netvirt.utils.mdsal.utils.MdsalUtils;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.Matches;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.matches.ace.type.AceEth;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.matches.ace.type.AceIp;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.matches.ace.type.ace.ip.ace.ip.version.AceIpv4;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
-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.flow.inventory.rev130819.tables.table.FlowBuilder;
-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.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;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg0;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.dst.choice.grouping.dst.choice.DstNxRegCaseBuilder;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class SfcClassifier {
- private static final Logger LOG = LoggerFactory.getLogger(SfcClassifier.class);
- private DataBroker dataBroker;
- private Southbound southbound;
- private MdsalUtils mdsalUtils;
- public final static long REG_VALUE_FROM_LOCAL = 0x1L;
- public final static long REG_VALUE_FROM_REMOTE = 0x2L;
- public static final Class<? extends NxmNxReg> REG_FIELD = NxmNxReg0.class;
- private static final String OPENFLOW = "openflow:";
-
- public SfcClassifier(DataBroker dataBroker, Southbound southbound, MdsalUtils mdsalUtils) {
- this.dataBroker = dataBroker;
- this.southbound = southbound;
- this.mdsalUtils = mdsalUtils;
- }
-
- /*
- * (TABLE:50) EGRESS VM TRAFFIC TOWARDS TEP with NSH header
- * MATCH: Match fields passed through ACL entry
- * INSTRUCTION: SET TUNNELID AND GOTO TABLE TUNNEL TABLE (N)
- * TABLE=0,IN_PORT=2,DL_SRC=00:00:00:00:00:01 \
- * ACTIONS=SET_FIELD:5->TUN_ID,GOTO_TABLE=1"
- */
- public void programSfcClassiferFlows(Long dpidLong, short writeTable, String ruleName, Matches match,
- NshUtils nshHeader, long tunnelOfPort, boolean write) {
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = "sfcClass_" + ruleName + "_" + nshHeader.getNshNsp();
- FlowUtils.initFlowBuilder(flowBuilder, flowName, writeTable);
-
- MatchBuilder matchBuilder = buildMatch(match);
- flowBuilder.setMatch(matchBuilder.build());
-
- if (write) {
- List<Action> actionList = getNshAction(nshHeader);
- ActionBuilder ab = new ActionBuilder();
-
- ab.setAction(ActionUtils.outputAction(FlowUtils.getNodeConnectorId(dpidLong, tunnelOfPort)));
- ab.setOrder(actionList.size());
- ab.setKey(new ActionKey(actionList.size()));
- actionList.add(ab.build());
-
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
-
- InstructionBuilder ib = new InstructionBuilder();
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
- ib.setOrder(0);
- ib.setKey(new InstructionKey(0));
- List<Instruction> instructions = new ArrayList<>();
- instructions.add(ib.build());
-
- InstructionsBuilder isb = new InstructionsBuilder();
- isb.setInstruction(instructions);
- flowBuilder.setInstructions(isb.build());
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
- }
-
- public void programEgressSfcClassiferFlows(Long dpidLong, short writeTable, String ruleName,
- Matches match, NshUtils nshHeader,
- long tunnelOfPort, long outOfPort, boolean write) {
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = "egressSfcClass_" + ruleName + "_" + nshHeader.getNshNsp() + "_" + nshHeader.getNshNsi();
- FlowUtils.initFlowBuilder(flowBuilder, flowName, writeTable);
-
- MatchBuilder matchBuilder = new MatchBuilder();
- flowBuilder.setMatch(MatchUtils.createInPortMatch(matchBuilder, dpidLong, tunnelOfPort).build());
- flowBuilder.setMatch(
- MatchUtils.createTunnelIDMatch(matchBuilder, BigInteger.valueOf(nshHeader.getNshMetaC2())).build());
- flowBuilder.setMatch(MatchUtils.addNxNspMatch(matchBuilder, nshHeader.getNshNsp()).build());
- flowBuilder.setMatch(MatchUtils.addNxNsiMatch(matchBuilder, nshHeader.getNshNsi()).build());
-
- if (write) {
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab = new ActionBuilder();
-
- ab.setAction(ActionUtils.nxLoadRegAction(new DstNxRegCaseBuilder().setNxReg(REG_FIELD).build(),
- BigInteger.valueOf(REG_VALUE_FROM_REMOTE)));
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
- actionList.add(ab.build());
-
- ab.setAction(ActionUtils.outputAction(FlowUtils.getNodeConnectorId(dpidLong, outOfPort)));
- ab.setOrder(1);
- ab.setKey(new ActionKey(1));
- actionList.add(ab.build());
-
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
-
- InstructionBuilder ib = new InstructionBuilder();
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
-
- ib.setOrder(0);
- ib.setKey(new InstructionKey(0));
- List<Instruction> instructions = new ArrayList<>();
- instructions.add(ib.build());
-
- InstructionsBuilder isb = new InstructionsBuilder();
- isb.setInstruction(instructions);
-
- flowBuilder.setInstructions(isb.build());
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
- }
-
- private List<Action> getNshAction(NshUtils header) {
- // Build the Actions to Add the NSH Header
- org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action pushNsh =
- ActionUtils.nxPushNshAction();
- org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action nshMdtypeLoad =
- ActionUtils.nxLoadNshMdtypeAction((short) 0x1);
- org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action nshNpLoad =
- ActionUtils.nxLoadNshNpAction((short) 0x3);
- org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action nshC1Load =
- ActionUtils.nxLoadNshc1RegAction(header.getNshMetaC1());
- org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action nshC2Load =
- ActionUtils.nxLoadNshc2RegAction(header.getNshMetaC2());
- org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action nspLoad =
- ActionUtils.nxSetNspAction(header.getNshNsp());
- org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action nsiLoad =
- ActionUtils.nxSetNsiAction(header.getNshNsi());
- org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action loadChainTunVnid =
- ActionUtils.nxLoadTunIdAction(BigInteger.valueOf(header.getNshNsp()), false);
- org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action loadChainTunDest =
- ActionUtils.nxLoadTunIPv4Action(header.getNshTunIpDst().getValue(), false);
-
- int count = 0;
- List<Action> actionList = new ArrayList<>();
- actionList.add(new ActionBuilder().setOrder(count++).setAction(pushNsh).build());
- actionList.add(new ActionBuilder().setOrder(count++).setAction(nshMdtypeLoad).build());
- actionList.add(new ActionBuilder().setOrder(count++).setAction(nshNpLoad).build());
- actionList.add(new ActionBuilder().setOrder(count++).setAction(nshC1Load).build());
- actionList.add(new ActionBuilder().setOrder(count++).setAction(nshC2Load).build());
- actionList.add(new ActionBuilder().setOrder(count++).setAction(nspLoad).build());
- actionList.add(new ActionBuilder().setOrder(count++).setAction(nsiLoad).build());
- actionList.add(new ActionBuilder().setOrder(count++).setAction(loadChainTunDest).build());
- actionList.add(new ActionBuilder().setOrder(count++).setAction(loadChainTunVnid).build());
- return actionList;
- }
-
- public void programLocalInPort(Long dpidLong, String segmentationId, Long inPort,
- short writeTable, short goToTableId, Matches match, boolean write) {
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = "sfcIngress_" + segmentationId + "_" + inPort;
- FlowUtils.initFlowBuilder(flowBuilder, flowName, writeTable);
-
- MatchBuilder matchBuilder = buildMatch(match);
- flowBuilder.setMatch(matchBuilder.build());
- flowBuilder.setMatch(MatchUtils.createInPortMatch(matchBuilder, dpidLong, inPort).build());
-
- if (write) {
- InstructionBuilder ib = new InstructionBuilder();
- InstructionsBuilder isb = new InstructionsBuilder();
- List<Instruction> instructions = new ArrayList<>();
-
- InstructionUtils.createSetTunnelIdInstructions(ib, new BigInteger(segmentationId));
- ApplyActionsCase aac = (ApplyActionsCase) ib.getInstruction();
- List<Action> actionList = aac.getApplyActions().getAction();
-
- // TODO: Mark the packets as sfc classified?
-
- ActionBuilder ab = new ActionBuilder();
- ab.setAction(ActionUtils.nxLoadRegAction(new DstNxRegCaseBuilder().setNxReg(REG_FIELD).build(),
- BigInteger.valueOf(REG_VALUE_FROM_LOCAL)));
- ab.setOrder(1);
- ab.setKey(new ActionKey(1));
- actionList.add(ab.build());
-
- ib.setOrder(0);
- ib.setKey(new InstructionKey(0));
- instructions.add(ib.build());
-
- // Next service GOTO Instructions Need to be appended to the List
- ib = InstructionUtils.createGotoTableInstructions(new InstructionBuilder(), goToTableId);
- ib.setOrder(1);
- ib.setKey(new InstructionKey(1));
- instructions.add(ib.build());
-
- isb.setInstruction(instructions);
- flowBuilder.setInstructions(isb.build());
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
- }
-
- public MatchBuilder buildMatch(Matches matches) {
- MatchBuilder matchBuilder = new MatchBuilder();
-
- if (matches.getAceType() instanceof AceIp) {
- AceIp aceIp = (AceIp)matches.getAceType();
- if (aceIp.getAceIpVersion() instanceof AceIpv4) {
- //AceIpv4 aceIpv4 = (AceIpv4) aceIp.getAceIpVersion();
- //MatchUtils.createSrcL3IPv4Match(matchBuilder, aceIpv4.getSourceIpv4Network());
- //MatchUtils.createDstL3IPv4Match(matchBuilder, aceIpv4.getDestinationIpv4Network());
- MatchUtils.createIpProtocolMatch(matchBuilder, aceIp.getProtocol());
- MatchUtils.addLayer4Match(matchBuilder, aceIp.getProtocol().intValue(), 0,
- aceIp.getDestinationPortRange().getLowerPort().getValue());
- }
- } else if (matches.getAceType() instanceof AceEth) {
- AceEth aceEth = (AceEth) matches.getAceType();
- MatchUtils.createEthSrcMatch(matchBuilder, new MacAddress(aceEth.getSourceMacAddress().getValue()));
- MatchUtils.createDestEthMatch(matchBuilder, new MacAddress(aceEth.getDestinationMacAddress().getValue()),
- new MacAddress(aceEth.getDestinationMacAddressMask().getValue()));
- }
-
- LOG.info("buildMatch: {}", matchBuilder.build());
- return matchBuilder;
- }
-
- protected void writeFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder) {
- LOG.debug("writeFlow: flowBuilder: {}, nodeBuilder: {}", flowBuilder.build(), nodeBuilder.build());
- mdsalUtils.merge(LogicalDatastoreType.CONFIGURATION, FlowUtils.createNodePath(nodeBuilder),
- nodeBuilder.build());
- mdsalUtils.put(LogicalDatastoreType.CONFIGURATION, FlowUtils.createFlowPath(flowBuilder, nodeBuilder),
- flowBuilder.build());
- }
-
- protected void removeFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder) {
- mdsalUtils.delete(LogicalDatastoreType.CONFIGURATION, FlowUtils.createFlowPath(flowBuilder, nodeBuilder));
- }
-}
+++ /dev/null
-/*
- * Copyright © 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc.standalone.openflow13.services;
-
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.AbstractServiceInstance;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.netvirt.openstack.netvirt.sfc.ISfcStandaloneClassifierService;
-import org.opendaylight.netvirt.openstack.netvirt.sfc.NshUtils;
-import org.opendaylight.netvirt.openstack.netvirt.providers.ConfigInterface;
-import org.opendaylight.netvirt.openstack.netvirt.sfc.ISfcClassifierService;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.Matches;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class SfcClassifierService extends AbstractServiceInstance implements ConfigInterface,
- ISfcStandaloneClassifierService {
- private static final Logger LOG = LoggerFactory.getLogger(SfcClassifierService.class);
-
- public SfcClassifierService(Service service) {
- super(service);
- }
-
- public SfcClassifierService() {
- super(Service.SFC_CLASSIFIER);
- }
-
- @Override
- public void setDependencies(BundleContext bundleContext, ServiceReference serviceReference) {
- super.setDependencies(bundleContext.getServiceReference(ISfcClassifierService.class.getName()), this);
- }
-
- @Override
- public void setDependencies(Object impl) {}
-
- @Override
- public void programIngressClassifier(long dataPathId, String ruleName, Matches matches, NshUtils nshHeader, long vxGpeOfPort, boolean write) {
-
- }
-
- @Override
- public void programSfcTable(long dataPathId, long vxGpeOfPort, short goToTableId, boolean write) {
-
- }
-
- @Override
- public void programEgressClassifier1(long dataPathId, long vxGpeOfPort, long nsp, short nsi, int tunnelOfPort, int tunnelId, short gotoTableId, boolean write) {
-
- }
-
- @Override
- public void programEgressClassifier(long dataPathId, long vxGpeOfPort, long nsp, short nsi, long sfOfPort, int tunnelId, boolean write) {
-
- }
-
- @Override
- public void programEgressClassifierBypass(long dataPathId, long vxGpeOfPort, long nsp, short nsi, long sfOfPort, int tunnelId, boolean write) {
-
- }
-
- @Override
- public void program_sfEgress(long dataPathId, int dstPort, boolean write) {
-
- }
-
- @Override
- public void program_sfIngress(long dataPathId, int dstPort, long sfOfPort, String ipAddress, String sfDplName, boolean write) {
-
- }
-
- @Override
- public void programStaticArpEntry(long dataPathId, long ofPort, String macAddressStr, String ipAddress, boolean write) {
- }
-}
+++ /dev/null
-/*
- * Copyright © 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc.workaround;
-
-import com.google.common.base.Preconditions;
-import java.util.List;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.OvsdbTables;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.openstack.netvirt.sfc.INetvirtSfcOF13Provider;
-import org.opendaylight.netvirt.openstack.netvirt.sfc.ISfcClassifierService;
-import org.opendaylight.netvirt.openstack.netvirt.sfc.NshUtils;
-import org.opendaylight.netvirt.openstack.netvirt.sfc.SfcUtils;
-import org.opendaylight.netvirt.utils.mdsal.utils.MdsalUtils;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.opendaylight.sfc.provider.api.SfcProviderRenderedPathAPI;
-import org.opendaylight.sfc.provider.api.SfcProviderServiceForwarderAPI;
-import org.opendaylight.sfc.provider.api.SfcProviderServiceFunctionAPI;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sl.rev140701.data.plane.locator.locator.type.Ip;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.CreateRenderedPathInput;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.CreateRenderedPathInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.rendered.service.path.first.hop.info.RenderedServicePathFirstHop;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.rendered.service.paths.RenderedServicePath;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.rendered.service.paths.rendered.service.path.RenderedServicePathHop;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sf.rev140701.service.functions.ServiceFunction;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.service.function.forwarders.ServiceFunctionForwarder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfp.rev140701.service.function.paths.ServiceFunctionPath;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.Acl;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.Ace;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.Matches;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.acl.rev150105.RedirectToSfc;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.classifier.rev150105.classifiers.classifier.Bridges;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.classifier.rev150105.classifiers.classifier.bridges.Bridge;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.classifier.rev150105.classifiers.classifier.sffs.Sff;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbTerminationPointAugmentation;
-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.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.node.TerminationPoint;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class NetvirtSfcWorkaroundOF13Provider implements INetvirtSfcOF13Provider {
- private static final Logger LOG = LoggerFactory.getLogger(NetvirtSfcWorkaroundOF13Provider.class);
- private volatile NodeCacheManager nodeCacheManager;
- private volatile Southbound southbound;
- private volatile ISfcClassifierService sfcClassifierService;
- private static final short SFC_TABLE = 150;
- private MdsalUtils mdsalUtils;
- private SfcUtils sfcUtils;
- private DataBroker dataBroker;
- private static final String VXGPE = "vxgpe";
- public static final String TUNNEL_ENDPOINT_KEY = "local_ip";
- private Boolean addSfFlows;
-
- public NetvirtSfcWorkaroundOF13Provider(final DataBroker dataBroker, MdsalUtils mdsalUtils,
- SfcUtils sfcUtils, Boolean addSfFlows) {
- Preconditions.checkNotNull(dataBroker, "Input dataBroker cannot be NULL!");
- Preconditions.checkNotNull(mdsalUtils, "Input mdsalUtils cannot be NULL!");
- Preconditions.checkNotNull(sfcUtils, "Input sfcUtils cannot be NULL!");
-
- this.dataBroker = dataBroker;
- this.mdsalUtils = mdsalUtils;
- this.sfcUtils = sfcUtils;
- this.addSfFlows = addSfFlows;
- }
-
- public void setSfcClassifierService(ISfcClassifierService sfcClassifierService) {
- this.sfcClassifierService = sfcClassifierService;
- }
-
- @Override
- public void addClassifierRules(Bridge bridge, Acl acl) {
-
- }
-
- @Override
- public void addClassifierRules(Bridges bridges, Acl acl) {
- Preconditions.checkNotNull(bridges, "Input bridges cannot be NULL!");
- Preconditions.checkNotNull(acl, "Input acl cannot be NULL!");
- }
-
- @Override
- public void removeClassifierRules(Sff sff, Acl acl) {
-
- }
-
- @Override
- public void addClassifierRules(Acl acl) {
- for (Ace ace : acl.getAccessListEntries().getAce()) {
- processAclEntry(ace);
- }
- }
-
- @Override
- public void removeClassifierRules(Acl acl) {
- for (Ace ace : acl.getAccessListEntries().getAce()) {
- RenderedServicePath rsp = getRenderedServicePath(ace);
- if (rsp == null) {
- LOG.warn("Failed to get renderedServicePatch for entry: {}", ace);
- return;
- }
- sfcClassifierService.clearFlows(dataBroker, rsp.getName().getValue());
- }
- }
-
- @Override
- public void removeRsp(RenderedServicePath change) {
- sfcClassifierService.clearFlows(dataBroker, change.getName().getValue());
- }
-
- @Override
- public void addRsp(RenderedServicePath change) {
- handleRenderedServicePath(change);
- }
-
- @Override
- public void updateRsp(RenderedServicePath change) {
- LOG.info("updateRsp not implemented yet");
- }
-
- private void processAclEntry(Ace entry) {
- Matches matches = entry.getMatches();
- Preconditions.checkNotNull(matches, "ACL Entry cannot be null!");
-
- RenderedServicePath rsp = getRenderedServicePath(entry);
- if (rsp == null) {
- LOG.warn("Failed to get renderedServicePatch for entry: {}", entry);
- return;
- }
-
- handleRenderedServicePath(rsp, entry);
- }
-
- private void handleRenderedServicePath(RenderedServicePath rsp) {
- LOG.info("handleRenderedServicePath: RSP: {}", rsp);
- Ace entry = getAceFromRenderedServicePath(rsp);
- if (entry == null) {
- LOG.warn("handleRenderedServicePath: failed to get acl entry");
- return;
- }
-
- handleRenderedServicePath(rsp, entry);
- }
-
- private void handleRenderedServicePath(RenderedServicePath rsp, Ace entry) {
- LOG.info("handleRenderedServicePath: RSP: {}, Ace: {}", rsp, entry);
-
- Matches matches = entry.getMatches();
- if (matches == null) {
- LOG.warn("processAclEntry: matches not found");
- return;
- }
-
- List<RenderedServicePathHop> pathHopList = rsp.getRenderedServicePathHop();
- if (pathHopList.isEmpty()) {
- LOG.warn("handleRenderedServicePath: RSP {} has empty hops!!", rsp.getName());
- return;
- }
- LOG.info("handleRenderedServicePath: pathHopList: {}", pathHopList);
-
- RenderedServicePathFirstHop firstRspHop = SfcProviderRenderedPathAPI
- .readRenderedServicePathFirstHop(rsp.getName());
- LOG.info("handleRenderedServicePath: firstRspHop: {}", firstRspHop);
-
- RenderedServicePathHop firstHop = pathHopList.get(0);
- RenderedServicePathHop lastHop = pathHopList.get(pathHopList.size()-1);
-
- final List<Node> bridgeNodes = nodeCacheManager.getBridgeNodes();
- if (bridgeNodes == null || bridgeNodes.isEmpty()) {
- LOG.warn("handleRenderedServicePath: There are no bridges to process");
- return;
- }
- for (RenderedServicePathHop hop : pathHopList) {
- for (Node bridgeNode : bridgeNodes) {
- // ignore bridges other than br-int
- // TODO: Get bridge name from DPL, rework this loop to use DPL list
- OvsdbBridgeAugmentation ovsdbBridgeAugmentation = southbound.getBridge(bridgeNode, "br-int");
- if (ovsdbBridgeAugmentation == null) {
- continue;
- }
- // TODO: Get port name from the DPL
- long vxGpeOfPort = getOFPort(bridgeNode, VXGPE);
- if (vxGpeOfPort == 0L) {
- LOG.warn("handleRenderedServicePath: Could not identify gpe vtep {} -> OF ({}) on {}",
- VXGPE, vxGpeOfPort, bridgeNode);
- continue;
- }
- long dataPathId = southbound.getDataPathId(bridgeNode);
- if (dataPathId == 0L) {
- LOG.warn("handleRenderedServicePath: Could not identify datapathId on {}", bridgeNode);
- continue;
- }
-
- ServiceFunction serviceFunction =
- SfcProviderServiceFunctionAPI.readServiceFunction(hop.getServiceFunctionName());
- if (serviceFunction == null) {
- LOG.warn("handleRenderedServicePath: Could not identify ServiceFunction {} on {}",
- hop.getServiceFunctionName().getValue(), bridgeNode);
- continue;
- }
- ServiceFunctionForwarder serviceFunctionForwarder =
- SfcProviderServiceForwarderAPI
- .readServiceFunctionForwarder(hop.getServiceFunctionForwarder());
- if (serviceFunctionForwarder == null) {
- LOG.warn("handleRenderedServicePath: Could not identify ServiceFunctionForwarder {} on {}",
- hop.getServiceFunctionName().getValue(), bridgeNode);
- continue;
- }
-
- handleSf(bridgeNode, serviceFunction, rsp);
- handleSff(bridgeNode, serviceFunctionForwarder, serviceFunction, hop, firstHop, lastHop,
- entry.getRuleName(), matches, vxGpeOfPort, rsp);
- if (firstHop == lastHop) {
- handleSff(bridgeNode, serviceFunctionForwarder, serviceFunction, hop, null, lastHop,
- entry.getRuleName(), matches, vxGpeOfPort, rsp);
- }
- }
- }
- }
-
- private void handleSff(Node bridgeNode, ServiceFunctionForwarder serviceFunctionForwarder,
- ServiceFunction serviceFunction,
- RenderedServicePathHop hop,
- RenderedServicePathHop firstHop,
- RenderedServicePathHop lastHop,
- String ruleName, Matches matches,
- long vxGpeOfPort, RenderedServicePath rsp) {
- long dataPathId = southbound.getDataPathId(bridgeNode);
-
- if (hop == firstHop) {
- LOG.info("handleSff: first hop processing {} - {}",
- bridgeNode.getNodeId().getValue(), serviceFunctionForwarder.getName().getValue());
- NshUtils nshHeader = new NshUtils();
- nshHeader.setNshNsp(rsp.getPathId());
- nshHeader.setNshNsi(firstHop.getServiceIndex());
- Ip sffIp = sfcUtils.getSffIp(lastHop.getServiceFunctionForwarder());
- nshHeader.setNshMetaC1(NshUtils.convertIpAddressToLong(sffIp.getIp().getIpv4Address()));
- if (isSffOnBridge(bridgeNode, serviceFunctionForwarder)) {
- LOG.info("handleSff: sff and bridge are the same: {} - {}, skipping first sff",
- bridgeNode.getNodeId().getValue(), serviceFunctionForwarder.getName().getValue());
- Ip ip = sfcUtils.getSfIp(serviceFunction);
- nshHeader.setNshTunIpDst(ip.getIp().getIpv4Address());
- nshHeader.setNshTunUdpPort(ip.getPort());
- sfcClassifierService.programIngressClassifier(dataPathId, ruleName, matches,
- rsp.getPathId(), rsp.getStartingIndex(),
- nshHeader, 0, rsp.getName().getValue(), true);
- } else {
- LOG.info("handleSff: sff and bridge are not the same: {} - {}, sending to first sff",
- bridgeNode.getNodeId().getValue(), serviceFunctionForwarder.getName().getValue());
- Ip ip = sfcUtils.getSffIp(serviceFunctionForwarder);
- nshHeader.setNshTunIpDst(ip.getIp().getIpv4Address());
- nshHeader.setNshTunUdpPort(ip.getPort());
- sfcClassifierService.programIngressClassifier(dataPathId, ruleName, matches,
- rsp.getPathId(), rsp.getStartingIndex(),
- nshHeader, vxGpeOfPort, rsp.getName().getValue(), true);
- }
- } else if (hop == lastHop) {
- LOG.info("handleSff: last hop processing {} - {}",
- bridgeNode.getNodeId().getValue(), serviceFunctionForwarder.getName().getValue());
- short lastServiceindex = (short)((lastHop.getServiceIndex()).intValue() - 1);
- String sfDplPortName = sfcUtils.getSfDplPortId(serviceFunction);
- long sfOfPort = getSfPort(bridgeNode, sfDplPortName);
- // TODO: Coexistence: SFC flows should take this using new egressTable REST
- sfcClassifierService.programEgressClassifier(dataPathId, vxGpeOfPort, rsp.getPathId(),
- lastServiceindex, sfOfPort, 0, rsp.getName().getValue(), true);
- // TODO: Coexistence: This flow should like like one above, change port, add reg0=1, resubmit
- sfcClassifierService.programEgressClassifierBypass(dataPathId, vxGpeOfPort, rsp.getPathId(),
- lastServiceindex, sfOfPort, 0, rsp.getName().getValue(), true);
- } else {
- // add typical sff flows
- }
-
- // TODO: Coexistence: SFC flows should take this using new tableOffset REST
- //sfcClassifierService.programSfcTable(dataPathId, vxGpeOfPort, SFC_TABLE, true);
- }
-
- void handleSf(Node bridgeNode, ServiceFunction serviceFunction, RenderedServicePath rsp) {
- if (isSfOnBridge(bridgeNode, serviceFunction)) {
- LOG.info("handleSf: sf and bridge are on the same node: {} - {}, adding workaround and arp",
- bridgeNode.getNodeId().getValue(), serviceFunction.getName().getValue());
- long dataPathId = southbound.getDataPathId(bridgeNode);
- Ip ip = sfcUtils.getSfIp(serviceFunction);
- String sfIpAddr = String.valueOf(ip.getIp().getValue());
- int sfIpPort = ip.getPort().getValue(); //GPE_PORT
- String sfDplPortName = sfcUtils.getSfDplPortId(serviceFunction);
- long sfOfPort = getSfPort(bridgeNode, sfDplPortName);
- String sfMac = getMacFromExternalIds(bridgeNode, sfDplPortName);
- if (sfMac == null) {
- LOG.warn("handleSff: could not find mac for {} on {}", sfDplPortName, bridgeNode);
- return;
- }
- //should be sffdplport, but they should all be the same 6633/4790
- // TODO: Coexistence: SFC flows should take this using new sf dpl augmentation
- if (addSfFlows) {
- sfcClassifierService.program_sfEgress(dataPathId, sfIpPort, rsp.getName().getValue(), true);
- sfcClassifierService.program_sfIngress(dataPathId, sfIpPort, sfOfPort, sfIpAddr, sfDplPortName,
- rsp.getName().getValue(), true);
- }
- sfcClassifierService.programStaticArpEntry(dataPathId, 0L, sfMac, sfIpAddr,
- rsp.getName().getValue(), true);
- } else {
- LOG.info("handleSf: sf and bridge are not on the same node: {} - {}, do nothing",
- bridgeNode.getNodeId().getValue(), serviceFunction.getName().getValue());
- }
- }
-
- private boolean isSffOnBridge(Node bridgeNode, ServiceFunctionForwarder serviceFunctionForwarder) {
- String localIp = "";
- Ip ip = sfcUtils.getSffIp(serviceFunctionForwarder);
- Node ovsdbNode = southbound.readOvsdbNode(bridgeNode);
- if (ovsdbNode != null) {
- localIp = getRemoteIp(ovsdbNode);
- }
- LOG.info("isSffOnBridge: {}: {}, localIp/remoteIp: {}, sff ip: {}",
- bridgeNode.getNodeId().getValue(),
- localIp.equals(String.valueOf(ip.getIp().getValue())),
- localIp, ip.getIp().getValue());
- return localIp.equals(String.valueOf(ip.getIp().getValue()));
- }
-
- private String getLocalip(Node ovsdbNode) {
- Preconditions.checkNotNull(ovsdbNode, "The ovsdbNode was null");
- String localIp = null;
- if (ovsdbNode != null) {
- OvsdbNodeAugmentation ovsdbNodeAugmentation = ovsdbNode.getAugmentation(OvsdbNodeAugmentation.class);
- if (ovsdbNodeAugmentation != null && ovsdbNodeAugmentation.getOpenvswitchOtherConfigs() != null) {
- localIp = southbound.getOtherConfig(ovsdbNode, OvsdbTables.OPENVSWITCH, TUNNEL_ENDPOINT_KEY);
- }
- }
- if (localIp == null) {
- LOG.warn("local_ip was not found for node: {}", ovsdbNode);
- localIp = "";
- }
- return localIp;
- }
-
- private String getRemoteIp(Node ovsdbNode) {
- Preconditions.checkNotNull(ovsdbNode, "The ovsdbNode was null");
- String ip = null;
- OvsdbNodeAugmentation ovsdbNodeAugmentation = ovsdbNode.getAugmentation(OvsdbNodeAugmentation.class);
- if (ovsdbNodeAugmentation != null && ovsdbNodeAugmentation.getConnectionInfo() != null) {
- ip = ovsdbNodeAugmentation.getConnectionInfo().getRemoteIp().getIpv4Address().getValue();
- }
- if (ip == null) {
- LOG.warn("remote_ip was not found for node: {}", ovsdbNode);
- ip = "";
- }
- return ip;
- }
-
- private boolean isSfOnBridge(Node bridgeNode, ServiceFunction serviceFunction) {
- String sfDplPortName = sfcUtils.getSfDplPortId(serviceFunction);
- long sfOfPort = getSfPort(bridgeNode, sfDplPortName);
- LOG.info("isSfOnBridge: {}: {}, sfOfPort: {}", bridgeNode.getNodeId().getValue(), sfOfPort != 0L, sfOfPort);
- return sfOfPort != 0L;
- }
-
- private Ace getAceFromRenderedServicePath(RenderedServicePath rsp) {
- Preconditions.checkNotNull(rsp, "RSP cannot be null");
- Ace ace;
- //String rspName = rsp.getName().getValue();
- //String rspNameSuffix = "_rsp";
- //String sfcName = rspName.substring(0, rspName.length() - rspNameSuffix.length());
- //String sfcName = rsp.getServiceChainName().getValue()
- //LOG.info("getAceFromRenderedServicePath: rsp: {}, sfcName: {}", rsp, sfcName);
- ace = sfcUtils.getAce(rsp);
-
- return ace;
- }
-
- private RenderedServicePath getRenderedServicePath (Ace entry) {
- RenderedServicePath rsp = null;
- RedirectToSfc sfcRedirect = entry.getActions().getAugmentation(RedirectToSfc.class);
- LOG.debug("getRenderedServicePath: Processing ACL entry = {} sfcRedirect = {}",
- entry.getRuleName(), sfcRedirect);
- if (sfcRedirect == null) {
- LOG.warn("getRenderedServicePath: sfcRedirect is null");
- return null;
- }
-
- if (sfcRedirect.getRspName() != null) {
- rsp = getRenderedServicePathFromRsp(sfcRedirect.getRspName());
- } else if (sfcRedirect.getSfpName() != null) {
- LOG.warn("getRenderedServicePath: by sfp not handled yet");
- } else {
- rsp = getRenderedServicePathFromSfc(entry);
- }
- LOG.info("getRenderedServicePath: rsp: {}", rsp);
- return rsp;
- }
-
- private RenderedServicePath getRenderedServicePathFromRsp(String rspName) {
- return sfcUtils.getRsp(rspName);
- }
-
- private RenderedServicePath getRenderedServicePathFromSfc (Ace entry) {
- RedirectToSfc sfcRedirect = entry.getActions().getAugmentation(RedirectToSfc.class);
- LOG.debug("getRenderedServicePathFromSfc: Processing ACL entry = {} sfcRedirect = {}",
- entry.getRuleName(), sfcRedirect);
- if (sfcRedirect == null) {
- LOG.warn("getRenderedServicePathFromSfc: sfcRedirect is null");
- return null;
- }
-
- String sfcName = sfcRedirect.getSfcName();
- ServiceFunctionPath sfp = sfcUtils.getSfp(sfcName);
- if (sfp == null || sfp.getName() == null) {
- LOG.warn("There is no configured SFP with sfcName = {}; so skip installing the ACL entry!!", sfcName);
- return null;
- }
-
- LOG.debug("getRenderedServicePathFromSfc: Processing Redirect to SFC = {}, SFP = {}", sfcName, sfp);
- // If RSP doesn't exist, create an RSP.
- String sfpName = sfp.getName().getValue();
- RenderedServicePath rsp = sfcUtils.getRspforSfp(sfpName);
- String rspName = sfp.getName().getValue() + "_rsp";
- if (rsp == null) {
- if (!sfcRedirect.isRenderRsp()) {
- LOG.info("getRenderedServicePathFromSfc: will not create RSP");
- return null;
- }
- LOG.info("getRenderedServicePathFromSfc: No configured RSP corresponding to SFP = {}, "
- + "Creating new RSP = {}", sfpName, rspName);
- CreateRenderedPathInput rspInput = new CreateRenderedPathInputBuilder()
- .setParentServiceFunctionPath(sfpName)
- .setName(rspName)
- .setSymmetric(sfp.isSymmetric())
- .build();
- rsp = SfcProviderRenderedPathAPI.createRenderedServicePathAndState(sfp, rspInput);
- if (rsp == null) {
- LOG.warn("getRenderedServicePathFromSfc: failed to add RSP");
- return null;
- }
-
- // If SFP is symmetric, create RSP in the reverse direction.
- if (sfp.isSymmetric()) {
- LOG.warn("getRenderedServicePathFromSfc: symmetric RSP is not supported yet");
- /*LOG.info("SFP = {} is symmetric, installing RSP in the reverse direction!!", sfpName);
- String rspNameRev = rspName + "-Reverse";
- RenderedServicePath rspReverse = mdsalUtils.read(LogicalDatastoreType.OPERATIONAL,
- sfcUtils.getRspId(rspNameRev));
- if (rspReverse == null) {
- rspReverse = SfcProviderRenderedPathAPI.createSymmetricRenderedServicePathAndState(rsp);
- if (rspReverse == null) {
- LOG.warn("failed to add reverse RSP");
- return null;
- }
- }*/
- }
- }
- return rsp;
- }
-
- private long getSfPort(Node bridgeNode, String sfPortName) {
- return getOFPort(bridgeNode, sfPortName);
- }
-
- private long getOFPort(Node bridgeNode, String portName) {
- long ofPort = 0L;
- OvsdbTerminationPointAugmentation port =
- southbound.extractTerminationPointAugmentation(bridgeNode, portName);
- if (port != null) {
- ofPort = southbound.getOFPort(port);
- }
- if (ofPort == 0L) {
- for (int i = 0; i < 5; i++) {
- LOG.info("Looking for ofPort {}, try: {}", portName, i);
- TerminationPoint tp = southbound.readTerminationPoint(bridgeNode, null, portName);
- if (tp != null) {
- port = tp.getAugmentation(OvsdbTerminationPointAugmentation.class);
- if (port != null) {
- ofPort = southbound.getOFPort(port);
- LOG.info("found ofPort {} - {}, try: {}", portName, ofPort, i);
- break;
- }
- }
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- LOG.error("Interrupted while waiting for ofPort {}", portName, e);
- }
- }
- }
- return ofPort;
- }
-
- private String getMacFromExternalIds(Node bridgeNode, String portName) {
- String mac = null;
- OvsdbTerminationPointAugmentation port = southbound.getTerminationPointOfBridge(bridgeNode, portName);
- LOG.info("getMac: portName: {}, bridgeNode: {},,, port: {}", portName, bridgeNode, port);
- if (port != null && port.getInterfaceExternalIds() != null) {
- mac = southbound.getInterfaceExternalIdsValue(port, Constants.EXTERNAL_ID_VM_MAC);
- }
- return mac;
- }
-
- @Override
- public void setDependencies(ServiceReference serviceReference) {
- nodeCacheManager = (NodeCacheManager) ServiceHelper.getGlobalInstance(NodeCacheManager.class, this);
- southbound = (Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this);
- sfcClassifierService =
- (ISfcClassifierService) ServiceHelper.getGlobalInstance(ISfcClassifierService.class, this);
- LOG.info("sfcClassifierService= {}", sfcClassifierService);
- }
-}
+++ /dev/null
-/*
- * Copyright © 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc.workaround.services;
-
-import org.opendaylight.netvirt.utils.mdsal.openflow.MatchUtils;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.Matches;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.matches.ace.type.AceEth;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.matches.ace.type.AceIp;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.matches.ace.type.ace.ip.ace.ip.version.AceIpv4;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.matches.ace.type.ace.ip.ace.ip.version.AceIpv6;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.EtherType;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class AclMatches {
- private static final Logger LOG = LoggerFactory.getLogger(AclMatches.class);
- MatchBuilder matchBuilder;
- Matches matches;
-
- public AclMatches(Matches matches) {
- matchBuilder = new MatchBuilder();
- this.matches = matches;
- }
-
- /**
- * Convert the ACL into an OpenFlow {@link MatchBuilder}
- * @return {@link MatchBuilder}
- */
- //TODO: Matches will overwrite previous matches for ethernet and ip since these methods
- // can be called successively for the same ACL.
- // This requires fixing the MatchUtils to preserve previously set fields.
- protected MatchBuilder buildMatch() {
- if (matches.getAceType() instanceof AceEth) {
- addEthMatch();
- } else if (matches.getAceType() instanceof AceIp) {
- addIpMatch();
- }
-
- LOG.info("buildMatch: {}", matchBuilder.build());
- return matchBuilder;
- }
-
- private void addEthMatch() {
- AceEth aceEth = (AceEth) matches.getAceType();
- MatchUtils.createEthSrcDstMatch(matchBuilder, aceEth.getSourceMacAddress(),
- aceEth.getDestinationMacAddress());
- }
-
- private void addIpMatch() {
- AceIp aceIp = (AceIp)matches.getAceType();
-
- if (aceIp.getDscp() != null) {
- MatchUtils.addDscp(matchBuilder, aceIp.getDscp().getValue());
- }
-
- if (aceIp.getProtocol() != null) {
- addIpProtocolMatch(aceIp);
- }
-
- if (aceIp.getAceIpVersion() instanceof AceIpv4) {
- addIpV4Match(aceIp);
- }
-
- if (aceIp.getAceIpVersion() instanceof AceIpv6) {
- addIpV6Match(aceIp);
- }
- }
-
- private void addIpProtocolMatch(AceIp aceIp) {
- int srcPort = 0;
- int dstPort = 0;
-
- // TODO Ranges are not supported yet
- if (aceIp.getSourcePortRange() != null && aceIp.getSourcePortRange().getLowerPort() != null) {
- srcPort = aceIp.getSourcePortRange().getLowerPort().getValue();
- }
- if (aceIp.getDestinationPortRange() != null && aceIp.getDestinationPortRange().getLowerPort() != null) {
- dstPort = aceIp.getDestinationPortRange().getLowerPort().getValue();
- }
- MatchUtils.createIpProtocolMatch(matchBuilder, aceIp.getProtocol());
- MatchUtils.addLayer4Match(matchBuilder, aceIp.getProtocol().intValue(), srcPort, dstPort);
- }
-
- private void addIpV4Match(AceIp aceIp) {
- AceIpv4 aceIpv4 = (AceIpv4)aceIp.getAceIpVersion();
-
- MatchUtils.createEtherTypeMatch(matchBuilder, new EtherType(MatchUtils.ETHERTYPE_IPV4));
- matchBuilder = MatchUtils.addRemoteIpPrefix(matchBuilder, aceIpv4.getSourceIpv4Network(),
- aceIpv4.getDestinationIpv4Network());
- }
-
- private void addIpV6Match(AceIp aceIp) {
- AceIpv6 aceIpv6 = (AceIpv6)aceIp.getAceIpVersion();
-
- MatchUtils.createEtherTypeMatch(matchBuilder, new EtherType(MatchUtils.ETHERTYPE_IPV6));
- matchBuilder = MatchUtils.addRemoteIpv6Prefix(matchBuilder, aceIpv6.getSourceIpv6Network(),
- aceIpv6.getDestinationIpv6Network());
- }
-}
+++ /dev/null
-/*
- * Copyright © 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc.workaround.services;
-
-import java.util.ArrayList;
-import java.util.List;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.AccessListsBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.Ipv4Acl;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.Acl;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.AclBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.AccessListEntriesBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.Ace;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.AceBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.ActionsBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.MatchesBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.actions.packet.handling.PermitBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.matches.ace.type.AceIpBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.packet.fields.rev160218.acl.transport.header.fields.DestinationPortRangeBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.packet.fields.rev160218.acl.transport.header.fields.SourcePortRangeBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.acl.rev150105.RedirectToSfc;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.acl.rev150105.RedirectToSfcBuilder;
-
-public class AclUtils {
- private static final String ACLNAME= "httpAcl";
- private static final String RULENAME= "httpRule";
- private static final String SFCNAME = "SFC";
-
- public MatchesBuilder matchesBuilder(MatchesBuilder matchesBuilder, int dstPort) {
- SourcePortRangeBuilder sourcePortRangeBuilder = new SourcePortRangeBuilder()
- .setLowerPort(PortNumber.getDefaultInstance("0"))
- .setUpperPort(PortNumber.getDefaultInstance("0"));
-
- PortNumber portNumber = new PortNumber(dstPort);
- DestinationPortRangeBuilder destinationPortRangeBuilder = new DestinationPortRangeBuilder()
- .setLowerPort(portNumber)
- .setUpperPort(portNumber);
-
- AceIpBuilder aceIpBuilder = new AceIpBuilder()
- .setSourcePortRange(sourcePortRangeBuilder.build())
- .setDestinationPortRange(destinationPortRangeBuilder.build())
- .setProtocol((short)6);
-
- return matchesBuilder.setAceType(aceIpBuilder.build());
- }
-
- public ActionsBuilder actionsBuilder(ActionsBuilder actionsBuilder, Boolean permit) {
- return actionsBuilder.setPacketHandling(new PermitBuilder().setPermit(permit).build());
- }
-
- public ActionsBuilder actionsBuilder(ActionsBuilder actionsBuilder, String sfcName, boolean renderRsp) {
- RedirectToSfcBuilder redirectToSfcBuilder = new RedirectToSfcBuilder()
- .setSfcName(sfcName)
- .setRenderRsp(renderRsp);
-
- return actionsBuilder.addAugmentation(RedirectToSfc.class, redirectToSfcBuilder.build());
- }
-
- public AceBuilder aceBuilder(AceBuilder accessListEntryBuilder,
- String ruleName,
- MatchesBuilder matchesBuilder,
- ActionsBuilder actionsBuilder) {
- return accessListEntryBuilder
- .setRuleName(ruleName)
- .setMatches(matchesBuilder.build())
- .setActions(actionsBuilder.build());
- }
-
- public AccessListEntriesBuilder accessListEntriesBuidler(AccessListEntriesBuilder accessListEntriesBuilder,
- AceBuilder aceBuilder) {
- List<Ace> aceList = new ArrayList<>();
- aceList.add(aceBuilder.build());
-
- return accessListEntriesBuilder.setAce(aceList);
- }
-
- public AclBuilder aclBuilder(AclBuilder aclBuilder,
- String aclName,
- AccessListEntriesBuilder accessListEntriesBuilder) {
- return aclBuilder
- .setAclName(aclName)
- .setAclType(Ipv4Acl.class)
- .setAccessListEntries(accessListEntriesBuilder.build());
- }
-
- public AccessListsBuilder accessListsbuilder(AccessListsBuilder accessListsBuilder,
- AclBuilder aclBuilder) {
- List<Acl> aclList = new ArrayList<>();
- aclList.add(aclBuilder.build());
-
- return accessListsBuilder.setAcl(aclList);
- }
-
- public AccessListsBuilder accessListsBuilder(boolean renderRsp) {
- String ruleName = RULENAME;
- String sfcName = SFCNAME;
- MatchesBuilder matchesBuilder = matchesBuilder(new MatchesBuilder(), 80);
- ActionsBuilder actionsBuilder = actionsBuilder(new ActionsBuilder(), sfcName, renderRsp);
- AceBuilder accessListEntryBuilder =
- aceBuilder(new AceBuilder(), ruleName, matchesBuilder, actionsBuilder);
- AccessListEntriesBuilder accessListEntriesBuilder =
- accessListEntriesBuidler(new AccessListEntriesBuilder(), accessListEntryBuilder);
- AclBuilder accessListBuilder =
- aclBuilder(new AclBuilder(), ACLNAME, accessListEntriesBuilder);
- AccessListsBuilder accessListsBuilder =
- accessListsbuilder(new AccessListsBuilder(), accessListBuilder);
- return accessListsBuilder;
- }
-}
+++ /dev/null
-/*
- * Copyright © 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc.workaround.services;
-
-import java.util.HashMap;
-import java.util.Map;
-import org.opendaylight.netvirt.utils.mdsal.openflow.FlowUtils;
-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.inventory.rev130819.nodes.NodeBuilder;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class FlowCache {
- private static final Logger LOG = LoggerFactory.getLogger(FlowCache.class);
- private Map<String, Map<Integer, InstanceIdentifier<Flow>>> flowCache = new HashMap<>();
-
- public void addFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder, String rspName, int flowId) {
- Map<Integer, InstanceIdentifier<Flow>> flowMap = flowCache.get(rspName);
- if (flowMap == null) {
- LOG.info("addFlow: adding new flowMap for {}({})", rspName, flowId);
- flowMap = new HashMap<>();
- }
- InstanceIdentifier<Flow> path = FlowUtils.createFlowPath(flowBuilder, nodeBuilder);
- flowMap.put(flowId, path);
- flowCache.put(rspName, flowMap);
- LOG.info("addFlow: added {}({}) {} to cache size {} - {}", rspName, flowId, path,
- flowCache.size(), flowCache);
- }
-
- public void removeFlow(String rspName, int flowId) {
- Map<Integer, InstanceIdentifier<Flow>> flowMap = flowCache.get(rspName);
- if (flowMap != null) {
- flowMap.remove(flowId);
- if (flowMap.isEmpty()) {
- flowCache.remove(rspName);
- LOG.info("removeFlow: removed flowMap {}({}) from cache size {}", rspName, flowId,
- flowCache.size());
- } else {
- flowCache.put(rspName, flowMap);
- }
- }
- LOG.info("removeFlow: removed {}({}) from cache size {}", rspName, flowId, flowCache.size());
- }
-
- public Map<Integer, InstanceIdentifier<Flow>> getFlows(String rspName) {
- return flowCache.get(rspName);
- }
-}
+++ /dev/null
-/*
- * Copyright © 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc.workaround.services;
-
-public class FlowNames {
-
- public static String getSfcIngressClass(String ruleName, long nsp, short nsi) {
- return "sfcIngressClass_" + nsp + "_" + nsi + "_" + ruleName;
- }
-
- public static String getSfcTable(long vxGpeOfPort) {
- return "sfcTable_" + vxGpeOfPort;
- }
-
- public static String getSfcEgressClass1(long vxGpeOfPort) {
- return "sfcEgressClass1_" + vxGpeOfPort;
- }
-
- public static String getSfcEgressClass(long vxGpeOfPort, long nsp, short nsi) {
- return "sfcEgressClass_" + nsp + "_" + nsi + "_" + vxGpeOfPort;
- }
-
- public static String getSfcEgressClassBypass(long nsp, short nsi, long sfOfPort) {
- return "sfcEgressClassBypass_" + nsp + "_" + nsi + "_" + sfOfPort;
- }
-
- public static String getSfEgress(int dstPort) {
- return "sfEgress_" + dstPort;
- }
-
- public static String getSfIngress(int dstPort, String ipAddress) {
- return "sfIngress_" + dstPort + "_" + ipAddress;
- }
-
- public static String getArpResponder(String ipAddress) {
- return "ArpResponder_" + ipAddress;
- }
-}
+++ /dev/null
-/*
- * Copyright © 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc.workaround.services;
-
-import com.google.common.util.concurrent.CheckedFuture;
-import java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.AbstractServiceInstance;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.netvirt.openstack.netvirt.sfc.NshUtils;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-import org.opendaylight.netvirt.openstack.netvirt.providers.ConfigInterface;
-import org.opendaylight.netvirt.openstack.netvirt.sfc.ISfcClassifierService;
-import org.opendaylight.netvirt.utils.mdsal.openflow.ActionUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.FlowUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.InstructionUtils;
-import org.opendaylight.netvirt.utils.mdsal.openflow.MatchUtils;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.Matches;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Prefix;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
-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.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.FlowCookie;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.OutputPortValues;
-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.ApplyActionsCaseBuilder;
-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;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.EtherType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.dst.choice.grouping.dst.choice.DstNxRegCaseBuilder;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class SfcClassifierService extends AbstractServiceInstance implements ConfigInterface, ISfcClassifierService {
- private static final Logger LOG = LoggerFactory.getLogger(SfcClassifierService.class);
- private static final short UDP_SHORT = 17;
- static int cookieIndex = 0;
- private FlowCache flowCache = new FlowCache();
-
- private enum FlowID {
- FLOW_INGRESSCLASS(1), FLOW_SFINGRESS(2), FLOW_SFEGRESS(3), FLOW_SFARP(4),
- FLOW_EGRESSCLASSUNUSED(5), FLOW_EGRESSCLASS(6), FLOW_EGRESSCLASSBYPASS(7), FLOW_SFCTABLE(8);
-
- private int value;
- FlowID(int value) {
- this.value = value;
- }
- }
-
- private BigInteger getCookie(FlowID flowID) {
- String cookieString = String.format("1110%02d%010d", flowID.value, cookieIndex++);
- return new BigInteger(cookieString, 16);
- }
-
- private BigInteger getCookie(FlowID flowID, short nsp, short nsi) {
- String cookieString = String.format("1110%02d%03d%03d0%03d", flowID.value, 0, nsp, nsi);
- return new BigInteger(cookieString, 16);
- }
-
- public SfcClassifierService(Service service) {
- super(service);
- }
-
- public SfcClassifierService() {
- super(Service.SFC_CLASSIFIER);
- }
-
- @Override
- public void setDependencies(BundleContext bundleContext, ServiceReference serviceReference) {
- super.setDependencies(bundleContext.getServiceReference(ISfcClassifierService.class.getName()), this);
- }
-
- @Override
- public void setDependencies(Object impl) {}
-
- private FlowBuilder initFlowBuilder(FlowBuilder flowBuilder, String flowName, short table, FlowID flowID) {
- FlowUtils.initFlowBuilder(flowBuilder, flowName, table)
- .setCookie(new FlowCookie(getCookie(flowID)))
- .setCookieMask(new FlowCookie(getCookie(flowID)));
- return flowBuilder;
- }
-
- private FlowBuilder initFlowBuilder(FlowBuilder flowBuilder, String flowName, short table, FlowID flowID,
- short nsp, short nsi) {
- FlowUtils.initFlowBuilder(flowBuilder, flowName, table)
- .setCookie(new FlowCookie(getCookie(flowID, nsp, nsi)))
- .setCookieMask(new FlowCookie(getCookie(flowID, nsp, nsi)));
- return flowBuilder;
- }
-
- private void writeFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder, String rspName, FlowID flowID) {
- flowCache.addFlow(flowBuilder, nodeBuilder, rspName, flowID.value);
- writeFlow(flowBuilder, nodeBuilder);
- }
-
- private void removeFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder, String rspName, FlowID flowID) {
- flowCache.removeFlow(rspName, flowID.value);
- removeFlow(flowBuilder, nodeBuilder);
- }
-
- @Override
- public void programIngressClassifier(long dataPathId, String ruleName, Matches matches, long nsp, short nsi,
- NshUtils nshHeader, long vxGpeOfPort, String rspName, boolean write) {
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dataPathId);
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = FlowNames.getSfcIngressClass(ruleName, nsp, nsi);
- initFlowBuilder(flowBuilder, flowName, getTable(), FlowID.FLOW_INGRESSCLASS,
- (short)nshHeader.getNshNsp(), nshHeader.getNshNsi());
-
- MatchBuilder matchBuilder = new AclMatches(matches).buildMatch();
- MatchUtils.addNxRegMatch(matchBuilder,
- MatchUtils.RegMatch.of(FlowUtils.REG_FIELD, FlowUtils.REG_VALUE_FROM_LOCAL));
- flowBuilder.setMatch(matchBuilder.build());
-
- if (write) {
- ActionBuilder ab = new ActionBuilder();
- List<Action> actionList = new ArrayList<>();
-
- ab.setAction(ActionUtils.nxMoveTunIdtoNshc2());
- ab.setOrder(actionList.size());
- ab.setKey(new ActionKey(actionList.size()));
- actionList.add(ab.build());
-
- getNshAction(nshHeader, actionList);
-
- if (vxGpeOfPort != 0) {
- ab.setAction(ActionUtils.outputAction(FlowUtils.getNodeConnectorId(dataPathId, vxGpeOfPort)));
- ab.setOrder(actionList.size());
- ab.setKey(new ActionKey(actionList.size()));
- actionList.add(ab.build());
- } else {
- ab.setAction(ActionUtils.nxResubmitAction(null, Service.CLASSIFIER.getTable()));
- ab.setOrder(actionList.size());
- ab.setKey(new ActionKey(actionList.size()));
- actionList.add(ab.build());
- }
-
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
-
- InstructionBuilder ib = new InstructionBuilder();
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
- ib.setOrder(0);
- ib.setKey(new InstructionKey(0));
- List<Instruction> instructions = new ArrayList<>();
- instructions.add(ib.build());
-
- InstructionsBuilder isb = new InstructionsBuilder();
- isb.setInstruction(instructions);
- flowBuilder.setInstructions(isb.build());
- writeFlow(flowBuilder, nodeBuilder, rspName, FlowID.FLOW_INGRESSCLASS);
- } else {
- removeFlow(flowBuilder, nodeBuilder, rspName, FlowID.FLOW_INGRESSCLASS);
- }
- }
-
- @Override
- public void programSfcTable(long dataPathId, long vxGpeOfPort, short goToTableId, boolean write) {
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dataPathId);
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = FlowNames.getSfcTable(vxGpeOfPort);
- initFlowBuilder(flowBuilder, flowName, getTable(Service.CLASSIFIER), FlowID.FLOW_SFCTABLE)
- .setPriority(1000);
-
- MatchBuilder matchBuilder = new MatchBuilder();
- MatchUtils.createInPortMatch(matchBuilder, dataPathId, vxGpeOfPort);
- flowBuilder.setMatch(matchBuilder.build());
-
- if (write) {
- InstructionsBuilder isb = new InstructionsBuilder();
- List<Instruction> instructions = new ArrayList<>();
- InstructionBuilder ib =
- InstructionUtils.createGotoTableInstructions(new InstructionBuilder(), goToTableId);
- ib.setOrder(0);
- ib.setKey(new InstructionKey(0));
- instructions.add(ib.build());
-
- isb.setInstruction(instructions);
- flowBuilder.setInstructions(isb.build());
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
- }
-
- @Override
- public void programEgressClassifier1(long dataPathId, long vxGpeOfPort, long nsp, short nsi,
- int tunnelOfPort, int tunnelId, short gotoTableId, boolean write) {
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dataPathId);
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = FlowNames.getSfcEgressClass1(vxGpeOfPort);
- initFlowBuilder(flowBuilder, flowName, getTable(Service.CLASSIFIER), FlowID.FLOW_EGRESSCLASSUNUSED,
- (short)nsp, nsi);
-
- MatchBuilder matchBuilder = new MatchBuilder();
- MatchUtils.createInPortMatch(matchBuilder, dataPathId, vxGpeOfPort);
- MatchUtils.addNxNspMatch(matchBuilder, nsp);
- MatchUtils.addNxNsiMatch(matchBuilder, nsi);
- flowBuilder.setMatch(matchBuilder.build());
-
- if (write) {
- InstructionsBuilder isb = new InstructionsBuilder();
- List<Instruction> instructions = new ArrayList<>();
-
- InstructionBuilder ib = InstructionUtils.createGotoTableInstructions(new InstructionBuilder(), getTable());
- ib.setOrder(instructions.size());
- ib.setKey(new InstructionKey(instructions.size()));
- instructions.add(ib.build());
-
- isb.setInstruction(instructions);
- flowBuilder.setInstructions(isb.build());
- writeFlow(flowBuilder, nodeBuilder);
- } else {
- removeFlow(flowBuilder, nodeBuilder);
- }
- }
-
- @Override
- public void programEgressClassifier(long dataPathId, long vxGpeOfPort, long nsp, short nsi,
- long sfOfPort, int tunnelId, String rspName, boolean write) {
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dataPathId);
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = FlowNames.getSfcEgressClass(vxGpeOfPort, nsp, nsi);
- initFlowBuilder(flowBuilder, flowName, getTable(Service.SFC_CLASSIFIER), FlowID.FLOW_EGRESSCLASS,
- (short)nsp, nsi);
-
- MatchBuilder matchBuilder = new MatchBuilder();
- MatchUtils.createInPortMatch(matchBuilder, dataPathId, vxGpeOfPort);
- MatchUtils.addNxNspMatch(matchBuilder, nsp);
- MatchUtils.addNxNsiMatch(matchBuilder, nsi);
- flowBuilder.setMatch(matchBuilder.build());
-
- if (write) {
- InstructionsBuilder isb = new InstructionsBuilder();
- List<Instruction> instructions = new ArrayList<>();
- List<Action> actionList = new ArrayList<>();
-
- ActionBuilder ab = new ActionBuilder();
-
- ab.setAction(
- ActionUtils.nxLoadRegAction(new DstNxRegCaseBuilder().setNxReg(FlowUtils.REG_FIELD).build(),
- BigInteger.valueOf(FlowUtils.REG_VALUE_FROM_LOCAL)));
- ab.setOrder(actionList.size());
- ab.setKey(new ActionKey(actionList.size()));
- actionList.add(ab.build());
-
- ab.setAction(ActionUtils.nxMoveNshc2ToTunId());
- ab.setOrder(actionList.size());
- ab.setKey(new ActionKey(actionList.size()));
- actionList.add(ab.build());
-
- ab.setAction(ActionUtils.nxResubmitAction((int)sfOfPort, getTable(Service.CLASSIFIER)));
- ab.setOrder(actionList.size());
- ab.setKey(new ActionKey(actionList.size()));
- actionList.add(ab.build());
-
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
- InstructionBuilder ib = new InstructionBuilder();
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
-
- ib.setOrder(0);
- ib.setKey(new InstructionKey(0));
- instructions.add(ib.build());
-
- isb.setInstruction(instructions);
- flowBuilder.setInstructions(isb.build());
- writeFlow(flowBuilder, nodeBuilder, rspName, FlowID.FLOW_EGRESSCLASS);
- } else {
- removeFlow(flowBuilder, nodeBuilder, rspName, FlowID.FLOW_EGRESSCLASS);
- }
- }
-
- @Override
- public void programEgressClassifierBypass(long dataPathId, long vxGpeOfPort, long nsp, short nsi,
- long sfOfPort, int tunnelId, String rspName, boolean write) {
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dataPathId);
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = FlowNames.getSfcEgressClassBypass(nsp, nsi, sfOfPort);
- initFlowBuilder(flowBuilder, flowName, getTable(Service.CLASSIFIER),
- FlowID.FLOW_EGRESSCLASSBYPASS, (short)nsp, nsi)
- .setPriority(40000);
-
- MatchBuilder matchBuilder = new MatchBuilder();
- MatchUtils.createInPortMatch(matchBuilder, dataPathId, sfOfPort);
- MatchUtils.addNxRegMatch(matchBuilder,
- MatchUtils.RegMatch.of(FlowUtils.REG_FIELD, FlowUtils.REG_VALUE_FROM_LOCAL));
- MatchUtils.addNxNspMatch(matchBuilder, nsp);
- MatchUtils.addNxNsiMatch(matchBuilder, nsi);
- flowBuilder.setMatch(matchBuilder.build());
-
- if (write) {
- ActionBuilder ab = new ActionBuilder();
- org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action popNshAction =
- ActionUtils.nxPopNshAction();
- ab.setAction(popNshAction);
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
-
- List<Action> actionList = new ArrayList<>();
- actionList.add(ab.build());
-
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
-
- InstructionBuilder popNshIb = new InstructionBuilder();
- popNshIb.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
- popNshIb.setOrder(0);
- popNshIb.setKey(new InstructionKey(0));
-
- // This will do a goto table
- InstructionBuilder mutableIb;
- mutableIb = this.getMutablePipelineInstructionBuilder();
- mutableIb.setOrder(1);
- mutableIb.setKey(new InstructionKey(1));
-
- List<Instruction> instructions = new ArrayList<>();
- instructions.add(popNshIb.build());
- instructions.add(mutableIb.build());
-
- InstructionsBuilder isb = new InstructionsBuilder();
- isb.setInstruction(instructions);
- flowBuilder.setInstructions(isb.build());
- writeFlow(flowBuilder, nodeBuilder, rspName, FlowID.FLOW_EGRESSCLASSBYPASS);
- } else {
- removeFlow(flowBuilder, nodeBuilder, rspName, FlowID.FLOW_EGRESSCLASSBYPASS);
- }
- }
-
- // packet from sf to sff that need to go out local
- @Override
- public void program_sfEgress(long dataPathId, int dstPort, String rspName, boolean write) {
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dataPathId);
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = FlowNames.getSfEgress(dstPort);
- initFlowBuilder(flowBuilder, flowName, getTable(), FlowID.FLOW_SFEGRESS);
-
- MatchBuilder matchBuilder = new MatchBuilder();
- MatchUtils.createIpProtocolMatch(matchBuilder, UDP_SHORT);
- MatchUtils.addLayer4Match(matchBuilder, UDP_SHORT, 0, dstPort);
- MatchUtils.addNxRegMatch(matchBuilder,
- MatchUtils.RegMatch.of(FlowUtils.REG_FIELD, FlowUtils.REG_VALUE_FROM_LOCAL));
- flowBuilder.setMatch(matchBuilder.build());
-
- if (write) {
- InstructionBuilder ib = new InstructionBuilder();
- InstructionsBuilder isb = new InstructionsBuilder();
- List<Instruction> instructions = new ArrayList<>();
- InstructionUtils.createLocalInstructions(ib, dataPathId);
- ib.setOrder(0);
- ib.setKey(new InstructionKey(0));
- instructions.add(ib.build());
-
- isb.setInstruction(instructions);
- flowBuilder.setInstructions(isb.build());
- writeFlow(flowBuilder, nodeBuilder, rspName, FlowID.FLOW_SFEGRESS);
- } else {
- removeFlow(flowBuilder, nodeBuilder, rspName, FlowID.FLOW_SFEGRESS);
- }
- }
-
- // looped back sff to sf packets
- @Override
- public void program_sfIngress(long dataPathId, int dstPort, long sfOfPort,
- String ipAddress, String sfDplName, String rspName, boolean write) {
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dataPathId);
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = FlowNames.getSfIngress(dstPort, ipAddress);
- initFlowBuilder(flowBuilder, flowName, Service.CLASSIFIER.getTable(), FlowID.FLOW_SFINGRESS);
-
- MatchBuilder matchBuilder = new MatchBuilder();
- MatchUtils.createIpProtocolMatch(matchBuilder, UDP_SHORT);
- Ipv4Prefix ipCidr = MatchUtils.iPv4PrefixFromIPv4Address(ipAddress);
- MatchUtils.createDstL3IPv4Match(matchBuilder, new Ipv4Prefix(ipCidr));
- MatchUtils.addLayer4Match(matchBuilder, UDP_SHORT, 0, dstPort);
- flowBuilder.setMatch(matchBuilder.build());
-
- if (write) {
- InstructionBuilder ib = new InstructionBuilder();
- InstructionsBuilder isb = new InstructionsBuilder();
- List<Instruction> instructions = new ArrayList<>();
- InstructionUtils.createOutputPortInstructions(ib, dataPathId, sfOfPort);
-
- ib.setOrder(0);
- ib.setKey(new InstructionKey(0));
- instructions.add(ib.build());
-
- isb.setInstruction(instructions);
- flowBuilder.setInstructions(isb.build());
- writeFlow(flowBuilder, nodeBuilder, rspName, FlowID.FLOW_SFINGRESS);
- } else {
- removeFlow(flowBuilder, nodeBuilder, rspName, FlowID.FLOW_SFINGRESS);
- }
- }
-
- @Override
- public void programStaticArpEntry(long dataPathId, long ofPort, String macAddressStr,
- String ipAddress, String rspName, boolean write) {
- NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dataPathId);
- FlowBuilder flowBuilder = new FlowBuilder();
- String flowName = FlowNames.getArpResponder(ipAddress);
- initFlowBuilder(flowBuilder, flowName, getTable(Service.ARP_RESPONDER), FlowID.FLOW_SFARP)
- .setPriority(1024);
-
- MacAddress macAddress = new MacAddress(macAddressStr);
-
- MatchBuilder matchBuilder = new MatchBuilder();
- MatchUtils.createInPortReservedMatch(matchBuilder, dataPathId, OutputPortValues.LOCAL.toString());
- MatchUtils.createEtherTypeMatch(matchBuilder, new EtherType(Constants.ARP_ETHERTYPE));
- MatchUtils.createArpDstIpv4Match(matchBuilder, MatchUtils.iPv4PrefixFromIPv4Address(ipAddress));
- flowBuilder.setMatch(matchBuilder.build());
-
- if (write) {
- InstructionBuilder ib = new InstructionBuilder();
- InstructionsBuilder isb = new InstructionsBuilder();
- List<Instruction> instructions = new ArrayList<>();
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- ActionBuilder ab = new ActionBuilder();
- List<Action> actionList = new ArrayList<>();
-
- // Move Eth Src to Eth Dst
- ab.setAction(ActionUtils.nxMoveEthSrcToEthDstAction());
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
- actionList.add(ab.build());
-
- // Set Eth Src
- ab.setAction(ActionUtils.setDlSrcAction(new MacAddress(macAddress)));
- ab.setOrder(1);
- ab.setKey(new ActionKey(1));
- actionList.add(ab.build());
-
- // Set ARP OP
- ab.setAction(ActionUtils.nxLoadArpOpAction(BigInteger.valueOf(FlowUtils.ARP_OP_REPLY)));
- ab.setOrder(2);
- ab.setKey(new ActionKey(2));
- actionList.add(ab.build());
-
- // Move ARP SHA to ARP THA
- ab.setAction(ActionUtils.nxMoveArpShaToArpThaAction());
- ab.setOrder(3);
- ab.setKey(new ActionKey(3));
- actionList.add(ab.build());
-
- // Move ARP SPA to ARP TPA
- ab.setAction(ActionUtils.nxMoveArpSpaToArpTpaAction());
- ab.setOrder(4);
- ab.setKey(new ActionKey(4));
- actionList.add(ab.build());
-
- // Load Mac to ARP SHA
- ab.setAction(ActionUtils.nxLoadArpShaAction(macAddress));
- ab.setOrder(5);
- ab.setKey(new ActionKey(5));
- actionList.add(ab.build());
-
- // Load IP to ARP SPA
- ab.setAction(ActionUtils.nxLoadArpSpaAction(ipAddress));
- ab.setOrder(6);
- ab.setKey(new ActionKey(6));
- actionList.add(ab.build());
-
- // Output of InPort
- ab.setAction(ActionUtils.outputAction(
- FlowUtils.getSpecialNodeConnectorId(dataPathId, OutputPortValues.INPORT.toString())));
- ab.setOrder(7);
- ab.setKey(new ActionKey(7));
- actionList.add(ab.build());
-
- // Create Apply Actions Instruction
- aab.setAction(actionList);
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
- ib.setOrder(0);
- ib.setKey(new InstructionKey(0));
- instructions.add(ib.build());
-
- isb.setInstruction(instructions);
- flowBuilder.setInstructions(isb.build());
- writeFlow(flowBuilder, nodeBuilder, rspName, FlowID.FLOW_SFARP);
- } else {
- removeFlow(flowBuilder, nodeBuilder, rspName, FlowID.FLOW_SFARP);
- }
- }
-
- private List<Action> getNshAction(NshUtils header, List<Action> actionList) {
- // Build the Actions to Add the NSH Header
- org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action pushNsh =
- ActionUtils.nxPushNshAction();
- org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action nshMdtypeLoad =
- ActionUtils.nxLoadNshMdtypeAction((short) 0x1);
- org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action nshNpLoad =
- ActionUtils.nxLoadNshNpAction((short) 0x3);
- org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action nshC1Load =
- ActionUtils.nxLoadNshc1RegAction(header.getNshMetaC1());
- org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action nspLoad =
- ActionUtils.nxSetNspAction(header.getNshNsp());
- org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action nsiLoad =
- ActionUtils.nxSetNsiAction(header.getNshNsi());
- org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action loadChainTunVnid =
- ActionUtils.nxLoadTunIdAction(BigInteger.valueOf(header.getNshNsp()), false);
- org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action loadChainTunDest =
- ActionUtils.nxLoadTunIPv4Action(header.getNshTunIpDst().getValue(), false);
-
- int count = actionList.size();
- actionList.add(new ActionBuilder()
- .setKey(new ActionKey(count)).setOrder(count++).setAction(pushNsh).build());
- actionList.add(new ActionBuilder()
- .setKey(new ActionKey(count)).setOrder(count++).setAction(nshMdtypeLoad).build());
- actionList.add(new ActionBuilder()
- .setKey(new ActionKey(count)).setOrder(count++).setAction(nshNpLoad).build());
- actionList.add(new ActionBuilder()
- .setKey(new ActionKey(count)).setOrder(count++).setAction(nshC1Load).build());
- actionList.add(new ActionBuilder()
- .setKey(new ActionKey(count)).setOrder(count++).setAction(nspLoad).build());
- actionList.add(new ActionBuilder()
- .setKey(new ActionKey(count)).setOrder(count++).setAction(nsiLoad).build());
- actionList.add(new ActionBuilder()
- .setKey(new ActionKey(count)).setOrder(count++).setAction(loadChainTunDest).build());
- actionList.add(new ActionBuilder()
- .setKey(new ActionKey(count)).setOrder(count).setAction(loadChainTunVnid).build());
- return actionList;
- }
-
- private static FlowID flowSet[] = {FlowID.FLOW_INGRESSCLASS, FlowID.FLOW_EGRESSCLASS,
- FlowID.FLOW_EGRESSCLASSBYPASS, FlowID.FLOW_SFARP, FlowID.FLOW_SFINGRESS, FlowID.FLOW_SFEGRESS};
-
- @Override
- public void clearFlows(DataBroker dataBroker, String rspName) {
- Map<Integer, InstanceIdentifier<Flow>> flowMap = flowCache.getFlows(rspName);
- if (flowMap != null) {
- for (FlowID flowID : flowSet) {
- InstanceIdentifier<Flow> path = flowMap.get(flowID.value);
- if (path != null) {
- flowCache.removeFlow(rspName, flowID.value);
- removeFlow(dataBroker, path);
- }
- }
- }
- }
-
- private void removeFlow(DataBroker dataBroker, InstanceIdentifier<Flow> path) {
- WriteTransaction modification = dataBroker.newWriteOnlyTransaction();
- modification.delete(LogicalDatastoreType.CONFIGURATION, path);
-
- CheckedFuture<Void, TransactionCommitFailedException> commitFuture = modification.submit();
- try {
- commitFuture.get(); // TODO: Make it async (See bug 1362)
- LOG.debug("Transaction success for deletion of Flow {}", path);
- } catch (Exception e) {
- LOG.error("Failed to remove flow {}", path, e);
- modification.cancel();
- }
- }
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
- xmlns:odl="http://opendaylight.org/xmlns/blueprint/v1.0.0"
- odl:use-default-for-reference-types="true">
-
- <reference id="dataBroker"
- interface="org.opendaylight.controller.md.sal.binding.api.DataBroker" />
- <reference id="pipelineOrchestrator"
- interface="org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.PipelineOrchestrator" />
- <reference id="southbound"
- interface="org.opendaylight.netvirt.openstack.netvirt.api.Southbound" />
-
- <odl:clustered-app-config id="netvirtSfcConfig"
- binding-class="org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.impl.config.rev160517.NetvirtSfcConfig">
- </odl:clustered-app-config>
-
- <bean id="netvirtSfcProvider"
- class="org.opendaylight.netvirt.openstack.netvirt.sfc.NetvirtSfcProvider"
- init-method="start" destroy-method="close">
- <argument ref="dataBroker" />
- <argument ref="netvirtSfcConfig" />
- <argument ref="blueprintBundleContext" />
- </bean>
-
-</blueprint>
\ No newline at end of file
+++ /dev/null
-module netvirt-sfc-config {
- yang-version 1;
- namespace "urn:opendaylight:params:xml:ns:yang:netvirt:sfc:impl:config";
- prefix "netvirt-sfc-config";
-
- description
- "Service configuration for netvirt sfc project";
-
- revision "2016-05-17" {
- description
- "Initial revision";
- }
-
- container netvirt-sfc-config {
- leaf of13provider {
- type string;
- default "workaround";
- }
- leaf addsflows {
- type boolean;
- default false;
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright © 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc.workaround.services;
-
-import static org.junit.Assert.assertEquals;
-
-import org.junit.Test;
-import org.opendaylight.netvirt.utils.mdsal.openflow.MatchUtils;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.MatchesBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder;
-
-public class AclMatchesTest {
- @Test
- public void buildMatchTest() {
- AclUtils aclUtils = new AclUtils();
- MatchesBuilder matchesBuilder = aclUtils.matchesBuilder(new MatchesBuilder(), 80);
- AclMatches aclMatches = new AclMatches(matchesBuilder.build());
- MatchBuilder matchBuilder = new MatchBuilder();
- MatchUtils.createIpProtocolMatch(matchBuilder, (short)6);
- MatchUtils.addLayer4Match(matchBuilder, 6, 0, 80);
- assertEquals(matchBuilder.build(), aclMatches.buildMatch().build());
- }
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-Copyright © 2015 Red Hat, Inc. and others. All rights reserved.
-
-This program and the accompanying materials are made available under the
-terms of the Eclipse Public License v1.0 which accompanies this distribution,
-and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
-
- <parent>
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>it</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <relativePath>../../commons/it</relativePath>
- </parent>
-
- <modelVersion>4.0.0</modelVersion>
- <artifactId>openstack.net-virt-sfc-it</artifactId>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <packaging>jar</packaging>
-
- <properties>
- <karaf.distro.groupId>org.opendaylight.netvirt</karaf.distro.groupId>
- <karaf.distro.artifactId>openstack.net-virt-sfc-karaf</karaf.distro.artifactId>
- <karaf.distro.version>${project.version}</karaf.distro.version>
- <karaf.distro.type>zip</karaf.distro.type>
- <ovsdb.version>1.5.0-SNAPSHOT</ovsdb.version>
- </properties>
-
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>openstack.net-virt-sfc-artifacts</artifactId>
- <version>${project.version}</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- </dependencies>
- </dependencyManagement>
-
- <dependencies>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>openstack.net-virt-sfc-features</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>openstack.net-virt-sfc-api</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>openstack.net-virt-sfc-impl</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>openstack.net-virt-providers</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>utils.mdsal-openflow</artifactId>
- <version>${project.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>utils.mdsal-utils</artifactId>
- <version>${project.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.ovsdb</groupId>
- <artifactId>utils.mdsal-utils</artifactId>
- <version>${ovsdb.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.ovsdb</groupId>
- <artifactId>utils.southbound-utils</artifactId>
- <version>${ovsdb.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>utils.netvirt-it-utils</artifactId>
- <version>${project.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.ovsdb</groupId>
- <artifactId>utils.ovsdb-it-utils</artifactId>
- <version>${ovsdb.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>concepts</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.codehaus.sonar-plugins.java</groupId>
- <artifactId>sonar-jacoco-listeners</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.jacoco</groupId>
- <artifactId>jacoco-maven-plugin</artifactId>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <!--<propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>-->
- <includeTestSourceDirectory>true</includeTestSourceDirectory>
- </configuration>
- </plugin>
- <plugin>
- <artifactId>maven-failsafe-plugin</artifactId>
- <configuration>
- <!-- <excludes>
- <exclude>**/NetvirtSfcIT.java</exclude>
- </excludes>-->
- </configuration>
- </plugin>
- </plugins>
- </build>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-/*
- * Copyright © 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc.it;
-
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-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.keepRuntimeFolder;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-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.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-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.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.PipelineOrchestrator;
-import org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.Service;
-import org.opendaylight.netvirt.openstack.netvirt.sfc.NshUtils;
-import org.opendaylight.netvirt.openstack.netvirt.sfc.SfcUtils;
-import org.opendaylight.netvirt.openstack.netvirt.sfc.it.utils.AclUtils;
-import org.opendaylight.netvirt.openstack.netvirt.sfc.it.utils.ClassifierUtils;
-import org.opendaylight.netvirt.openstack.netvirt.sfc.it.utils.NetvirtConfigUtils;
-import org.opendaylight.netvirt.openstack.netvirt.sfc.it.utils.NetvirtSfcUtils;
-import org.opendaylight.netvirt.openstack.netvirt.sfc.it.utils.RenderedServicePathUtils;
-import org.opendaylight.netvirt.openstack.netvirt.sfc.it.utils.ServiceFunctionChainUtils;
-import org.opendaylight.netvirt.openstack.netvirt.sfc.it.utils.ServiceFunctionForwarderUtils;
-import org.opendaylight.netvirt.openstack.netvirt.sfc.it.utils.ServiceFunctionPathUtils;
-import org.opendaylight.netvirt.openstack.netvirt.sfc.it.utils.ServiceFunctionUtils;
-import org.opendaylight.netvirt.openstack.netvirt.sfc.it.utils.SfcConfigUtils;
-import org.opendaylight.netvirt.openstack.netvirt.sfc.standalone.openflow13.SfcClassifier;
-import org.opendaylight.netvirt.openstack.netvirt.sfc.workaround.services.FlowNames;
-import org.opendaylight.netvirt.utils.mdsal.openflow.FlowUtils;
-import org.opendaylight.netvirt.utils.mdsal.utils.MdsalUtils;
-import org.opendaylight.netvirt.utils.netvirt.it.utils.NetvirtItUtils;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.opendaylight.ovsdb.southbound.SouthboundConstants;
-import org.opendaylight.ovsdb.utils.mdsal.utils.NotifyingDataChangeListener;
-import org.opendaylight.ovsdb.utils.ovsdb.it.utils.NodeInfo;
-import org.opendaylight.ovsdb.utils.ovsdb.it.utils.OvsdbItUtils;
-import org.opendaylight.ovsdb.utils.southbound.utils.SouthboundUtils;
-import org.opendaylight.sfc.provider.api.SfcProviderRenderedPathAPI;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.RspName;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.SftTypeName;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.CreateRenderedPathInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.RenderedServicePaths;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.rendered.service.paths.RenderedServicePath;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.rendered.service.paths.RenderedServicePathKey;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.rendered.service.paths.rendered.service.path.RenderedServicePathHop;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sf.rev140701.ServiceFunctions;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sf.rev140701.ServiceFunctionsBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sf.rev140701.service.functions.ServiceFunction;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sf.rev140701.service.functions.ServiceFunctionBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfc.rev140701.ServiceFunctionChains;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfc.rev140701.ServiceFunctionChainsBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfc.rev140701.service.function.chain.grouping.ServiceFunctionChainBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfc.rev140701.service.function.chain.grouping.service.function.chain.SfcServiceFunction;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfc.rev140701.service.function.chain.grouping.service.function.chain.SfcServiceFunctionBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.ServiceFunctionForwarders;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.ServiceFunctionForwardersBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.service.function.forwarders.ServiceFunctionForwarder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.service.function.forwarders.ServiceFunctionForwarderBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfp.rev140701.ServiceFunctionPaths;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfp.rev140701.ServiceFunctionPathsBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfp.rev140701.service.function.paths.ServiceFunctionPathBuilder;
-import org.opendaylight.yang.gen.v1.urn.ericsson.params.xml.ns.yang.sfc.of.renderer.rev151123.SfcOfRendererConfig;
-import org.opendaylight.yang.gen.v1.urn.ericsson.params.xml.ns.yang.sfc.of.renderer.rev151123.SfcOfRendererConfigBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.AccessLists;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.AccessListsBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.AclBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.AccessListEntriesBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.AceBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.ActionsBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.MatchesBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
-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.netvirt.providers.config.rev160109.NetvirtProvidersConfig;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.providers.config.rev160109.NetvirtProvidersConfigBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.classifier.rev150105.Classifiers;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.classifier.rev150105.ClassifiersBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.classifier.rev150105.classifiers.ClassifierBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.classifier.rev150105.classifiers.classifier.SffsBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.classifier.rev150105.classifiers.classifier.sffs.SffBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.rev150105.Sfc;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.rev150105.SfcBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeRef;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.ControllerEntry;
-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.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
-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.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.node.TerminationPoint;
-import org.opendaylight.yangtools.concepts.Builder;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-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.LogLevelOption;
-import org.ops4j.pax.exam.karaf.options.LogLevelOption.LogLevel;
-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.ops4j.pax.exam.util.Filter;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-@RunWith(PaxExam.class)
-@ExamReactorStrategy(PerClass.class)
-public class NetvirtSfcIT extends AbstractMdsalTestBase {
- private static final Logger LOG = LoggerFactory.getLogger(NetvirtSfcIT.class);
- private static AclUtils aclUtils = new AclUtils();
- private static ClassifierUtils classifierUtils = new ClassifierUtils();
- private static NetvirtSfcUtils netvirtSfcUtils = new NetvirtSfcUtils();
- private static ServiceFunctionUtils serviceFunctionUtils = new ServiceFunctionUtils();
- private static ServiceFunctionForwarderUtils serviceFunctionForwarderUtils = new ServiceFunctionForwarderUtils();
- private static ServiceFunctionChainUtils serviceFunctionChainUtils = new ServiceFunctionChainUtils();
- private static ServiceFunctionPathUtils serviceFunctionPathUtils = new ServiceFunctionPathUtils();
- private static RenderedServicePathUtils renderedServicePathUtils = new RenderedServicePathUtils();
- private static SfcConfigUtils sfcConfigUtils = new SfcConfigUtils();
- private static NetvirtConfigUtils netvirtConfigUtils = new NetvirtConfigUtils();
- private static MdsalUtils mdsalUtils;
- private static AtomicBoolean setup = new AtomicBoolean(false);
- private static SouthboundUtils southboundUtils;
- private static SfcUtils sfcUtils;
- private static String addressStr;
- private static String portStr;
- private static String connectionType;
- private static String controllerStr;
- private static boolean ovsdb_wait = false;
- private static String userSpaceEnabled = "no";
- private static PipelineOrchestrator pipelineOrchestrator;
- private static Southbound southbound;
- private static OvsdbItUtils itUtils;
- private static NetvirtItUtils nvItUtils;
- public static final String CONTROLLER_IPADDRESS = "ovsdb.controller.address";
- public static final String SERVER_IPADDRESS = "ovsdbserver.ipaddress";
- public static final String SERVER_PORT = "ovsdbserver.port";
- public static final String CONNECTION_TYPE = "ovsdbserver.connection";
- public static final String CONNECTION_TYPE_ACTIVE = "active";
- public static final String CONNECTION_TYPE_PASSIVE = "passive";
- public static final String DEFAULT_SERVER_PORT = "6640";
- public static final String USERSPACE_ENABLED = "ovsdb.userspace.enabled";
- public static final String INTEGRATION_BRIDGE_NAME = "br-int";
- private static final String NETVIRT_TOPOLOGY_ID = "netvirt:1";
- private static final String OVSDB_TRACE = "ovsdb.trace";
- private static final String OVSDB_WAIT = "ovsdb.wait";
- private static final String SF1NAME = "firewall-72";
- private static final String SF2NAME = "dpi-72";
- private static final String SF1IP = "10.2.1.1";//"192.168.50.70";//"192.168.120.31";
- private static final String SF2IP = "10.2.1.2";
- private static final String SF1DPLNAME = "sf1";
- private static final String SF2DPLNAME = "sf2";
- private static final String SF1DPLPORTNAME = "tap-123456789ab";
- // Use 192.168.50.70 when running against vagrant vm for workaround testing, eg. netvirtsfc-env.
- // Use 192.168.1.129 (or whatever address is dhcp'ed) for tacker-vm.
- // "192.168.50.70"; "127.0.0.1"; "192.168.1.129";
- private static final String SFF1IP = "192.168.50.70";
- private static final String SFF2IP = "127.0.0.1";
- private static final String SFF1NAME = "sff1";
- private static final String SFF2NAME = "sff2";
- private static final String SFFDPL1NAME = "vxgpe";
- private static final String SFFDPL2NAME = "vxgpe";
- private static final String SN1NAME = "ovsdb1";
- private static final String SN2NAME = "ovsdb2";
- private static final String BRIDGE1NAME= "br-int";
- private static final String BRIDGE2NAME= "br-int";
- private static final String ACLNAME= "httpAcl";
- private static final String RULENAME= "httpRule";
- private static final String SFCNAME = "SFC";
- private static final String SFCPATH = "SFC-Path";
- private static final String RSPNAME = SFCPATH + "_rsp";
- private static final String SFCSF1NAME = "firewall-abstract";
- private static final SftTypeName SFCSF1TYPE = new SftTypeName("firewall");
- private static final int GPEUDPPORT = 6633;
- @Inject @Filter(timeout=60000)
- private static DataBroker dataBroker = null;
-
- @Override
- public MavenUrlReference getFeatureRepo() {
- return maven()
- .groupId("org.opendaylight.netvirt")
- .artifactId("openstack.net-virt-sfc-features")
- .classifier("features")
- .type("xml")
- .versionAsInProject();
- }
-
- @Override
- public String getFeatureName() {
- return "odl-ovsdb-sfc-test";
- }
-
- @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.netvirt", "utils.mdsal-openflow")
- .version(asInProject())
- .type("jar")),
- configureConsole().startLocalConsole(),
- //vmOption("-verbose:class"),
- vmOption("-javaagent:../jars/org.jacoco.agent.jar=destfile=../../jacoco-it.exec"),
- keepRuntimeFolder()
- };
- }
-
- public Option[] getPropertiesOptions() {
- return new Option[] {
- propagateSystemProperties(SERVER_IPADDRESS, SERVER_PORT, CONNECTION_TYPE,
- CONTROLLER_IPADDRESS, OVSDB_TRACE, OVSDB_WAIT, USERSPACE_ENABLED),
- };
- }
-
- @Override
- public Option getLoggingOption() {
- return composite(
- when(Boolean.getBoolean(OVSDB_TRACE)).useOptions(
- editConfigurationFilePut(ORG_OPS4J_PAX_LOGGING_CFG,
- "log4j.logger.org.opendaylight.ovsdb",
- LogLevelOption.LogLevel.TRACE.name())),
- //editConfigurationFilePut(ORG_OPS4J_PAX_LOGGING_CFG,
- // "log4j.logger.org.opendaylight.ovsdb",
- // LogLevel.TRACE.name()),
- //editConfigurationFilePut(ORG_OPS4J_PAX_LOGGING_CFG,
- // "log4j.logger.org.opendaylight.ovsdb.lib",
- // LogLevel.INFO.name()),
- editConfigurationFilePut(ORG_OPS4J_PAX_LOGGING_CFG,
- "log4j.logger.org.opendaylight.netvirt.openstack.netvirt.sfc",
- LogLevel.TRACE.name()),
- editConfigurationFilePut(ORG_OPS4J_PAX_LOGGING_CFG,
- logConfiguration(NetvirtSfcIT.class),
- LogLevel.INFO.name()),
- editConfigurationFilePut(ORG_OPS4J_PAX_LOGGING_CFG,
- "log4j.logger.org.opendaylight.netvirt.openstack.netvirt.sfc",
- LogLevel.TRACE.name()),
- editConfigurationFilePut(ORG_OPS4J_PAX_LOGGING_CFG,
- "log4j.logger.org.opendaylight.netvirt.openstack.netvirt.providers.openflow13",
- LogLevel.TRACE.name()),
- editConfigurationFilePut(ORG_OPS4J_PAX_LOGGING_CFG,
- "log4j.logger.org.opendaylight.sfc",
- LogLevel.TRACE.name()),
- editConfigurationFilePut(ORG_OPS4J_PAX_LOGGING_CFG,
- "log4j.logger.org.opendaylight.openflowjava.protocol.impl.util.ListDeserializer",
- LogLevel.ERROR.name()),
- editConfigurationFilePut(ORG_OPS4J_PAX_LOGGING_CFG,
- "log4j.logger.org.opendaylight.controller.configpusherfeature.internal.FeatureConfigPusher",
- LogLevel.ERROR.name()),
- super.getLoggingOption());
- }
-
- 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";
- }
-
- private void getProperties() {
- Properties props = System.getProperties();
- addressStr = props.getProperty(SERVER_IPADDRESS);
- portStr = props.getProperty(SERVER_PORT, DEFAULT_SERVER_PORT);
- connectionType = props.getProperty(CONNECTION_TYPE, "active");
- controllerStr = props.getProperty(CONTROLLER_IPADDRESS, "0.0.0.0");
- userSpaceEnabled = props.getProperty(USERSPACE_ENABLED, "no");
- LOG.info("setUp: Using the following properties: mode= {}, ip:port= {}:{}, controller ip: {}, " +
- "userspace.enabled: {}",
- connectionType, addressStr, portStr, controllerStr, userSpaceEnabled);
- if (connectionType.equalsIgnoreCase(CONNECTION_TYPE_ACTIVE)) {
- if (addressStr == null) {
- fail(usage());
- }
- }
- LOG.info("getProperties {}: {}", OVSDB_TRACE, props.getProperty(OVSDB_TRACE));
- LOG.info("getProperties {}: {}", OVSDB_WAIT, props.getProperty(OVSDB_WAIT));
- if (props.getProperty(OVSDB_WAIT) != null && props.getProperty(OVSDB_WAIT).equals("true")) {
- ovsdb_wait = true;
- }
- }
-
- @Before
- @Override
- public void setup() {
- if (setup.get()) {
- LOG.info("Skipping setUp, already initialized");
- return;
- }
-
- try {
- Thread.sleep(1000);
- super.setup();
- } catch (Exception e) {
- LOG.warn("Failed to setup test", e);
- fail("Failed to setup test: " + e);
- }
-
- getProperties();
-
- assertNotNull("dataBroker should not be null", dataBroker);
- itUtils = new OvsdbItUtils(dataBroker);
- nvItUtils = new NetvirtItUtils(dataBroker);
- mdsalUtils = new MdsalUtils(dataBroker);
- org.opendaylight.ovsdb.utils.mdsal.utils.MdsalUtils sbMdsalUtils =
- new org.opendaylight.ovsdb.utils.mdsal.utils.MdsalUtils(dataBroker);
- assertNotNull("mdsalUtils should not be null", mdsalUtils);
- southboundUtils = new SouthboundUtils(sbMdsalUtils);
- sfcUtils = new SfcUtils(mdsalUtils);
- assertTrue("Did not find " + NETVIRT_TOPOLOGY_ID, getNetvirtTopology());
- southbound = (Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this);
- assertNotNull("southbound should not be null", southbound);
- pipelineOrchestrator =
- (PipelineOrchestrator) ServiceHelper.getGlobalInstance(PipelineOrchestrator.class, this);
- assertNotNull("pipelineOrchestrator should not be null", pipelineOrchestrator);
-
- setup.set(true);
- }
-
- @After
- public void teardown() {
- closeWaitFors();
- }
-
- private Boolean getNetvirtTopology() {
- LOG.info("getNetvirtTopology: looking for {}...", NETVIRT_TOPOLOGY_ID);
- Boolean found = false;
- final TopologyId topologyId = new TopologyId(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) {
- LOG.warn("Interrupted while waiting for {}", NETVIRT_TOPOLOGY_ID, e);
- }
- }
- }
- return found;
- }
-
- private AccessListsBuilder accessListsBuilder() {
- return accessListsBuilder(false);
- }
-
- private AccessListsBuilder accessListsBuilder(boolean renderRsp) {
- String ruleName = RULENAME;
- String sfcName = SFCNAME;
- MatchesBuilder matchesBuilder = aclUtils.matchesBuilder(new MatchesBuilder(), 80);
- LOG.info("Matches: {}", matchesBuilder.build());
- ActionsBuilder actionsBuilder = aclUtils.actionsBuilder(new ActionsBuilder(), sfcName, renderRsp);
- AceBuilder accessListEntryBuilder =
- aclUtils.aceBuilder(new AceBuilder(), ruleName, matchesBuilder, actionsBuilder);
- AccessListEntriesBuilder accessListEntriesBuilder =
- aclUtils.accessListEntriesBuidler(new AccessListEntriesBuilder(), accessListEntryBuilder);
- AclBuilder accessListBuilder =
- aclUtils.aclBuilder(new AclBuilder(), ACLNAME, accessListEntriesBuilder);
- AccessListsBuilder accessListsBuilder =
- aclUtils.accesslistsbuilder(new AccessListsBuilder(), accessListBuilder);
- LOG.info("AccessLists: {}", accessListsBuilder.build());
- return accessListsBuilder;
- }
-
- @Test
- public void testAccessLists() throws InterruptedException {
- testModel(accessListsBuilder(), AccessLists.class, 0);
- }
-
- private ClassifiersBuilder classifiersBuilder() {
- SffBuilder sffBuilder = classifierUtils.sffBuilder(new SffBuilder(), SFF1NAME);
- SffsBuilder sffsBuilder = classifierUtils.sffsBuilder(new SffsBuilder(), sffBuilder);
- ClassifierBuilder classifierBuilder = classifierUtils.classifierBuilder(new ClassifierBuilder(),
- "classifierName", ACLNAME, sffsBuilder);
- ClassifiersBuilder classifiersBuilder = classifierUtils.classifiersBuilder(new ClassifiersBuilder(),
- classifierBuilder);
- LOG.info("Classifiers: {}", classifiersBuilder.build());
- return classifiersBuilder;
- }
-
- @Test
- public void testClassifiers() throws InterruptedException {
- testModel(classifiersBuilder(), Classifiers.class, 0);
- }
-
- private SfcBuilder netvirtSfcBuilder() {
- return netvirtSfcUtils.sfcBuilder(new SfcBuilder(), "sfc");
- }
-
- @Test
- public void testNetvirtSfcModel() throws InterruptedException {
- testModel(netvirtSfcBuilder(), Sfc.class, 0);
- }
-
- private <T extends DataObject> void testModelPut(Builder<T> builder, Class<T> clazz) {
- InstanceIdentifier<T> path = InstanceIdentifier.create(clazz);
- assertTrue(mdsalUtils.put(LogicalDatastoreType.CONFIGURATION, path, builder.build()));
- T result = mdsalUtils.read(LogicalDatastoreType.CONFIGURATION, path);
- assertNotNull(clazz.getSimpleName() + " should not be null", result);
- }
-
- private <T extends DataObject> void testModelDelete(Builder<T> builder, Class<T> clazz)
- throws InterruptedException {
- InstanceIdentifier<T> path = InstanceIdentifier.create(clazz);
- assertTrue("Failed to remove " + clazz.getSimpleName(),
- mdsalUtils.delete(LogicalDatastoreType.CONFIGURATION, path));
- T result = mdsalUtils.read(LogicalDatastoreType.CONFIGURATION, path);
- assertNull(clazz.getSimpleName() + " should be null", result);
- }
-
- private <T extends DataObject> void testModel(Builder<T> builder, Class<T> clazz, long wait)
- throws InterruptedException {
- testModelPut(builder, clazz);
- Thread.sleep(wait);
- testModelDelete(builder, clazz);
- }
-
- private <T extends DataObject> void testModel(Builder<T> builder, Class<T> clazz)
- throws InterruptedException {
- testModelPut(builder, clazz);
- Thread.sleep(1000);
- testModelDelete(builder, clazz);
- }
-
- private ServiceFunctionsBuilder serviceFunctionsBuilder() {
- String sf1Name = SF1NAME;
- String sf1Ip = SF1IP;
- String sff1Name = SFF1NAME;
- String sf1DplName = SF1DPLNAME;
- String sf1DplportName = SF1DPLPORTNAME;
- int port = GPEUDPPORT;
-
- ServiceFunctionBuilder serviceFunctionBuilder =
- serviceFunctionUtils.serviceFunctionBuilder(sf1Ip, port, sf1DplName, sf1DplportName,
- sff1Name, sf1Name);
- List<ServiceFunction> serviceFunctionList = serviceFunctionUtils.list(
- new ArrayList<>(), serviceFunctionBuilder);
-
- ServiceFunctionsBuilder serviceFunctionsBuilder =
- serviceFunctionUtils.serviceFunctionsBuilder(new ServiceFunctionsBuilder(),
- serviceFunctionList);
- LOG.info("ServiceFunctions: {}", serviceFunctionsBuilder.build());
- return serviceFunctionsBuilder;
- }
-
- private ServiceFunctionForwardersBuilder serviceFunctionForwardersBuilder() {
- return serviceFunctionForwardersBuilder(null);
- }
-
- private ServiceFunctionForwardersBuilder serviceFunctionForwardersBuilder(OvsdbNodeRef ovsdbNodeRef) {
- String sf1Name = SF1NAME;
- String sf1Ip = SF1IP;
- String sf1DplName = SF1DPLNAME;
- String sff1Ip = SFF1IP;
- String sff1Name = SFF1NAME;
- String sffDpl1Name = SFFDPL1NAME;
- String sn1Name = SN1NAME;
- String bridge1Name= BRIDGE1NAME;
- int port = GPEUDPPORT;
-
- ServiceFunctionForwarderBuilder serviceFunctionForwarderBuilder =
- serviceFunctionForwarderUtils.serviceFunctionForwarderBuilder(
- sff1Name, sff1Ip, port, sffDpl1Name, sf1Ip, sn1Name, bridge1Name, sf1Name, sf1DplName,
- ovsdbNodeRef);
- List<ServiceFunctionForwarder> serviceFunctionForwarderList = serviceFunctionForwarderUtils.list(
- new ArrayList<>(), serviceFunctionForwarderBuilder);
-
- ServiceFunctionForwardersBuilder serviceFunctionForwardersBuilder =
- serviceFunctionForwarderUtils.serviceFunctionForwardersBuilder(
- new ServiceFunctionForwardersBuilder(), serviceFunctionForwarderList);
- LOG.info("ServiceFunctionForwarders: {}", serviceFunctionForwardersBuilder.build());
- return serviceFunctionForwardersBuilder;
- }
-
- private ServiceFunctionChainsBuilder serviceFunctionChainsBuilder() {
- String sf1Name = SFCSF1NAME;
- SftTypeName sfType = SFCSF1TYPE;
- String sfcName = SFCNAME;
-
- SfcServiceFunctionBuilder sfcServiceFunctionBuilder = serviceFunctionChainUtils.sfcServiceFunctionBuilder(
- new SfcServiceFunctionBuilder(), sf1Name, sfType);
- List<SfcServiceFunction> sfcServiceFunctionList =
- serviceFunctionChainUtils.list(new ArrayList<>(), sfcServiceFunctionBuilder);
-
- ServiceFunctionChainBuilder serviceFunctionChainBuilder =
- serviceFunctionChainUtils.serviceFunctionChainBuilder(
- new ServiceFunctionChainBuilder(), sfcName, false, sfcServiceFunctionList);
- ServiceFunctionChainsBuilder serviceFunctionChainsBuilder =
- serviceFunctionChainUtils.serviceFunctionChainsBuilder(
- new ServiceFunctionChainsBuilder(),
- serviceFunctionChainUtils.list(new ArrayList<>(),
- serviceFunctionChainBuilder));
- LOG.info("ServiceFunctionChains: {}", serviceFunctionChainBuilder.build());
- return serviceFunctionChainsBuilder;
- }
-
- private ServiceFunctionPathsBuilder serviceFunctionPathsBuilder() {
- String sfpName = SFCPATH;
- String sfcName = SFCNAME;
- short startingIndex = 255;
-
- ServiceFunctionPathBuilder serviceFunctionPathBuilder =
- serviceFunctionPathUtils.serviceFunctionPathBuilder(
- new ServiceFunctionPathBuilder(), sfpName, sfcName, startingIndex, false);
- ServiceFunctionPathsBuilder serviceFunctionPathsBuilder =
- serviceFunctionPathUtils.serviceFunctionPathsBuilder(
- serviceFunctionPathUtils.list(new ArrayList<>(),
- serviceFunctionPathBuilder));
- LOG.info("ServiceFunctionPaths: {}", serviceFunctionPathsBuilder.build());
- return serviceFunctionPathsBuilder;
- }
-
- private SfcOfRendererConfigBuilder sfcOfRendererConfigBuilder(short tableOffset, short egressTable) {
- SfcOfRendererConfigBuilder sfcOfRendererConfigBuilder =
- sfcConfigUtils.sfcOfRendererConfigBuilder(new SfcOfRendererConfigBuilder(), tableOffset, egressTable);
- LOG.info("SfcOfRendererConfig: {}", sfcOfRendererConfigBuilder.build());
- return sfcOfRendererConfigBuilder;
- }
-
- private NetvirtProvidersConfigBuilder netvirtProvidersConfigBuilder(short tableOffset) {
- NetvirtProvidersConfigBuilder netvirtProvidersConfigBuilder =
- netvirtConfigUtils.netvirtProvidersConfigBuilder(new NetvirtProvidersConfigBuilder(), tableOffset);
- LOG.info("NetvirtProvidersConfig: {}", netvirtProvidersConfigBuilder.build());
- return netvirtProvidersConfigBuilder;
- }
-
- @Test
- public void testSfcModel() throws InterruptedException {
- int timeout = 1000;
- testModel(serviceFunctionsBuilder(), ServiceFunctions.class, timeout);
- testModel(serviceFunctionForwardersBuilder(), ServiceFunctionForwarders.class, timeout);
- testModel(serviceFunctionChainsBuilder(), ServiceFunctionChains.class, timeout);
- testModel(serviceFunctionPathsBuilder(), ServiceFunctionPaths.class, timeout);
- }
-
- @Test
- public void testSfcModels() throws InterruptedException {
- testModel(serviceFunctionsBuilder(), ServiceFunctions.class);
- testModel(serviceFunctionForwardersBuilder(), ServiceFunctionForwarders.class);
- testModel(serviceFunctionChainsBuilder(), ServiceFunctionChains.class);
- testModel(serviceFunctionPathsBuilder(), ServiceFunctionPaths.class);
-
- testModel(accessListsBuilder(), AccessLists.class);
- testModel(classifiersBuilder(), Classifiers.class);
- }
-
- /**
- * Test that the NetvirtSfc SfcClassifierService is added to the Netvirt pipeline. The test
- * sets the table offset and verifies the correct flow is programmed with the offset.
- */
- @Test
- @SuppressWarnings("checkstyle:IllegalCatch")
- public void testNetvirtSfcPipeline() throws Exception {
- short netvirtTableOffset = 1;
- testModelPut(netvirtProvidersConfigBuilder(netvirtTableOffset), NetvirtProvidersConfig.class);
-
- NodeInfo nodeInfo = itUtils.createNodeInfo(SouthboundUtils.getConnectionInfo(addressStr, portStr), waitList);
- nodeInfo.connect();
-
- String flowId = "DEFAULT_PIPELINE_FLOW_" + pipelineOrchestrator.getTable(Service.SFC_CLASSIFIER);
- nvItUtils.verifyFlow(nodeInfo.datapathId, flowId, pipelineOrchestrator.getTable(Service.SFC_CLASSIFIER));
-
- nodeInfo.disconnect();
- }
-
- /**
- * Test the full NetvirtSfc functionality by creating everything needed to realize a chain and
- * then verify all flows have been created.
- * NOTE: This test requires an OVS with the NSH v8 patch, otherwise it will fail miserably.
- * @throws InterruptedException
- */
- @Test
- @SuppressWarnings("checkstyle:IllegalCatch")
- public void testNetvirtSfcAll() throws Exception {
- if (userSpaceEnabled.equals("yes")) {
- LOG.info("testNetvirtSfcAll: skipping test because userSpaceEnabled {}", userSpaceEnabled);
- return;
- }
-
- String sfpName = SFCPATH;
- String sfcName = SFCNAME;
- short startingIndex = 255;
-
- short netvirtTableOffset = 1;
- testModelPut(netvirtProvidersConfigBuilder(netvirtTableOffset), NetvirtProvidersConfig.class);
- short sfcTableoffset = 150;
- short egressTable = pipelineOrchestrator.getTable(Service.SFC_CLASSIFIER);
- testModelPut(sfcOfRendererConfigBuilder(sfcTableoffset, egressTable), SfcOfRendererConfig.class);
-
- NodeInfo nodeInfo = itUtils.createNodeInfo(SouthboundUtils.getConnectionInfo(addressStr, portStr), waitList);
- nodeInfo.connect();
-
- String flowId = "DEFAULT_PIPELINE_FLOW_" + pipelineOrchestrator.getTable(Service.SFC_CLASSIFIER);
- nvItUtils.verifyFlow(nodeInfo.datapathId, flowId, pipelineOrchestrator.getTable(Service.SFC_CLASSIFIER));
-
- Map<String, String> externalIds = new HashMap<>();
- externalIds.put("attached-mac", "f6:00:00:0f:00:01");
- southboundUtils.addTerminationPoint(nodeInfo.bridgeNode, SF1DPLPORTNAME, "internal", (Map<String, String>) null, externalIds);
- externalIds.clear();
- externalIds.put("attached-mac", "f6:00:00:0c:00:01");
- southboundUtils.addTerminationPoint(nodeInfo.bridgeNode, "vm1", "internal");
- externalIds.clear();
- externalIds.put("attached-mac", "f6:00:00:0c:00:02");
- southboundUtils.addTerminationPoint(nodeInfo.bridgeNode, "vm2", "internal");
-
- InstanceIdentifier<TerminationPoint> tpIid =
- southboundUtils.createTerminationPointInstanceIdentifier(nodeInfo.bridgeNode, SF1DPLPORTNAME);
- final NotifyingDataChangeListener portOperationalListener =
- new NotifyingDataChangeListener(LogicalDatastoreType.OPERATIONAL, tpIid, waitList);
- portOperationalListener.registerDataChangeListener(dataBroker);
-
- InstanceIdentifier<RenderedServicePath> rspIid = sfcUtils.getRspId(RSPNAME);
- final NotifyingDataChangeListener rspOperationalListener =
- new NotifyingDataChangeListener(LogicalDatastoreType.OPERATIONAL, rspIid, waitList);
- rspOperationalListener.registerDataChangeListener(dataBroker);
-
- OvsdbBridgeAugmentation bridgeAugmentation = southbound.extractBridgeAugmentation(nodeInfo.bridgeNode);
- OvsdbNodeRef ovsdbNodeRef = null;
- if (bridgeAugmentation != null) {
- ovsdbNodeRef = bridgeAugmentation.getManagedBy();
- }
-
- testModelPut(serviceFunctionsBuilder(), ServiceFunctions.class);
- testModelPut(serviceFunctionForwardersBuilder(ovsdbNodeRef), ServiceFunctionForwarders.class);
- testModelPut(serviceFunctionChainsBuilder(), ServiceFunctionChains.class);
- testModelPut(serviceFunctionPathsBuilder(), ServiceFunctionPaths.class);
-
- testModelPut(accessListsBuilder(false), AccessLists.class);
- testModelPut(classifiersBuilder(), Classifiers.class);
- ServiceFunctionPathBuilder serviceFunctionPathBuilder =
- serviceFunctionPathUtils.serviceFunctionPathBuilder(
- new ServiceFunctionPathBuilder(), sfpName, sfcName, startingIndex, false);
- SfcProviderRenderedPathAPI.createRenderedServicePathAndState(serviceFunctionPathBuilder.build(),
- renderedServicePathUtils.createRenderedPathInputBuilder(new CreateRenderedPathInputBuilder(),
- SFCPATH, RSPNAME).build());
-
- portOperationalListener.waitForCreation();
- long vxGpeOfPort = southbound.getOFPort(nodeInfo.bridgeNode, SFFDPL1NAME);
- assertNotEquals("vxGpePort was not found", 0, vxGpeOfPort);
-
- rspOperationalListener.waitForCreation();
- RenderedServicePath rsp = mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, rspIid);
- assertNotNull("RSP was not found", rsp);
-
- flowId = FlowNames.getSfcIngressClass(RULENAME, rsp.getPathId(), rsp.getStartingIndex());
- nvItUtils.verifyFlow(nodeInfo.datapathId, flowId, pipelineOrchestrator.getTable(Service.SFC_CLASSIFIER));
- RenderedServicePathHop lastHop = sfcUtils.getLastHop(rsp);
- short lastServiceindex = (short)((lastHop.getServiceIndex()).intValue() - 1);
- flowId = FlowNames.getSfcEgressClass(vxGpeOfPort, rsp.getPathId(), lastServiceindex);
- nvItUtils.verifyFlow(nodeInfo.datapathId, flowId, pipelineOrchestrator.getTable(Service.SFC_CLASSIFIER));
- flowId = FlowNames.getSfcEgressClassBypass(rsp.getPathId(), lastServiceindex, 1);
- nvItUtils.verifyFlow(nodeInfo.datapathId, flowId, pipelineOrchestrator.getTable(Service.CLASSIFIER));
- flowId = FlowNames.getArpResponder(SF1IP);
- nvItUtils.verifyFlow(nodeInfo.datapathId, flowId, pipelineOrchestrator.getTable(Service.ARP_RESPONDER));
- // Only verify these flows if NetVirt adds them and not SFC
- //flowId = FlowNames.getSfEgress(GPEUDPPORT);
- //verifyFlow(nodeInfo.datapathId, flowId, pipelineOrchestrator.getTable(Service.SFC_CLASSIFIER));
- //flowId = FlowNames.getSfIngress(GPEUDPPORT, SF1IP);
- //verifyFlow(nodeInfo.datapathId, flowId, Service.CLASSIFIER.getTable());
-
- LOG.info("check for flows!!!!!!!!!!!!!");
- //Thread.sleep(30000);
- InstanceIdentifier<Flow> flowIid = createFlowIid(nodeInfo.datapathId, flowId,
- pipelineOrchestrator.getTable(Service.CLASSIFIER));
-
- final NotifyingDataChangeListener flowConfigurationListener =
- new NotifyingDataChangeListener(LogicalDatastoreType.CONFIGURATION, flowIid, waitList);
- flowConfigurationListener.registerDataChangeListener(dataBroker);
- final NotifyingDataChangeListener flowOperationalListener =
- new NotifyingDataChangeListener(LogicalDatastoreType.OPERATIONAL, flowIid, waitList);
- flowOperationalListener.registerDataChangeListener(dataBroker);
-
- deleteRsp(RSPNAME);
- rspOperationalListener.waitForDeletion();
- rsp = mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, rspIid);
- assertNull("RSP should not be found", rsp);
-
- flowConfigurationListener.waitForDeletion();
- Flow flow = mdsalUtils.read(LogicalDatastoreType.CONFIGURATION, flowIid);
- assertNull("Flow should not be found in CONFIGURATION " + flowIid, flow);
-
- flowOperationalListener.waitForDeletion();
- flow = mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, flowIid);
- assertNull("Flow should not be found in OPERATIONAL " + flowIid, flow);
-
- nodeInfo.disconnect();
- }
-
- private void deleteRsp(String rspName) {
- RenderedServicePathKey renderedServicePathKey =
- new RenderedServicePathKey(RspName.getDefaultInstance(rspName));
- InstanceIdentifier<RenderedServicePath> path =
- InstanceIdentifier.create(RenderedServicePaths.class)
- .child(RenderedServicePath.class, renderedServicePathKey);
- mdsalUtils.delete(LogicalDatastoreType.OPERATIONAL, path);
- }
-
- /**
- * Test the standalone NetvirtSfc implementation
- * NOTE: This test requires an OVS with the NSH v8 patch, otherwise it will fail miserably.
- * @throws InterruptedException
- */
- @Ignore
- @Test
- public void testStandalone() throws InterruptedException {
- String bridgeName = "sw1";
- ConnectionInfo connectionInfo = SouthboundUtils.getConnectionInfo(addressStr, portStr);
- assertNotNull("connection failed", southboundUtils.connectOvsdbNode(connectionInfo));
- Node ovsdbNode = southboundUtils.getOvsdbNode(connectionInfo);
- assertNotNull("node is not connected", ovsdbNode);
-
- String controllerTarget = "tcp:192.168.50.1:6653";
- List<ControllerEntry> setControllerEntry = southboundUtils.createControllerEntry(controllerTarget);
- Assert.assertTrue(southboundUtils.addBridge(connectionInfo, null, bridgeName, null, true,
- SouthboundConstants.OVSDB_FAIL_MODE_MAP.inverse().get("secure"), true, null, null,
- setControllerEntry, null, "00:00:00:00:00:00:00:01"));
- assertTrue("Controller " + SouthboundUtils.connectionInfoToString(connectionInfo)
- + " is not connected", itUtils.isControllerConnected(connectionInfo));
-
- Node bridgeNode = southbound.getBridgeNode(ovsdbNode, bridgeName);
- assertNotNull("bridge " + bridgeName + " was not found", bridgeNode);
- long datapathId = southbound.getDataPathId(bridgeNode);
- String datapathIdString = southbound.getDatapathId(bridgeNode);
- LOG.info("testNetVirt: bridgeNode: {}, datapathId: {} - {}", bridgeNode, datapathIdString, datapathId);
- assertNotEquals("datapathId was not found", datapathId, 0);
-
- SfcClassifier sfcClassifier = new SfcClassifier(dataBroker, southbound, mdsalUtils);
- //sfcClassifier.programLocalInPort(datapathId, "4096", (long)1, (short)0, (short)50, true);
-
- NshUtils nshUtils = new NshUtils(new Ipv4Address("192.168.50.71"), new PortNumber(6633),
- (long)10, (short)255, (long)4096, (long)4096);
- MatchesBuilder matchesBuilder = aclUtils.matchesBuilder(new MatchesBuilder(), 80);
- sfcClassifier.programSfcClassiferFlows(datapathId, (short)0, "test", matchesBuilder.build(),
- nshUtils, (long)2, true);
-
- //nshUtils = new NshUtils(null, null, (long)10, (short)253, 0, 0);
- //sfcClassifier.programEgressSfcClassiferFlows(datapathId, (short)0, "test", null,
- // nshUtils, (long)2, (long)3, true);
-
- //NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(datapathId);
- //FlowBuilder flowBuilder = getLocalInPortFlow(datapathId, "4096", (long) 1,
- // pipelineOrchestrator.getTable(Service.CLASSIFIER));
- //Flow flow = getFlow(flowBuilder, nodeBuilder, LogicalDatastoreType.CONFIGURATION);
- //assertNotNull("Could not find flow in config", flow);
- //flow = getFlow(flowBuilder, nodeBuilder, LogicalDatastoreType.OPERATIONAL);
- //assertNotNull("Could not find flow in operational", flow);
-
- //MatchBuilder matchBuilder = sfcClassifier.buildMatch(matchesBuilder.build());
- //NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(datapathId);
- //FlowBuilder flowBuilder = getSfcClassifierFlow(datapathId,
- // pipelineOrchestrator.getTable(Service.CLASSIFIER), "test", null,
- // nshUtils, (long) 2, matchBuilder);
- //Flow flow = getFlow(flowBuilder, nodeBuilder, LogicalDatastoreType.CONFIGURATION);
- //assertNotNull("Could not find flow in config", flow);
- //flow = getFlow(flowBuilder, nodeBuilder, LogicalDatastoreType.OPERATIONAL);
- //assertNotNull("Could not find flow in operational", flow);
-
- //nodeBuilder = FlowUtils.createNodeBuilder(datapathId);
- //flowBuilder = getEgressSfcClassifierFlow(datapathId,
- //pipelineOrchestrator.getTable(Service.CLASSIFIER),
- //"test", nshUtils, (long) 2);
- //flow = getFlow(flowBuilder, nodeBuilder, LogicalDatastoreType.CONFIGURATION);
- //assertNotNull("Could not find flow in config", flow);
- //flow = getFlow(flowBuilder, nodeBuilder, LogicalDatastoreType.OPERATIONAL);
- //assertNotNull("Could not find flow in operational", flow);
-
- LOG.info("***** Go look for flows *****");
- Thread.sleep(30000);
- assertTrue(southboundUtils.deleteBridge(connectionInfo, bridgeName));
- Thread.sleep(1000);
- assertTrue(southboundUtils.deleteBridge(connectionInfo, INTEGRATION_BRIDGE_NAME));
- Thread.sleep(1000);
- assertTrue(southboundUtils.disconnectOvsdbNode(connectionInfo));
- }
-
- private InstanceIdentifier<Flow> createFlowIid(long datapathId, String flowId, short table) {
- org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder nodeBuilder =
- FlowUtils.createNodeBuilder(datapathId);
- FlowBuilder flowBuilder =
- FlowUtils.initFlowBuilder(new FlowBuilder(), flowId, table);
- return FlowUtils.createFlowPath(flowBuilder, nodeBuilder);
- }
-
- private Flow getFlow (
- FlowBuilder flowBuilder,
- org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder nodeBuilder,
- LogicalDatastoreType store) throws InterruptedException {
-
- Flow flow = null;
- for (int i = 0; i < 10; i++) {
- LOG.info("getFlow try {} from {}: looking for flow: {}, node: {}",
- i, store, flowBuilder.build(), nodeBuilder.build());
- flow = FlowUtils.getFlow(flowBuilder, nodeBuilder, dataBroker.newReadOnlyTransaction(), store);
- if (flow != null) {
- LOG.info("getFlow try {} from {}: found flow: {}", i, store, flow);
- break;
- }
- Thread.sleep(1000);
- }
- return flow;
- }
-
- private void readwait() {
- if (ovsdb_wait) {
- LOG.warn("Waiting, kill with ps -ef | grep java, kill xxx... ");
- try {
- System.in.read();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
-
- private List<NotifyingDataChangeListener> waitList = new ArrayList<>();
-
- private void closeWaitFors() {
- for (Iterator<NotifyingDataChangeListener> iterator = waitList.iterator(); iterator.hasNext();) {
- NotifyingDataChangeListener listener = iterator.next();
- iterator.remove();
- try {
- listener.close();
- } catch (Exception ex) {
- LOG.warn("Failed to close registration {}", listener, ex);
- }
- }
- LOG.info("waitList size {}", waitList.size());
- }
-
-}
+++ /dev/null
-/*
- * Copyright © 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc.it.utils;
-
-import java.util.List;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.service.function.forwarder.base.sff.data.plane.locator.DataPlaneLocatorBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sl.rev140701.VxlanGpe;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sl.rev140701.data.plane.locator.locator.type.IpBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
-import org.opendaylight.yangtools.concepts.Builder;
-
-public abstract class AbstractUtils {
- public <T> List<T> list(List<T> list, Builder<T> builder) {
- list.add(builder.build());
- return list;
- }
-
- public IpBuilder ipBuilder(String ip, int port) {
- return new IpBuilder()
- .setIp(new IpAddress(ip.toCharArray()))
- .setPort(new PortNumber(port));
- }
-
- public DataPlaneLocatorBuilder dataPlaneLocatorBuilder(DataPlaneLocatorBuilder dataPlaneLocatorBuilder,
- String ip, int port) {
- return dataPlaneLocatorBuilder
- .setLocatorType(ipBuilder(ip, port).build())
- .setTransport(VxlanGpe.class);
- }
-}
+++ /dev/null
-/*
- * Copyright © 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc.it.utils;
-
-import java.util.ArrayList;
-import java.util.List;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.AccessListsBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.Ipv4Acl;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.Acl;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.AclBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.AccessListEntriesBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.Ace;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.AceBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.ActionsBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.MatchesBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.actions.packet.handling.PermitBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.matches.ace.type.AceIpBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.packet.fields.rev160218.acl.transport.header.fields.DestinationPortRangeBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.packet.fields.rev160218.acl.transport.header.fields.SourcePortRangeBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.acl.rev150105.RedirectToSfc;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.acl.rev150105.RedirectToSfcBuilder;
-
-public class AclUtils extends AbstractUtils {
- public MatchesBuilder matchesBuilder(MatchesBuilder matchesBuilder, int destPort) {
- SourcePortRangeBuilder sourcePortRangeBuilder = new SourcePortRangeBuilder()
- .setLowerPort(PortNumber.getDefaultInstance("0"))
- .setUpperPort(PortNumber.getDefaultInstance("0"));
-
- PortNumber portNumber = new PortNumber(destPort);
- DestinationPortRangeBuilder destinationPortRangeBuilder = new DestinationPortRangeBuilder()
- .setLowerPort(portNumber)
- .setUpperPort(portNumber);
-
- AceIpBuilder aceIpBuilder = new AceIpBuilder()
- .setSourcePortRange(sourcePortRangeBuilder.build())
- .setDestinationPortRange(destinationPortRangeBuilder.build())
- .setProtocol((short)6);
-
- return matchesBuilder.setAceType(aceIpBuilder.build());
- }
-
- public ActionsBuilder actionsBuilder(ActionsBuilder actionsBuilder, Boolean permit) {
- return actionsBuilder.setPacketHandling(new PermitBuilder().setPermit(permit).build());
- }
-
- public ActionsBuilder actionsBuilder(ActionsBuilder actionsBuilder, String sfcName, boolean renderRsp) {
- RedirectToSfcBuilder redirectToSfcBuilder = new RedirectToSfcBuilder()
- .setSfcName(sfcName)
- .setRenderRsp(renderRsp);
-
- return actionsBuilder.addAugmentation(RedirectToSfc.class, redirectToSfcBuilder.build());
- }
-
- public AceBuilder aceBuilder(AceBuilder accessListEntryBuilder,
- String ruleName,
- MatchesBuilder matchesBuilder,
- ActionsBuilder actionsBuilder) {
- return accessListEntryBuilder
- .setRuleName(ruleName)
- .setMatches(matchesBuilder.build())
- .setActions(actionsBuilder.build());
- }
-
- public AccessListEntriesBuilder accessListEntriesBuidler(AccessListEntriesBuilder accessListEntriesBuilder,
- AceBuilder aceBuilder) {
- List<Ace> aceList = new ArrayList<>();
- aceList.add(aceBuilder.build());
-
- return accessListEntriesBuilder.setAce(aceList);
- }
-
- public AclBuilder aclBuilder(AclBuilder aclBuilder,
- String aclName,
- AccessListEntriesBuilder accessListEntriesBuilder) {
- return aclBuilder
- .setAclName(aclName)
- .setAclType(Ipv4Acl.class)
- .setAccessListEntries(accessListEntriesBuilder.build());
- }
-
- public AccessListsBuilder accesslistsbuilder(AccessListsBuilder accessListsBuilder,
- AclBuilder aclBuilder) {
- List<Acl> aclList = new ArrayList<>();
- aclList.add(aclBuilder.build());
-
- return accessListsBuilder.setAcl(aclList);
- }
-}
+++ /dev/null
-/*
- * Copyright © 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc.it.utils;
-
-import java.util.ArrayList;
-import java.util.List;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.classifier.rev150105.ClassifiersBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.classifier.rev150105.classifiers.Classifier;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.classifier.rev150105.classifiers.ClassifierBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.classifier.rev150105.classifiers.classifier.SffsBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.classifier.rev150105.classifiers.classifier.sffs.Sff;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.classifier.rev150105.classifiers.classifier.sffs.SffBuilder;
-
-public class ClassifierUtils extends AbstractUtils {
- public SffBuilder sffBuilder(SffBuilder sffBuilder, String sffName) {
- return sffBuilder.setName(sffName);
- }
-
- public SffsBuilder sffsBuilder(SffsBuilder sffsBuilder, SffBuilder sffBuilder) {
- List<Sff> sffList = new ArrayList<>();
- sffList.add(sffBuilder.build());
- sffsBuilder.setSff(sffList);
-
- return sffsBuilder;
- }
-
- public ClassifierBuilder classifierBuilder(ClassifierBuilder classifierBuilder,
- String classifierName, String aclName,
- SffsBuilder sffsBuilder) {
- return classifierBuilder
- .setName(classifierName)
- .setAcl(aclName);
- }
-
- public ClassifiersBuilder classifiersBuilder(ClassifiersBuilder classifiersBuilder,
- ClassifierBuilder classifierBuilder) {
- List<Classifier> classifierList = new ArrayList<>();
- classifierList.add(classifierBuilder.build());
- classifiersBuilder.setClassifier(classifierList);
-
- return classifiersBuilder;
- }
-}
+++ /dev/null
-/*
- * Copyright © 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc.it.utils;
-
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.providers.config.rev160109.NetvirtProvidersConfigBuilder;
-
-public class NetvirtConfigUtils {
- public NetvirtProvidersConfigBuilder netvirtProvidersConfigBuilder(
- NetvirtProvidersConfigBuilder netvirtProvidersConfigBuilder, short tableOffset) {
- return netvirtProvidersConfigBuilder.setTableOffset(tableOffset);
- }
-}
+++ /dev/null
-/*
- * Copyright © 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc.it.utils;
-
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.rev150105.SfcBuilder;
-
-public class NetvirtSfcUtils {
- public SfcBuilder sfcBuilder(SfcBuilder sfcBuilder, String sfcName) {
- return sfcBuilder.setName(sfcName);
- }
-}
+++ /dev/null
-/*
- * Copyright © 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc.it.utils;
-
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.CreateRenderedPathInputBuilder;
-
-public class RenderedServicePathUtils extends AbstractUtils {
-
- public CreateRenderedPathInputBuilder createRenderedPathInputBuilder(
- CreateRenderedPathInputBuilder createRenderedPathInputBuilder, String sfpName, String rspName) {
- return createRenderedPathInputBuilder
- .setName(rspName)
- .setParentServiceFunctionPath(sfpName)
- .setSymmetric(false);
- }
-}
+++ /dev/null
-/*
- * Copyright © 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc.it.utils;
-
-import java.util.List;
-
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.SfcName;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.SftTypeName;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfc.rev140701.ServiceFunctionChainsBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfc.rev140701.service.function.chain.grouping.ServiceFunctionChain;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfc.rev140701.service.function.chain.grouping.ServiceFunctionChainBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfc.rev140701.service.function.chain.grouping.service.function.chain.SfcServiceFunction;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfc.rev140701.service.function.chain.grouping.service.function.chain.SfcServiceFunctionBuilder;
-
-public class ServiceFunctionChainUtils extends AbstractUtils {
- public SfcServiceFunctionBuilder sfcServiceFunctionBuilder(SfcServiceFunctionBuilder sfcServiceFunctionBuilder,
- String name,
- SftTypeName type) {
- return sfcServiceFunctionBuilder
- .setName(name)
- .setType(type);
- }
-
- public ServiceFunctionChainBuilder serviceFunctionChainBuilder(
- ServiceFunctionChainBuilder serviceFunctionChainBuilder, String name, Boolean symmetric,
- List<SfcServiceFunction> sfcServiceFunctionList) {
-
- return serviceFunctionChainBuilder
- .setName(SfcName.getDefaultInstance(name))
- .setSymmetric(symmetric)
- .setSfcServiceFunction(sfcServiceFunctionList);
- }
-
- public ServiceFunctionChainsBuilder serviceFunctionChainsBuilder(
- ServiceFunctionChainsBuilder serviceFunctionChainsBuilder,
- List<ServiceFunctionChain> serviceFunctionChainBuilderList) {
-
- return serviceFunctionChainsBuilder.setServiceFunctionChain(serviceFunctionChainBuilderList);
- }
-}
+++ /dev/null
-/*
- * Copyright © 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc.it.utils;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.SfDataPlaneLocatorName;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.SfName;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.SffDataPlaneLocatorName;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.SffName;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.SnName;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.ovs.rev140701.SffOvsBridgeAugmentation;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.ovs.rev140701.SffOvsBridgeAugmentationBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.ovs.rev140701.SffOvsLocatorOptionsAugmentation;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.ovs.rev140701.SffOvsLocatorOptionsAugmentationBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.ovs.rev140701.SffOvsNodeAugmentation;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.ovs.rev140701.SffOvsNodeAugmentationBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.ovs.rev140701.bridge.OvsBridgeBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.ovs.rev140701.node.OvsNodeBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.ovs.rev140701.options.OvsOptionsBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.ServiceFunctionForwardersBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.service.function.forwarders.ServiceFunctionForwarder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.service.function.forwarders.ServiceFunctionForwarderBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.service.function.forwarders.service.function.forwarder.ServiceFunctionDictionary;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.service.function.forwarders.service.function.forwarder.ServiceFunctionDictionaryBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.service.function.forwarder.base.SffDataPlaneLocator;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.service.function.forwarder.base.SffDataPlaneLocatorBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.service.function.forwarders.service.function.forwarder.service.function.dictionary.SffSfDataPlaneLocatorBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.service.function.forwarder.base.sff.data.plane.locator.DataPlaneLocatorBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeRef;
-
-public class ServiceFunctionForwarderUtils extends AbstractUtils {
- public OvsOptionsBuilder ovsOptionsBuilder(OvsOptionsBuilder ovsOptionsBuilder, int port) {
- String flow = "flow";
- return ovsOptionsBuilder
- .setDstPort(String.valueOf(port))
- .setRemoteIp(flow)
- .setKey(flow)
- .setNsi(flow)
- .setNsp(flow)
- .setNshc1(flow)
- .setNshc2(flow)
- .setNshc3(flow)
- .setNshc4(flow);
- }
-
- public SffDataPlaneLocatorBuilder sffDataPlaneLocatorBuilder(SffDataPlaneLocatorBuilder sffDataPlaneLocatorBuilder,
- DataPlaneLocatorBuilder dataPlaneLocatorBuilder,
- String dplName) {
- SffOvsLocatorOptionsAugmentationBuilder sffOvsLocatorOptionsAugmentationBuilder =
- new SffOvsLocatorOptionsAugmentationBuilder();
- sffOvsLocatorOptionsAugmentationBuilder.setOvsOptions(
- ovsOptionsBuilder(new OvsOptionsBuilder(), 6633).build());
-
- return sffDataPlaneLocatorBuilder
- .setName(new SffDataPlaneLocatorName(dplName))
- .setDataPlaneLocator(dataPlaneLocatorBuilder.build())
- .addAugmentation(SffOvsLocatorOptionsAugmentation.class,
- sffOvsLocatorOptionsAugmentationBuilder.build());
- }
-
- public SffSfDataPlaneLocatorBuilder sffSfDataPlaneLocatorBuilder(
- SffSfDataPlaneLocatorBuilder sffSfDataPlaneLocatorBuilder, String sffDplName, String sfDplName) {
- return sffSfDataPlaneLocatorBuilder
- .setSfDplName(SfDataPlaneLocatorName.getDefaultInstance(sfDplName))
- .setSffDplName(SffDataPlaneLocatorName.getDefaultInstance(sffDplName));
- }
-
- public ServiceFunctionDictionaryBuilder serviceFunctionDictionaryBuilder(
- ServiceFunctionDictionaryBuilder serviceFunctionDictionaryBuilder,
- SffSfDataPlaneLocatorBuilder sffSfDataPlaneLocatorBuilder,
- String sfName) {
-
- return serviceFunctionDictionaryBuilder
- .setName(SfName.getDefaultInstance(sfName))
- .setSffSfDataPlaneLocator(sffSfDataPlaneLocatorBuilder.build());
- }
-
- public OvsBridgeBuilder ovsBridgeBuilder(OvsBridgeBuilder ovsBridgeBuilder, String bridgeName) {
- return ovsBridgeBuilder.setBridgeName(bridgeName);
- }
-
- public ServiceFunctionForwarderBuilder serviceFunctionForwarderBuilder(
- ServiceFunctionForwarderBuilder serviceFunctionForwarderBuilder,
- String sffName, String serviceNodeName, String bridgeName,
- List<SffDataPlaneLocator> sffDataPlaneLocatorList,
- List<ServiceFunctionDictionary> serviceFunctionDictionaryList,
- OvsdbNodeRef ovsdbNodeRef) {
-
- SffOvsBridgeAugmentationBuilder sffOvsBridgeAugmentationBuilder = new SffOvsBridgeAugmentationBuilder();
- sffOvsBridgeAugmentationBuilder.setOvsBridge(ovsBridgeBuilder(new OvsBridgeBuilder(), bridgeName).build());
-
- SffOvsNodeAugmentationBuilder sffOvsNodeAugmentationBuilder = new SffOvsNodeAugmentationBuilder();
- OvsNodeBuilder ovsNodeBuilder = new OvsNodeBuilder();
- ovsNodeBuilder.setNodeId(ovsdbNodeRef);
- sffOvsNodeAugmentationBuilder.setOvsNode(ovsNodeBuilder.build());
-
- return serviceFunctionForwarderBuilder
- .setName(new SffName(sffName))
- .setServiceNode(new SnName(serviceNodeName))
- .setServiceFunctionDictionary(serviceFunctionDictionaryList)
- .setSffDataPlaneLocator(sffDataPlaneLocatorList)
- .addAugmentation(SffOvsNodeAugmentation.class, sffOvsNodeAugmentationBuilder.build())
- .addAugmentation(SffOvsBridgeAugmentation.class, sffOvsBridgeAugmentationBuilder.build());
- }
-
- public ServiceFunctionForwardersBuilder serviceFunctionForwardersBuilder(
- ServiceFunctionForwardersBuilder serviceFunctionForwardersBuilder,
- List<ServiceFunctionForwarder> serviceFunctionForwarderList) {
- return serviceFunctionForwardersBuilder.setServiceFunctionForwarder(serviceFunctionForwarderList);
- }
-
- public ServiceFunctionForwarderBuilder serviceFunctionForwarderBuilder(
- String sffName, String sffIp, int port, String sffDplName,
- String sfIp, String snName, String bridgeName, String sfName, String sfDplName,
- OvsdbNodeRef ovsdbNodeRef) {
-
- DataPlaneLocatorBuilder dataPlaneLocatorBuilder =
- dataPlaneLocatorBuilder(new DataPlaneLocatorBuilder(), sffIp, port);
- SffDataPlaneLocatorBuilder sffDataPlaneLocatorBuilder =
- sffDataPlaneLocatorBuilder( new SffDataPlaneLocatorBuilder(), dataPlaneLocatorBuilder, sffDplName);
- List<SffDataPlaneLocator> sffDataPlaneLocatorList =
- list(new ArrayList<>(), sffDataPlaneLocatorBuilder);
-
- SffSfDataPlaneLocatorBuilder sffSfDataPlaneLocatorBuilder =
- sffSfDataPlaneLocatorBuilder(new SffSfDataPlaneLocatorBuilder(), sffDplName, sfDplName);
- ServiceFunctionDictionaryBuilder serviceFunctionDictionaryBuilder =
- serviceFunctionDictionaryBuilder(new ServiceFunctionDictionaryBuilder(),
- sffSfDataPlaneLocatorBuilder, sfName);
- List<ServiceFunctionDictionary> serviceFunctionDictionaryList =
- list(new ArrayList<>(), serviceFunctionDictionaryBuilder);
-
- ServiceFunctionForwarderBuilder serviceFunctionForwarderBuilder =
- serviceFunctionForwarderBuilder(
- new ServiceFunctionForwarderBuilder(), sffName, snName, bridgeName,
- sffDataPlaneLocatorList, serviceFunctionDictionaryList, ovsdbNodeRef);
- return serviceFunctionForwarderBuilder;
- }
-}
+++ /dev/null
-/*
- * Copyright © 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc.it.utils;
-
-import java.util.List;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.SfcName;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.SfpName;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfp.rev140701.ServiceFunctionPathsBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfp.rev140701.service.function.paths.ServiceFunctionPath;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfp.rev140701.service.function.paths.ServiceFunctionPathBuilder;
-
-public class ServiceFunctionPathUtils extends AbstractUtils {
- public ServiceFunctionPathBuilder serviceFunctionPathBuilder(
- ServiceFunctionPathBuilder serviceFunctionPathBuilder,
- String sfpName, String sfcName, short startingIndex, Boolean symmetric) {
-
- return serviceFunctionPathBuilder
- .setSymmetric(symmetric)
- .setName(SfpName.getDefaultInstance(sfpName))
- .setServiceChainName(SfcName.getDefaultInstance(sfcName))
- .setStartingIndex(startingIndex);
- }
-
- public ServiceFunctionPathsBuilder serviceFunctionPathsBuilder(
- List<ServiceFunctionPath> serviceFunctionPathList) {
-
- return new ServiceFunctionPathsBuilder().setServiceFunctionPath(serviceFunctionPathList);
- }
-}
+++ /dev/null
-/*
- * Copyright © 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc.it.utils;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.SfDataPlaneLocatorName;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.SfName;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.SffName;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.SftTypeName;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sf.rev140701.ServiceFunctionsBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sf.rev140701.service.function.base.SfDataPlaneLocator;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sf.rev140701.service.function.base.SfDataPlaneLocatorBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sf.rev140701.service.functions.ServiceFunction;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sf.rev140701.service.functions.ServiceFunctionBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sl.rev140701.VxlanGpe;
-import org.opendaylight.yang.gen.v1.urn.ericsson.params.xml.ns.yang.sfc.sf.ovs.rev160107.SfDplOvsAugmentation;
-import org.opendaylight.yang.gen.v1.urn.ericsson.params.xml.ns.yang.sfc.sf.ovs.rev160107.SfDplOvsAugmentationBuilder;
-import org.opendaylight.yang.gen.v1.urn.ericsson.params.xml.ns.yang.sfc.sf.ovs.rev160107.connected.port.OvsPortBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
-
-public class ServiceFunctionUtils extends AbstractUtils {
- public SfDataPlaneLocatorBuilder sfDataPlaneLocatorBuilder(SfDataPlaneLocatorBuilder sfDataPlaneLocatorBuilder,
- String ip, int port, String dplName,
- String sf1DplPortName, String sffName) {
- SfDplOvsAugmentationBuilder sfDplOvsAugmentationBuilder = new SfDplOvsAugmentationBuilder();
- OvsPortBuilder ovsPortBuilder = new OvsPortBuilder().setPortId(sf1DplPortName);
- sfDplOvsAugmentationBuilder.setOvsPort(ovsPortBuilder.build());
-
- return sfDataPlaneLocatorBuilder
- .addAugmentation(SfDplOvsAugmentation.class, sfDplOvsAugmentationBuilder.build())
- .setLocatorType(ipBuilder(ip, port).build())
- .setName(SfDataPlaneLocatorName.getDefaultInstance(dplName))
- .setTransport(VxlanGpe.class)
- .setServiceFunctionForwarder(SffName.getDefaultInstance(sffName));
- }
-
- public ServiceFunctionBuilder serviceFunctionBuilder(ServiceFunctionBuilder serviceFunctionBuilder,
- String ip, String sfName,
- List<SfDataPlaneLocator> sfDataPlaneLocatorList,
- SftTypeName type) {
- return serviceFunctionBuilder
- .setSfDataPlaneLocator(sfDataPlaneLocatorList)
- .setName(new SfName(sfName))
- .setIpMgmtAddress(new IpAddress(ip.toCharArray()))
- .setType(type);
- }
-
- public ServiceFunctionsBuilder serviceFunctionsBuilder(ServiceFunctionsBuilder serviceFunctionsBuilder,
- List<ServiceFunction> serviceFunctionList) {
- return serviceFunctionsBuilder.setServiceFunction(serviceFunctionList);
- }
-
- public ServiceFunctionBuilder serviceFunctionBuilder(String sfIp, int port, String sf1DplName,
- String sf1DplPortName,
- String sffname, String sfName) {
- SfDataPlaneLocatorBuilder sfDataPlaneLocator =
- sfDataPlaneLocatorBuilder(new SfDataPlaneLocatorBuilder(), sfIp, port, sf1DplName,
- sf1DplPortName, sffname);
- List<SfDataPlaneLocator> sfDataPlaneLocatorList = list(new ArrayList<>(), sfDataPlaneLocator);
- return serviceFunctionBuilder(
- new ServiceFunctionBuilder(), sfIp, sfName, sfDataPlaneLocatorList, new SftTypeName("firewall"));
- }
-
-
-}
+++ /dev/null
-/*
- * Copyright © 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.sfc.it.utils;
-
-import org.opendaylight.yang.gen.v1.urn.ericsson.params.xml.ns.yang.sfc.of.renderer.rev151123.SfcOfRendererConfig;
-import org.opendaylight.yang.gen.v1.urn.ericsson.params.xml.ns.yang.sfc.of.renderer.rev151123.SfcOfRendererConfigBuilder;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-
-public class SfcConfigUtils {
- public SfcOfRendererConfigBuilder sfcOfRendererConfigBuilder(SfcOfRendererConfigBuilder sfcOfRendererConfigBuilder,
- short tableOffset, short egressTable) {
- return sfcOfRendererConfigBuilder
- .setSfcOfTableOffset(tableOffset)
- .setSfcOfAppEgressTableOffset(egressTable);
- }
-
- public InstanceIdentifier<SfcOfRendererConfig> getPath() {
- return InstanceIdentifier.create(SfcOfRendererConfig.class);
- }
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-Copyright © 2015 Red Hat, Inc. and others. All rights reserved.
-This program and the accompanying materials are made available under the
-terms of the Eclipse Public License v1.0 which accompanies this distribution,
-and is available at http://www.eclipse.org/legal/epl-v10.html INTERNAL
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>karaf4-parent</artifactId>
- <version>1.9.0</version>
- <relativePath/>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>openstack.net-virt-sfc-karaf</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <properties>
- <karaf.localFeature>odl-ovsdb-sfc-test</karaf.localFeature>
- </properties>
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>openstack.net-virt-sfc-artifacts</artifactId>
- <version>${project.version}</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- </dependencies>
- </dependencyManagement>
- <dependencies>
- <dependency>
- <!-- scope is compile so all features (there is only one) are installed
- into startup.properties and the feature repo itself is not installed -->
- <groupId>org.apache.karaf.features</groupId>
- <artifactId>framework</artifactId>
- <type>kar</type>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>openstack.net-virt-sfc-features4</artifactId>
- <version>${project.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- <scope>runtime</scope>
- </dependency>
- </dependencies>
- <!-- DO NOT install or deploy the karaf artifact -->
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-deploy-plugin</artifactId>
- <configuration>
- <skip>true</skip>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-Copyright © 2015 Red Hat, Inc. and others. All rights reserved.
-This program and the accompanying materials are made available under the
-terms of the Eclipse Public License v1.0 which accompanies this distribution,
-and is available at http://www.eclipse.org/legal/epl-v10.html INTERNAL
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>odlparent-lite</artifactId>
- <version>2.0.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>openstack.net-virt-sfc-aggregator</artifactId>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>pom</packaging>
- <modelVersion>4.0.0</modelVersion>
- <modules>
- <module>api</module>
- <module>impl</module>
- <module>karaf</module>
- <module>features</module>
- <module>artifacts</module>
- <module>it</module>
- </modules>
- <!-- DO NOT install or deploy the repo root pom as it's only needed to initiate a build -->
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-deploy-plugin</artifactId>
- <configuration>
- <skip>true</skip>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-install-plugin</artifactId>
- <configuration>
- <skip>true</skip>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
- <scm>
- <connection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</connection>
- <developerConnection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</developerConnection>
- <tag>HEAD</tag>
- <url>https://wiki.opendaylight.org/view/OVSDB_Integration:Main</url>
- </scm>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
-
-This program and the accompanying materials are made available under the
-terms of the Eclipse Public License v1.0 which accompanies this distribution,
-and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-parent</artifactId>
- <version>0.7.0-SNAPSHOT</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>openstack.net-virt</artifactId>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>bundle</packaging>
- <description>The OVSDB Plugin integration project is a project for OpenDaylight that will implement the Open vSwitch Database RFC 7047 management protocol allowing the Southbound configuration of vSwitches and a network virtualization implementation.</description>
- <licenses>
- <license>
- <name>Eclipse Public License v1.0</name>
- <url>http://www.eclipse.org/legal/epl-v10.html</url>
- </license>
- </licenses>
- <developers>
- <developer>
- <name>Sam Hague</name>
- <email>shague@gmail.com</email>
- <url>https://github.com/shague</url>
- </developer>
- </developers>
- <scm>
- <connection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</connection>
- <developerConnection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</developerConnection>
- <tag>HEAD</tag>
- <url>https://wiki.opendaylight.org/view/OVSDB_Integration:Main</url>
- </scm>
-
- <properties>
- <neutron.model.version>0.9.0-SNAPSHOT</neutron.model.version>
- <ovsdb.version>1.5.0-SNAPSHOT</ovsdb.version>
- <sonar.jacoco.itReportPath>../net-virt-it/target/jacoco-it.exec</sonar.jacoco.itReportPath>
- </properties>
-
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.ovsdb</groupId>
- <artifactId>southbound-api</artifactId>
- <version>${ovsdb.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>utils.config</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>utils.servicehelper</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>utils.mdsal-utils</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.neutron</groupId>
- <artifactId>model</artifactId>
- <version>${neutron.model.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>ietf-inet-types-2013-07-15</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>ietf-topology</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>opendaylight-l2-types</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>ietf-yang-types-20130715</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>ietf-yang-types-20130715</artifactId>
- </dependency>
- <dependency>
- <groupId>commons-net</groupId>
- <artifactId>commons-net</artifactId>
- </dependency>
- <dependency>
- <groupId>org.codehaus.sonar-plugins.java</groupId>
- <artifactId>sonar-jacoco-listeners</artifactId>
- <version>${sonar-jacoco-listeners.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-simple</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-core</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-core</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-module-junit4</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-api-mockito</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-api-support</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-reflect</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-binding-broker-impl</artifactId>
- <type>test-jar</type>
- <scope>test</scope>
- </dependency>
- </dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <extensions>true</extensions>
- <configuration>
- <instructions>
- <Embed-Dependency>utils.config;type=!pom;inline=false</Embed-Dependency>
- <Embed-Transitive>true</Embed-Transitive>
- <Export-Package>
- org.opendaylight.netvirt.openstack.netvirt.translator,
- org.opendaylight.netvirt.openstack.netvirt.translator.crud,
- org.opendaylight.netvirt.openstack.netvirt.api,
- org.opendaylight.netvirt.openstack.netvirt
- </Export-Package>
- </instructions>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
- <configuration>
- <properties>
- <property>
- <name>listener</name>
- <value>org.sonar.java.jacoco.JUnitListener</value>
- </property>
- </properties>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.jacoco</groupId>
- <artifactId>jacoco-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>default-instrument</id>
- <goals>
- <goal>instrument</goal>
- </goals>
- </execution>
- <execution>
- <id>default-restore-instrumented-classes</id>
- <goals>
- <goal>restore-instrumented-classes</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-/*
- * Copyright (c) 2014, 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt;
-
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-
-/**
- * Abstract class for events used by neutron northbound and southbound events.
- */
-public abstract class AbstractEvent {
-
- public enum HandlerType {
- SOUTHBOUND,
- NEUTRON_FLOATING_IP,
- NEUTRON_NETWORK,
- NEUTRON_PORT,
- NEUTRON_PORT_SECURITY,
- NEUTRON_ROUTER,
- NEUTRON_SUBNET,
- NEUTRON_FWAAS,
- NEUTRON_LOAD_BALANCER,
- NEUTRON_LOAD_BALANCER_POOL,
- NEUTRON_LOAD_BALANCER_POOL_MEMBER,
- NODE,
- NEUTRON_L3_ADAPTER,
- DISTRIBUTED_ARP_SERVICE;
-
- public static final int size = HandlerType.values().length;
- }
-
- private HandlerType handlerType;
- private Action action;
- private int transactionId;
-
- public int getTransactionId() {
- return transactionId;
- }
-
- private static int txId = 0;
- private static int incTxId() {
- return ++txId;
- }
- public static int getTxId() {
- return txId;
- }
-
- private AbstractEvent() {
- // this is private to force proper construction
- }
-
- protected AbstractEvent(HandlerType handlerType, Action action) {
- this.handlerType = handlerType;
- this.action = action;
- this.transactionId = incTxId();
- }
-
- public HandlerType getHandlerType() {
- return handlerType;
- }
-
- public Action getAction() {
- return action;
- }
-
- @Override
- public String toString() {
- return "AbstractEvent [transactionId=" + transactionId
- + " handlerType=" + handlerType + " action=" + action + "]";
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((handlerType == null) ? 0 : handlerType.hashCode());
- result = prime * result + ((action == null) ? 0 : action.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- AbstractEvent other = (AbstractEvent) obj;
- if (handlerType == null) {
- if (other.handlerType != null) {
- return false;
- }
- } else if (!handlerType.equals(other.handlerType)) {
- return false;
- }
- if (action == null) {
- if (other.action != null) {
- return false;
- }
- } else if (!action.equals(other.action)) {
- return false;
- }
- return true;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt;
-
-import org.opendaylight.netvirt.openstack.netvirt.api.Status;
-import org.opendaylight.netvirt.openstack.netvirt.api.StatusCode;
-import org.opendaylight.netvirt.openstack.netvirt.api.EventDispatcher;
-
-import com.google.common.base.Preconditions;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.net.HttpURLConnection;
-
-/**
- * OpenStack related events originate from multiple north callbacks as well as south.
- * This interface provides a layer of abstraction between the event dispatcher and the
- * handlers.
- */
-public abstract class AbstractHandler {
- private static final Logger LOG = LoggerFactory.getLogger(AbstractHandler.class);
-
- // The implementation for each of these services is resolved by the OSGi Service Manager
- protected volatile EventDispatcher eventDispatcher;
-
- /**
- * Convert failure status returned by the manager into
- * neutron API service errors.
- *
- * @param status manager status
- * @return An error to be returned to neutron API service.
- */
- protected static int getException(Status status) {
- assert !status.isSuccess();
-
- StatusCode code = status.getCode();
- LOG.debug(" Exception code - {}, description - {}",
- code, status.getDescription());
-
- switch(code) {
- case BADREQUEST:
- return HttpURLConnection.HTTP_BAD_REQUEST;
- case CONFLICT:
- return HttpURLConnection.HTTP_CONFLICT;
- case NOTACCEPTABLE:
- return HttpURLConnection.HTTP_NOT_ACCEPTABLE;
- case NOTFOUND:
- return HttpURLConnection.HTTP_NOT_FOUND;
- default:
- return HttpURLConnection.HTTP_INTERNAL_ERROR;
- }
- }
-
- /**
- * Enqueue the event.
- *
- * @param abstractEvent the {@link AbstractEvent} event to be handled.
- * @see EventDispatcher
- */
- protected void enqueueEvent(AbstractEvent abstractEvent) {
- LOG.debug("enqueueEvent evenDispatcher : {} with event : {}",
- eventDispatcher, abstractEvent);
- Preconditions.checkNotNull(eventDispatcher);
- eventDispatcher.enqueueEvent(abstractEvent);
- }
-
- /**
- * Process the event.
- *
- * @param abstractEvent the {@link AbstractEvent} event to be handled.
- * @see EventDispatcher
- */
- public abstract void processEvent(AbstractEvent abstractEvent);
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt;
-
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.netvirt.utils.mdsal.utils.MdsalUtils;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-/**
- * Class is a wrapper for MdsalUtils.java class. It wrap all the methods
- * from MdsalUtils and call it only when *this* instance is net-virt master
- * instances.
- *
- * Created by vishnoianil on 1/11/16.
- */
-
-public class ClusterAwareMdsalUtils {
-
- private final MdsalUtils mdsalUtils;
-
- /**
- * Class constructor setting the MdsalUtils instance.
- *
- * @param dataBroker the {@link org.opendaylight.controller.md.sal.binding.api.DataBroker}
- */
- public ClusterAwareMdsalUtils(DataBroker dataBroker) {
- mdsalUtils = new MdsalUtils(dataBroker);
- }
-
- /**
- * Wrapper method to execute delete as a blocking transaction.
- *
- * @param store {@link LogicalDatastoreType} which should be modified
- * @param path {@link InstanceIdentifier} to read from
- * @param <D> the data object type
- * @return the result of the request
- */
- public <D extends org.opendaylight.yangtools.yang.binding.DataObject> boolean delete(
- final LogicalDatastoreType store, final InstanceIdentifier<D> path) {
- if (NetvirtProvider.isMasterProviderInstance()) {
- return mdsalUtils.delete(store,path);
- }
- return true;
- }
-
- /**
- * Wrapper method to execute merge as a blocking transaction.
- *
- * @param logicalDatastoreType {@link LogicalDatastoreType} which should be modified
- * @param path {@link InstanceIdentifier} for path to read
- * @param <D> the data object type
- * @return the result of the request
- */
- public <D extends org.opendaylight.yangtools.yang.binding.DataObject> boolean merge(
- final LogicalDatastoreType logicalDatastoreType, final InstanceIdentifier<D> path, D data) {
- if (NetvirtProvider.isMasterProviderInstance()) {
- return mdsalUtils.merge(logicalDatastoreType,path, data);
- }
- return true;
- }
-
- /**
- * Wrapper method to execute put as a blocking transaction.
- *
- * @param logicalDatastoreType {@link LogicalDatastoreType} which should be modified
- * @param path {@link InstanceIdentifier} for path to read
- * @param <D> the data object type
- * @return the result of the request
- */
- public <D extends org.opendaylight.yangtools.yang.binding.DataObject> boolean put(
- final LogicalDatastoreType logicalDatastoreType, final InstanceIdentifier<D> path, D data) {
- if (NetvirtProvider.isMasterProviderInstance()) {
- return mdsalUtils.put(logicalDatastoreType,path, data);
- }
- return true;
- }
-
- /**
- * Wrapper method to executes read as a blocking transaction.
- * Read is open for all instances to execute their normal
- * control flow. Because with current implementation all the
- * net-virt instances execute in similar way, because they want
- * to build their local caches so that all the instances has same
- * state of internal cache.
- *
- * @param store {@link LogicalDatastoreType} to read
- * @param path {@link InstanceIdentifier} for path to read
- * @param <D> the data object type
- * @return the result as the data object requested
- */
- public <D extends org.opendaylight.yangtools.yang.binding.DataObject> D read(
- final LogicalDatastoreType store, final InstanceIdentifier<D> path) {
- return mdsalUtils.read(store,path);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt;
-
-import java.util.ArrayList;
-import java.util.Dictionary;
-import java.util.Hashtable;
-import java.util.List;
-
-import org.apache.commons.lang3.tuple.Pair;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.netvirt.openstack.netvirt.api.ArpProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.BridgeConfigurationManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.ConfigurationService;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-import org.opendaylight.netvirt.openstack.netvirt.api.EgressAclProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.EventDispatcher;
-import org.opendaylight.netvirt.openstack.netvirt.api.GatewayMacResolver;
-import org.opendaylight.netvirt.openstack.netvirt.api.GatewayMacResolverListener;
-import org.opendaylight.netvirt.openstack.netvirt.api.IcmpEchoProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.InboundNatProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.IngressAclProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.L3ForwardingProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.L2ForwardingProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.LoadBalancerProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.MultiTenantAwareRouter;
-import org.opendaylight.netvirt.openstack.netvirt.api.NetworkingProviderManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheListener;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.OutboundNatProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.OvsdbInventoryListener;
-import org.opendaylight.netvirt.openstack.netvirt.api.OvsdbInventoryService;
-import org.opendaylight.netvirt.openstack.netvirt.api.RoutingProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.SecurityGroupCacheManger;
-import org.opendaylight.netvirt.openstack.netvirt.api.SecurityServicesManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.openstack.netvirt.api.TenantNetworkManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.VlanConfigurationCache;
-import org.opendaylight.netvirt.openstack.netvirt.api.VlanResponderProvider;
-import org.opendaylight.netvirt.openstack.netvirt.impl.BridgeConfigurationManagerImpl;
-import org.opendaylight.netvirt.openstack.netvirt.impl.ConfigurationServiceImpl;
-import org.opendaylight.netvirt.openstack.netvirt.impl.DistributedArpService;
-import org.opendaylight.netvirt.openstack.netvirt.impl.EventDispatcherImpl;
-import org.opendaylight.netvirt.openstack.netvirt.impl.HostConfigService;
-import org.opendaylight.netvirt.openstack.netvirt.impl.NeutronL3Adapter;
-import org.opendaylight.netvirt.openstack.netvirt.impl.NodeCacheManagerImpl;
-import org.opendaylight.netvirt.openstack.netvirt.impl.OpenstackRouter;
-import org.opendaylight.netvirt.openstack.netvirt.impl.OvsdbInventoryServiceImpl;
-import org.opendaylight.netvirt.openstack.netvirt.impl.ProviderNetworkManagerImpl;
-import org.opendaylight.netvirt.openstack.netvirt.impl.SecurityGroupCacheManagerImpl;
-import org.opendaylight.netvirt.openstack.netvirt.impl.SecurityServicesImpl;
-import org.opendaylight.netvirt.openstack.netvirt.impl.SouthboundImpl;
-import org.opendaylight.netvirt.openstack.netvirt.impl.TenantNetworkManagerImpl;
-import org.opendaylight.netvirt.openstack.netvirt.impl.VlanConfigurationCacheImpl;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronFloatingIPCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronLoadBalancerCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronLoadBalancerPoolCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronNetworkCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronPortCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSubnetCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.impl.NeutronFirewallInterface;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.impl.NeutronFirewallPolicyInterface;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.impl.NeutronFirewallRuleInterface;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.impl.NeutronFloatingIPInterface;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.impl.NeutronLoadBalancerHealthMonitorInterface;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.impl.NeutronLoadBalancerInterface;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.impl.NeutronLoadBalancerListenerInterface;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.impl.NeutronLoadBalancerPoolInterface;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.impl.NeutronLoadBalancerPoolMemberInterface;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.impl.NeutronNetworkInterface;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.impl.NeutronPortInterface;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.impl.NeutronRouterInterface;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.impl.NeutronSecurityGroupInterface;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.impl.NeutronSecurityRuleInterface;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.impl.NeutronSubnetInterface;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronFirewallAware;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronFirewallRuleAware;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronFirewallPolicyAware;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronFloatingIPAware;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronLoadBalancerAware;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronLoadBalancerPoolAware;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronLoadBalancerPoolMemberAware;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronNetworkAware;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronPortAware;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronRouterAware;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronSecurityGroupAware;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronSecurityRuleAware;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronSubnetAware;
-import org.osgi.framework.BundleActivator;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.osgi.framework.ServiceRegistration;
-import org.osgi.util.tracker.ServiceTracker;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ConfigActivator implements BundleActivator {
- private static final Logger LOG = LoggerFactory.getLogger(ConfigActivator.class);
- private List<ServiceRegistration<?>> translatorCRUDRegistrations = new ArrayList<>();
- private List<Pair<Object, ServiceRegistration>> servicesAndRegistrations = new ArrayList<>();
- private final DataBroker dataBroker;
- private boolean conntrackEnabled = false;
- private boolean intBridgeGenMac = true;
-
- public ConfigActivator(final DataBroker dataBroker) {
- this.dataBroker = dataBroker;
- }
-
- @Override
- public void start(BundleContext context) throws Exception {
- LOG.info("ConfigActivator start:");
- registerCRUDServiceProviders(context);
-
- ConfigurationServiceImpl configurationService = new ConfigurationServiceImpl();
- registerService(context, new String[] {ConfigurationService.class.getName()},
- null, configurationService);
-
- BridgeConfigurationManagerImpl bridgeConfigurationManager = new BridgeConfigurationManagerImpl(intBridgeGenMac);
- registerService(context, new String[] {BridgeConfigurationManager.class.getName()},
- null, bridgeConfigurationManager);
-
- final TenantNetworkManagerImpl tenantNetworkManager = new TenantNetworkManagerImpl();
- registerService(context, new String[] {TenantNetworkManager.class.getName()},
- null, tenantNetworkManager);
-
- VlanConfigurationCacheImpl vlanConfigurationCache = new VlanConfigurationCacheImpl();
- registerService(context, new String[] {VlanConfigurationCache.class.getName()},
- null, vlanConfigurationCache);
-
- FloatingIPHandler floatingIPHandler = new FloatingIPHandler();
- registerAbstractHandlerService(context, new Class[] {INeutronFloatingIPAware.class},
- AbstractEvent.HandlerType.NEUTRON_FLOATING_IP, floatingIPHandler);
-
- final NetworkHandler networkHandler = new NetworkHandler();
- registerAbstractHandlerService(context, new Class[] {INeutronNetworkAware.class},
- AbstractEvent.HandlerType.NEUTRON_NETWORK, networkHandler);
-
- SubnetHandler subnetHandler = new SubnetHandler();
- registerAbstractHandlerService(context, new Class[] {INeutronSubnetAware.class},
- AbstractEvent.HandlerType.NEUTRON_SUBNET, subnetHandler);
-
- PortHandler portHandler = new PortHandler();
- registerAbstractHandlerService(context, new Class[] {INeutronPortAware.class},
- AbstractEvent.HandlerType.NEUTRON_PORT, portHandler);
-
- RouterHandler routerHandler = new RouterHandler();
- registerAbstractHandlerService(context, new Class[] {INeutronRouterAware.class},
- AbstractEvent.HandlerType.NEUTRON_ROUTER, routerHandler);
-
- SouthboundHandler southboundHandler = new SouthboundHandler();
- registerAbstractHandlerService(context, new Class[] {OvsdbInventoryListener.class, NodeCacheListener.class},
- AbstractEvent.HandlerType.SOUTHBOUND, southboundHandler);
-
- final LBaaSHandler lBaaSHandler = new LBaaSHandler();
- registerAbstractHandlerService(context, new Class[] {INeutronLoadBalancerAware.class, NodeCacheListener.class},
- AbstractEvent.HandlerType.NEUTRON_LOAD_BALANCER, lBaaSHandler);
-
- final LBaaSPoolHandler lBaaSPoolHandler = new LBaaSPoolHandler();
- registerAbstractHandlerService(context, new Class[] {INeutronLoadBalancerPoolAware.class},
- AbstractEvent.HandlerType.NEUTRON_LOAD_BALANCER_POOL, lBaaSPoolHandler);
-
- final LBaaSPoolMemberHandler lBaaSPoolMemberHandler = new LBaaSPoolMemberHandler();
- registerAbstractHandlerService(context, new Class[] {INeutronLoadBalancerPoolMemberAware.class},
- AbstractEvent.HandlerType.NEUTRON_LOAD_BALANCER_POOL_MEMBER, lBaaSPoolMemberHandler);
-
- PortSecurityHandler portSecurityHandler = new PortSecurityHandler();
- registerAbstractHandlerService(context,
- new Class[] {INeutronSecurityRuleAware.class, INeutronSecurityGroupAware.class},
- AbstractEvent.HandlerType.NEUTRON_PORT_SECURITY, portSecurityHandler);
-
- final SecurityServicesImpl securityServices = new SecurityServicesImpl(conntrackEnabled);
- registerService(context,
- new String[]{SecurityServicesManager.class.getName()}, null, securityServices);
-
- final SecurityGroupCacheManger securityGroupCacheManger = new SecurityGroupCacheManagerImpl();
- registerService(context,
- new String[]{SecurityGroupCacheManger.class.getName()}, null, securityGroupCacheManger);
-
- registerService(context,
- new String[]{SecurityServicesManager.class.getName()}, null, securityServices);
-
- FWaasHandler fWaasHandler = new FWaasHandler();
- registerAbstractHandlerService(context,
- new Class[] {INeutronFirewallAware.class, INeutronFirewallRuleAware.class, INeutronFirewallPolicyAware.class},
- AbstractEvent.HandlerType.NEUTRON_FWAAS, fWaasHandler);
-
- ProviderNetworkManagerImpl providerNetworkManager = new ProviderNetworkManagerImpl();
- registerService(context,
- new String[]{NetworkingProviderManager.class.getName()}, null, providerNetworkManager);
-
- EventDispatcherImpl eventDispatcher = new EventDispatcherImpl();
- registerService(context,
- new String[]{EventDispatcher.class.getName()}, null, eventDispatcher);
-
- final NeutronL3Adapter neutronL3Adapter = new NeutronL3Adapter(
- new NeutronModelsDataStoreHelper(dataBroker));
- registerAbstractHandlerService(context, new Class[] {NeutronL3Adapter.class, GatewayMacResolverListener.class},
- AbstractEvent.HandlerType.NEUTRON_L3_ADAPTER, neutronL3Adapter);
-
- // TODO Why is DistributedArpService registered as an event handler without being an AbstractHandlerService?
- Dictionary<String, Object> distributedArpServiceProperties = new Hashtable<>();
- distributedArpServiceProperties.put(Constants.EVENT_HANDLER_TYPE_PROPERTY,
- AbstractEvent.HandlerType.DISTRIBUTED_ARP_SERVICE);
- final DistributedArpService distributedArpService = new DistributedArpService();
- registerService(context,
- new String[] {DistributedArpService.class.getName()},
- distributedArpServiceProperties, distributedArpService);
-
- final VLANProvider vlanProvider = new VLANProvider();
- registerService(context,
- new String[] {VLANProvider.class.getName()},
- null, vlanProvider);
-
- OpenstackRouter openstackRouter = new OpenstackRouter();
- registerService(context,
- new String[]{MultiTenantAwareRouter.class.getName()}, null, openstackRouter);
-
- Southbound southbound = new SouthboundImpl(dataBroker);
- registerService(context,
- new String[]{Southbound.class.getName()}, null, southbound);
-
- HostConfigService hostConfigService = new HostConfigService(dataBroker);
- registerService(context,
- new String[]{HostConfigService.class.getName()}, null, hostConfigService);
-
- NodeCacheManagerImpl nodeCacheManager = new NodeCacheManagerImpl();
- registerAbstractHandlerService(context, new Class[] {NodeCacheManager.class},
- AbstractEvent.HandlerType.NODE, nodeCacheManager);
-
- OvsdbInventoryServiceImpl ovsdbInventoryService = new OvsdbInventoryServiceImpl(dataBroker);
- registerService(context,
- new String[] {OvsdbInventoryService.class.getName()}, null, ovsdbInventoryService);
-
- // Call .setDependencies() starting with the last service registered
- for (int i = servicesAndRegistrations.size() - 1; i >= 0; i--) {
- Pair<Object, ServiceRegistration> serviceAndRegistration = servicesAndRegistrations.get(i);
- Object service = serviceAndRegistration.getLeft();
- ServiceRegistration<?> serviceRegistration = serviceAndRegistration.getRight();
- LOG.info("Setting dependencies on service {}/{}, {}", i, servicesAndRegistrations.size(),
- service.getClass());
- if (service instanceof ConfigInterface) {
- ((ConfigInterface) service).setDependencies(
- serviceRegistration != null ? serviceRegistration.getReference() : null);
- LOG.info("Dependencies set");
- } else {
- LOG.warn("Service isn't a ConfigInterface");
- }
- }
-
- // TODO check if services are already available and setDependencies
- // addingService may not be called if the service is already available when the ServiceTracker
- // is started
- trackService(context, INeutronNetworkCRUD.class, tenantNetworkManager, networkHandler, lBaaSHandler,
- lBaaSPoolHandler, lBaaSPoolMemberHandler, neutronL3Adapter, distributedArpService, vlanProvider, southboundHandler);
- trackService(context, INeutronSubnetCRUD.class, lBaaSHandler, lBaaSPoolHandler, lBaaSPoolMemberHandler,
- securityServices, neutronL3Adapter);
- trackService(context, INeutronPortCRUD.class, tenantNetworkManager, lBaaSHandler, lBaaSPoolHandler,
- lBaaSPoolMemberHandler, securityServices, neutronL3Adapter, distributedArpService, portHandler, vlanProvider);
- trackService(context, INeutronFloatingIPCRUD.class, neutronL3Adapter);
- trackService(context, INeutronLoadBalancerCRUD.class, lBaaSHandler, lBaaSPoolHandler, lBaaSPoolMemberHandler);
- trackService(context, INeutronLoadBalancerPoolCRUD.class, lBaaSHandler, lBaaSPoolMemberHandler);
- trackService(context, LoadBalancerProvider.class, lBaaSHandler, lBaaSPoolHandler, lBaaSPoolMemberHandler);
- trackService(context, L2ForwardingProvider.class, southboundHandler);
- trackService(context, ArpProvider.class, neutronL3Adapter, distributedArpService);
- trackService(context, VLANProvider.class, neutronL3Adapter, vlanProvider);
- trackService(context, InboundNatProvider.class, neutronL3Adapter);
- trackService(context, OutboundNatProvider.class, neutronL3Adapter);
- trackService(context, VlanResponderProvider.class, vlanProvider);
- trackService(context, RoutingProvider.class, neutronL3Adapter);
- trackService(context, L3ForwardingProvider.class, neutronL3Adapter);
- trackService(context, GatewayMacResolver.class, neutronL3Adapter);
- trackService(context, IngressAclProvider.class, securityServices);
- trackService(context, EgressAclProvider.class, securityServices);
- trackService(context, IcmpEchoProvider.class, neutronL3Adapter);
-
- // We no longer need to track the services, avoid keeping references around
- servicesAndRegistrations.clear();
- }
-
- private void registerCRUDServiceProviders(BundleContext context) {
- LOG.debug("Registering CRUD service providers");
- NeutronRouterInterface.registerNewInterface(context, dataBroker, translatorCRUDRegistrations);
- NeutronPortInterface.registerNewInterface(context, dataBroker, translatorCRUDRegistrations);
- NeutronSubnetInterface.registerNewInterface(context, dataBroker, translatorCRUDRegistrations);
- NeutronNetworkInterface.registerNewInterface(context, dataBroker, translatorCRUDRegistrations);
- NeutronSecurityGroupInterface.registerNewInterface(context, dataBroker, translatorCRUDRegistrations);
- NeutronSecurityRuleInterface.registerNewInterface(context, dataBroker, translatorCRUDRegistrations);
- NeutronFirewallInterface.registerNewInterface(context, dataBroker, translatorCRUDRegistrations);
- NeutronFirewallPolicyInterface.registerNewInterface(context, dataBroker, translatorCRUDRegistrations);
- NeutronFirewallRuleInterface.registerNewInterface(context, dataBroker, translatorCRUDRegistrations);
- NeutronLoadBalancerInterface.registerNewInterface(context, dataBroker, translatorCRUDRegistrations);
- NeutronLoadBalancerPoolInterface.registerNewInterface(context, dataBroker, translatorCRUDRegistrations);
- NeutronLoadBalancerListenerInterface.registerNewInterface(context, dataBroker, translatorCRUDRegistrations);
- NeutronLoadBalancerHealthMonitorInterface.registerNewInterface(context, dataBroker, translatorCRUDRegistrations);
- NeutronLoadBalancerPoolMemberInterface.registerNewInterface(context, dataBroker, translatorCRUDRegistrations);
- NeutronFloatingIPInterface.registerNewInterface(context, dataBroker, translatorCRUDRegistrations);
- }
-
- private void trackService(BundleContext context, final Class<?> clazz, final ConfigInterface... dependents) {
- @SuppressWarnings("unchecked")
- ServiceTracker tracker = new ServiceTracker(context, clazz, null) {
- @Override
- public Object addingService(ServiceReference reference) {
- LOG.info("addingService " + clazz.getName());
- Object service = context.getService(reference);
- if (service != null) {
- for (ConfigInterface dependent : dependents) {
- dependent.setDependencies(service);
- }
- }
- return service;
- }
- };
- tracker.open();
- }
-
- private void registerAbstractHandlerService(BundleContext context, Class[] interfaces,
- AbstractEvent.HandlerType handlerType, AbstractHandler handler) {
- Dictionary<String, Object> properties = new Hashtable<>();
- properties.put(Constants.EVENT_HANDLER_TYPE_PROPERTY, handlerType);
- String[] interfaceNames = new String[interfaces.length + 1];
- for (int i = 0; i < interfaces.length; i++) {
- interfaceNames[i] = interfaces[i].getName();
- }
- interfaceNames[interfaces.length] = AbstractHandler.class.getName();
- registerService(context, interfaceNames, properties, handler);
- }
-
-
- @Override
- public void stop(BundleContext context) throws Exception {
- LOG.info("ConfigActivator stop");
- // ServiceTrackers and services are already released when bundle stops,
- // so we don't need to close the trackers or unregister the services
- }
-
- private ServiceRegistration<?> registerService(BundleContext bundleContext, String[] interfaces,
- Dictionary<String, Object> properties, Object impl) {
- ServiceRegistration serviceRegistration = bundleContext.registerService(interfaces, impl, properties);
- if (serviceRegistration == null) {
- LOG.warn("Service registration for {} failed to return a ServiceRegistration instance", impl.getClass());
- }
- servicesAndRegistrations.add(Pair.of(impl, serviceRegistration));
- return serviceRegistration;
- }
-
- public void setConntrackEnabled(boolean conntrackEnabled) {
- this.conntrackEnabled = conntrackEnabled;
- }
-
- public void setIntBridgeGenMac(boolean intBridgeGenMac) {
- this.intBridgeGenMac = intBridgeGenMac;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt;
-
-import org.osgi.framework.ServiceReference;
-
-public interface ConfigInterface {
- void setDependencies(ServiceReference serviceReference);
- void setDependencies(Object impl);
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt;
-
-import java.net.HttpURLConnection;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronFirewall;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronFirewallPolicyAware;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronFirewallPolicy;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronFirewallRule;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronFirewallAware;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronFirewallRuleAware;
-import org.opendaylight.netvirt.openstack.netvirt.api.EventDispatcher;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Handle requests for OpenStack Neutron v2.0 Port Firewall API calls.
- */
-public class FWaasHandler extends AbstractHandler
- implements INeutronFirewallAware, INeutronFirewallRuleAware,
- INeutronFirewallPolicyAware, ConfigInterface {
-
- private static final Logger LOG = LoggerFactory.getLogger(FWaasHandler.class);
-
- /**
- * Invoked when a Firewall Rules creation is requested
- * to indicate if the specified Rule can be created.
- *
- * @param neutronFirewall An instance of proposed new Neutron Firewall object.
- * @return HttpURLConnection A HTTP status code to the creation request.
- */
- @Override
- public int canCreateNeutronFirewall(NeutronFirewall neutronFirewall) {
- return HttpURLConnection.HTTP_CREATED;
- }
-
- @Override
- public void neutronFirewallCreated(NeutronFirewall neutronFirewall) {
- LOG.debug("Neutron Firewall created by Neutron: {}", neutronFirewall);
-
- int result = canCreateNeutronFirewall(neutronFirewall);
- if (result != HttpURLConnection.HTTP_CREATED) {
- LOG.error("Neutron Firewall creation failed: {} ", result);
- }
- }
-
- @Override
- public int canUpdateNeutronFirewall(NeutronFirewall delta, NeutronFirewall original) {
- return HttpURLConnection.HTTP_OK;
- }
-
- @Override
- public void neutronFirewallUpdated(NeutronFirewall neutronFirewall) {
- LOG.debug("NeutronFirewall updated from Neutron: {}", neutronFirewall);
- }
-
- @Override
- public int canDeleteNeutronFirewall(NeutronFirewall neutronFirewall) {
- return HttpURLConnection.HTTP_OK;
- }
-
- @Override
- public void neutronFirewallDeleted(NeutronFirewall neutronFirewall) {
- //TODO: Trigger flowmod removals
- int result = canDeleteNeutronFirewall(neutronFirewall);
- if (result != HttpURLConnection.HTTP_OK) {
- LOG.error(" delete Neutron Firewall validation failed for result - {} ", result);
- }
- }
-
- /**
- * Invoked when a Firewall Rule creation is requested
- * to indicate if the specified Rule can be created.
- *
- * @param neutronFirewallRule An instance of proposed new Neutron Firewall Rule object.
- * @return HttpURLConnection A HTTP status code to the creation request.
- */
- @Override
- public int canCreateNeutronFirewallRule(NeutronFirewallRule neutronFirewallRule) {
- return HttpURLConnection.HTTP_CREATED;
- }
-
- @Override
- public void neutronFirewallRuleCreated(NeutronFirewallRule neutronFirewallRule) {
- LOG.debug("NeutronFirewallRule created by Neutron: {}", neutronFirewallRule);
-
- int result = canCreateNeutronFirewallRule(neutronFirewallRule);
- if (result != HttpURLConnection.HTTP_CREATED) {
- LOG.error("Neutron Firewall Rule creation failed {} ", result);
- }
- }
-
- @Override
- public int canUpdateNeutronFirewallRule(NeutronFirewallRule delta, NeutronFirewallRule original) {
- return HttpURLConnection.HTTP_OK;
- }
-
- @Override
- public void neutronFirewallRuleUpdated(NeutronFirewallRule neutronFirewallRule) {
- LOG.debug("Neutron Firewall Rule updated from Neutron: {}", neutronFirewallRule);
- }
-
- @Override
- public int canDeleteNeutronFirewallRule(NeutronFirewallRule neutronFirewallRule) {
- return HttpURLConnection.HTTP_OK;
- }
-
- @Override
- public void neutronFirewallRuleDeleted(NeutronFirewallRule neutronFirewallRule) {
- int result = canDeleteNeutronFirewallRule(neutronFirewallRule);
- if (result != HttpURLConnection.HTTP_OK) {
- LOG.error(" delete Neutron Firewall Rule validation failed for result - {} ", result);
- }
- }
-
- /**
- * Invoked when a Firewall Policy creation is requested
- * to indicate if the specified Rule can be created.
- *
- * @param neutronFirewallPolicy An instance of proposed new Neutron Firewall Policy object.
- * @return HttpURLConnection A HTTP status code to the creation request.
- */
- @Override
- public int canCreateNeutronFirewallPolicy(NeutronFirewallPolicy neutronFirewallPolicy) {
- return HttpURLConnection.HTTP_CREATED;
- }
-
- @Override
- public void neutronFirewallPolicyCreated(NeutronFirewallPolicy neutronFirewallPolicy) {
- LOG.debug("Neutron Firewall Policy created by Neutron: {}", neutronFirewallPolicy);
-
- int result = canCreateNeutronFirewallPolicy(neutronFirewallPolicy);
- if (result != HttpURLConnection.HTTP_CREATED) {
- LOG.debug("Neutron Firewall Policy creation failed: {} ", result);
- }
- }
-
- @Override
- public int canUpdateNeutronFirewallPolicy(NeutronFirewallPolicy delta, NeutronFirewallPolicy original) {
- return HttpURLConnection.HTTP_OK;
- }
-
- @Override
- public void neutronFirewallPolicyUpdated(NeutronFirewallPolicy neutronFirewallPolicy) {
- LOG.debug("Neutron Firewall Policy updated from Neutron: {}", neutronFirewallPolicy);
- }
-
- @Override
- public int canDeleteNeutronFirewallPolicy(NeutronFirewallPolicy neutronFirewallPolicy) {
- return HttpURLConnection.HTTP_OK;
- }
-
- @Override
- public void neutronFirewallPolicyDeleted(NeutronFirewallPolicy neutronFirewallPolicy) {
- int result = canDeleteNeutronFirewallPolicy(neutronFirewallPolicy);
- if (result != HttpURLConnection.HTTP_OK) {
- LOG.error(" delete Neutron Firewall Policy validation failed for result - {} ", result);
- }
- }
-
- /**
- * Process the event.
- *
- * @param abstractEvent new FWaas Event@see EventDispatcher
- */
- @Override
- public void processEvent(AbstractEvent abstractEvent) {
- if (!(abstractEvent instanceof NorthboundEvent)) {
- LOG.error("Unable to process abstract event {}", abstractEvent);
- return;
- }
- NorthboundEvent ev = (NorthboundEvent) abstractEvent;
- switch (ev.getAction()) {
- // TODO: add handling of events here, once callbacks do something
- // other than logging.
- default:
- LOG.warn("Unable to process event action {}", ev.getAction());
- break;
- }
- }
-
- @Override
- public void setDependencies(ServiceReference serviceReference) {
- eventDispatcher =
- (EventDispatcher) ServiceHelper.getGlobalInstance(EventDispatcher.class, this);
- eventDispatcher.eventHandlerAdded(serviceReference, this);
- }
-
- @Override
- public void setDependencies(Object impl) {}
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt;
-
-import java.net.HttpURLConnection;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronFloatingIP;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronFloatingIPAware;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.EventDispatcher;
-import org.opendaylight.netvirt.openstack.netvirt.impl.NeutronL3Adapter;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Handle requests for Neutron Floating IP.
- */
-public class FloatingIPHandler extends AbstractHandler
- implements INeutronFloatingIPAware, ConfigInterface {
-
- private static final Logger LOG = LoggerFactory.getLogger(FloatingIPHandler.class);
-
- // The implementation for each of these services is resolved by the OSGi Service Manager
- private volatile NeutronL3Adapter neutronL3Adapter;
-
- /**
- * Services provide this interface method to indicate if the specified floatingIP can be created
- *
- * @param floatingIP
- * instance of proposed new Neutron FloatingIP object
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the create operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- @Override
- public int canCreateFloatingIP(NeutronFloatingIP floatingIP) {
- return HttpURLConnection.HTTP_OK;
- }
-
-
- /**
- * Services provide this interface method for taking action after a floatingIP has been created
- *
- * @param floatingIP
- * instance of new Neutron FloatingIP object
- */
- @Override
- public void neutronFloatingIPCreated(NeutronFloatingIP floatingIP) {
- enqueueEvent(new NorthboundEvent(floatingIP, Action.ADD));
- }
-
- /**
- * Services provide this interface method to indicate if the specified floatingIP can be changed using the specified
- * delta
- *
- * @param delta
- * updates to the floatingIP object using patch semantics
- * @param original
- * instance of the Neutron FloatingIP object to be updated
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the update operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- @Override
- public int canUpdateFloatingIP(NeutronFloatingIP delta, NeutronFloatingIP original) {
- return HttpURLConnection.HTTP_OK;
- }
-
- /**
- * Services provide this interface method for taking action after a floatingIP has been updated
- *
- * @param floatingIP
- * instance of modified Neutron FloatingIP object
- */
- @Override
- public void neutronFloatingIPUpdated(NeutronFloatingIP floatingIP) {
- enqueueEvent(new NorthboundEvent(floatingIP, Action.UPDATE));
- }
-
- /**
- * Services provide this interface method to indicate if the specified floatingIP can be deleted
- *
- * @param floatingIP
- * instance of the Neutron FloatingIP object to be deleted
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the delete operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- @Override
- public int canDeleteFloatingIP(NeutronFloatingIP floatingIP) {
- return HttpURLConnection.HTTP_OK;
- }
-
- /**
- * Services provide this interface method for taking action after a floatingIP has been deleted
- *
- * @param floatingIP
- * instance of deleted Neutron FloatingIP object
- */
- @Override
- public void neutronFloatingIPDeleted(NeutronFloatingIP floatingIP) {
- enqueueEvent(new NorthboundEvent(floatingIP, Action.DELETE));
- }
-
- /**
- * Process the event.
- *
- * @param abstractEvent the {@link AbstractEvent} event to be handled.
- * @see EventDispatcher
- */
- @Override
- public void processEvent(AbstractEvent abstractEvent) {
- if (!(abstractEvent instanceof NorthboundEvent)) {
- LOG.error("Unable to process abstract event {}", abstractEvent);
- return;
- }
- NorthboundEvent ev = (NorthboundEvent) abstractEvent;
- switch (ev.getAction()) {
- case ADD:
- // fall through
- case DELETE:
- // fall through
- case UPDATE:
- neutronL3Adapter.handleNeutronFloatingIPEvent(ev.getNeutronFloatingIP(), ev.getAction());
- break;
- default:
- LOG.warn("Unable to process event action {}", ev.getAction());
- break;
- }
- }
-
- @Override
- public void setDependencies(ServiceReference serviceReference) {
- eventDispatcher =
- (EventDispatcher) ServiceHelper.getGlobalInstance(EventDispatcher.class, this);
- neutronL3Adapter =
- (NeutronL3Adapter) ServiceHelper.getGlobalInstance(NeutronL3Adapter.class, this);
- eventDispatcher.eventHandlerAdded(serviceReference, this);
- }
-
- @Override
- public void setDependencies(Object impl) {}
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 SDN Hub, LLC. 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.netvirt.openstack.netvirt;
-
-import java.net.HttpURLConnection;
-import java.util.List;
-import java.util.Map;
-
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheManager;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancerPoolMember;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronLoadBalancerPoolCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronNetworkCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronLoadBalancerAware;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancer;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancerPool;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronLoadBalancerCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronPortCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSubnetCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.EventDispatcher;
-import org.opendaylight.netvirt.openstack.netvirt.api.LoadBalancerConfiguration;
-import org.opendaylight.netvirt.openstack.netvirt.api.LoadBalancerProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheListener;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Preconditions;
-
-/**
- * Handle requests for OpenStack Neutron v2.0 LBaaS API calls for /v2.0/loadbalancers.
- */
-
-//TODO: Implement INeutronLoadBalancerHealthMonitorAware, INeutronLoadBalancerListenerAware, INeutronLoadBalancerPoolMemberAware,
-
-public class LBaaSHandler extends AbstractHandler
- implements INeutronLoadBalancerAware, ConfigInterface, NodeCacheListener {
- private static final Logger LOG = LoggerFactory.getLogger(LBaaSHandler.class);
-
- // The implementation for each of these services is resolved by the OSGi Service Manager
- private volatile INeutronLoadBalancerCRUD neutronLBCache;
- private volatile INeutronLoadBalancerPoolCRUD neutronLBPoolCache;
- private volatile INeutronPortCRUD neutronPortCache;
- private volatile INeutronNetworkCRUD neutronNetworkCache;
- private volatile INeutronSubnetCRUD neutronSubnetCache;
- private volatile LoadBalancerProvider loadBalancerProvider;
- private volatile NodeCacheManager nodeCacheManager;
-
- @Override
- public int canCreateNeutronLoadBalancer(NeutronLoadBalancer neutronLB) {
- //Always allowed and not wait for pool and members to be created
- return HttpURLConnection.HTTP_OK;
- }
-
- @Override
- public void neutronLoadBalancerCreated(NeutronLoadBalancer neutronLB) {
- LOG.debug("Neutron LB Creation : {}", neutronLB.toString());
- enqueueEvent(new NorthboundEvent(neutronLB, Action.ADD));
- }
-
- /**
- * Assuming that the pool information is fully populated before this call is made,
- * we go with creating the LoadBalancerConfiguration object for this call with
- * all information that is necessary to insert flow_mods
- */
- private void doNeutronLoadBalancerCreate(NeutronLoadBalancer neutronLB) {
- Preconditions.checkNotNull(loadBalancerProvider);
- LoadBalancerConfiguration lbConfig = extractLBConfiguration(neutronLB);
- final List<Node> nodes = nodeCacheManager.getBridgeNodes();
-
- if (!lbConfig.isValid()) {
- LOG.debug("Neutron LB pool configuration invalid for {} ", lbConfig.getName());
- } else if (nodes.isEmpty()) {
- LOG.debug("Noop with LB {} creation because no nodes available.", lbConfig.getName());
- } else {
- for (Node node : nodes) {
- loadBalancerProvider.programLoadBalancerRules(node, lbConfig, Action.ADD);
- }
- }
- }
-
- @Override
- public int canUpdateNeutronLoadBalancer(NeutronLoadBalancer delta, NeutronLoadBalancer original) {
- //Update allowed anytime, even when the LB has no active pool yet
- return HttpURLConnection.HTTP_OK;
- }
-
- @Override
- public void neutronLoadBalancerUpdated(NeutronLoadBalancer neutronLB) {
- LOG.debug("Neutron LB Update : {}", neutronLB.toString());
- enqueueEvent(new NorthboundEvent(neutronLB, Action.UPDATE));
- }
-
- @Override
- public int canDeleteNeutronLoadBalancer(NeutronLoadBalancer neutronLB) {
- //Always allowed and not wait for pool to stop using it
- return HttpURLConnection.HTTP_OK;
- }
-
- @Override
- public void neutronLoadBalancerDeleted(NeutronLoadBalancer neutronLB) {
- LOG.debug("Neutron LB Deletion : {}", neutronLB.toString());
- enqueueEvent(new NorthboundEvent(neutronLB, Action.DELETE));
- }
-
- private void doNeutronLoadBalancerDelete(NeutronLoadBalancer neutronLB) {
- Preconditions.checkNotNull(loadBalancerProvider);
- LoadBalancerConfiguration lbConfig = extractLBConfiguration(neutronLB);
- final List<Node> nodes = nodeCacheManager.getBridgeNodes();
-
- if (!lbConfig.isValid()) {
- LOG.debug("Neutron LB pool configuration invalid for {} ", lbConfig.getName());
- } else if (nodes.isEmpty()) {
- LOG.debug("Noop with LB {} deletion because no nodes available.", lbConfig.getName());
- } else {
- for (Node node : nodes) {
- loadBalancerProvider.programLoadBalancerRules(node, lbConfig, Action.DELETE);
- }
- }
- }
-
- /**
- * Process the event.
- *
- * @param abstractEvent the {@link AbstractEvent} event to be handled.
- * @see EventDispatcher
- */
- @Override
- public void processEvent(AbstractEvent abstractEvent) {
- LOG.debug("Processing Loadbalancer event {}", abstractEvent);
- if (!(abstractEvent instanceof NorthboundEvent)) {
- LOG.error("Unable to process abstract event {}", abstractEvent);
- return;
- }
- NorthboundEvent ev = (NorthboundEvent) abstractEvent;
- switch (ev.getAction()) {
- case ADD:
- doNeutronLoadBalancerCreate(ev.getLoadBalancer());
- break;
- case DELETE:
- doNeutronLoadBalancerDelete(ev.getLoadBalancer());
- break;
- case UPDATE:
- /**
- * Currently member update requires delete and re-adding
- * Also, weights and weight updates are not supported
- */
- doNeutronLoadBalancerDelete(ev.getLoadBalancer());
- doNeutronLoadBalancerCreate(ev.getLoadBalancer());
- break;
- default:
- LOG.warn("Unable to process event action {}", ev.getAction());
- break;
- }
- }
-
- /**
- * Useful utility for extracting the loadbalancer instance
- * configuration from the neutron LB cache
- * @param neutronLB neutron load balancer object
- * @return returns load balancer configuration
- */
- public LoadBalancerConfiguration extractLBConfiguration(NeutronLoadBalancer neutronLB) {
- String loadBalancerName = neutronLB.getLoadBalancerName();
- String loadBalancerVip = neutronLB.getLoadBalancerVipAddress();
- String loadBalancerSubnetID = neutronLB.getLoadBalancerVipSubnetID();
-
- LoadBalancerConfiguration lbConfig = new LoadBalancerConfiguration(loadBalancerName, loadBalancerVip);
- Map.Entry<String,String> providerInfo =
- NeutronCacheUtils.getProviderInformation(neutronNetworkCache, neutronSubnetCache, loadBalancerSubnetID);
- if (providerInfo != null) {
- lbConfig.setProviderNetworkType(providerInfo.getKey());
- lbConfig.setProviderSegmentationId(providerInfo.getValue());
- }
- lbConfig.setVmac(NeutronCacheUtils.getMacAddress(neutronPortCache, loadBalancerSubnetID, loadBalancerVip));
-
- for (NeutronLoadBalancerPool neutronLBPool: neutronLBPoolCache.getAllNeutronLoadBalancerPools()) {
- List<NeutronLoadBalancerPoolMember> members = neutronLBPool.getLoadBalancerPoolMembers();
- String memberProtocol = neutronLBPool.getLoadBalancerPoolProtocol();
- if (memberProtocol == null) {
- continue;
- }
-
- if (!(memberProtocol.equalsIgnoreCase(LoadBalancerConfiguration.PROTOCOL_TCP) ||
- memberProtocol.equalsIgnoreCase(LoadBalancerConfiguration.PROTOCOL_HTTP) ||
- memberProtocol.equalsIgnoreCase(LoadBalancerConfiguration.PROTOCOL_HTTPS))) {
- continue;
- }
- for (NeutronLoadBalancerPoolMember neutronLBPoolMember: members) {
- Boolean memberAdminStateIsUp = neutronLBPoolMember.getPoolMemberAdminStateIsUp();
- String memberSubnetID = neutronLBPoolMember.getPoolMemberSubnetID();
- if (memberSubnetID != null && memberAdminStateIsUp != null &&
- memberSubnetID.equals(loadBalancerSubnetID) && memberAdminStateIsUp) {
- String memberID = neutronLBPoolMember.getID();
- String memberIP = neutronLBPoolMember.getPoolMemberAddress();
- Integer memberPort = neutronLBPoolMember.getPoolMemberProtoPort();
- if (memberID == null || memberIP == null || memberPort == null) {
- LOG.debug("Neutron LB pool member details incomplete: {}", neutronLBPoolMember);
- continue;
- }
- String memberMAC = NeutronCacheUtils.getMacAddress(neutronPortCache, memberSubnetID, memberIP);
- if (memberMAC == null) {
- continue;
- }
- lbConfig.addMember(memberID, memberIP, memberMAC, memberProtocol, memberPort);
- }
- }
- }
- return lbConfig;
- }
-
- /**
- * On the addition of a new node, we iterate through all existing loadbalancer
- * instances and program the node for all of them. It is sufficient to do that only
- * when a node is added, and only for the LB instances (and not individual members).
- */
- @Override
- public void notifyNode(Node node, Action type) {
- LOG.trace("notifyNode: Node {} update {} from Controller's inventory Service", node, type);
- Preconditions.checkNotNull(loadBalancerProvider);
-
- for (NeutronLoadBalancer neutronLB: neutronLBCache.getAllNeutronLoadBalancers()) {
- LoadBalancerConfiguration lbConfig = extractLBConfiguration(neutronLB);
- if (!lbConfig.isValid()) {
- LOG.debug("Neutron LB configuration invalid for {} ", lbConfig.getName());
- } else {
- if (type.equals(Action.ADD)) {
- loadBalancerProvider.programLoadBalancerRules(node, lbConfig, Action.ADD);
-
- /* When node disappears, we do nothing for now. Making a call to
- * loadBalancerProvider.programLoadBalancerRules(node, lbConfig, Action.DELETE)
- * can lead to TransactionCommitFailedException. Similarly when node is changed,
- * because of remove followed by add, we do nothing.
- */
-
- //(type.equals(UpdateType.REMOVED) || type.equals(UpdateType.CHANGED))
- }
- }
- }
- }
-
- @Override
- public void setDependencies(ServiceReference serviceReference) {
- loadBalancerProvider =
- (LoadBalancerProvider) ServiceHelper.getGlobalInstance(LoadBalancerProvider.class, this);
- nodeCacheManager =
- (NodeCacheManager) ServiceHelper.getGlobalInstance(NodeCacheManager.class, this);
- nodeCacheManager.cacheListenerAdded(serviceReference, this);
- eventDispatcher =
- (EventDispatcher) ServiceHelper.getGlobalInstance(EventDispatcher.class, this);
- eventDispatcher.eventHandlerAdded(serviceReference, this);
- }
-
- @Override
- public void setDependencies(Object impl) {
- if (impl instanceof INeutronNetworkCRUD) {
- neutronNetworkCache = (INeutronNetworkCRUD)impl;
- } else if (impl instanceof INeutronPortCRUD) {
- neutronPortCache = (INeutronPortCRUD)impl;
- } else if (impl instanceof INeutronSubnetCRUD) {
- neutronSubnetCache = (INeutronSubnetCRUD)impl;
- } else if (impl instanceof INeutronLoadBalancerCRUD) {
- neutronLBCache = (INeutronLoadBalancerCRUD)impl;
- } else if (impl instanceof INeutronLoadBalancerPoolCRUD) {
- neutronLBPoolCache = (INeutronLoadBalancerPoolCRUD)impl;
- } else if (impl instanceof LoadBalancerProvider) {
- loadBalancerProvider = (LoadBalancerProvider)impl;
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 SDN Hub, LLC. 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.netvirt.openstack.netvirt;
-
-import com.google.common.base.Preconditions;
-import java.net.HttpURLConnection;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.EventDispatcher;
-import org.opendaylight.netvirt.openstack.netvirt.api.LoadBalancerConfiguration;
-import org.opendaylight.netvirt.openstack.netvirt.api.LoadBalancerProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheManager;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancer;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancerPool;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancerPoolMember;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronLoadBalancerCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronNetworkCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronPortCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSubnetCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronLoadBalancerPoolAware;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Handle requests for OpenStack Neutron v2.0 LBaaS API calls for
- * /v2.0/pools . It is possible that each pool spans multiple subnets.
- * In that case, the user should be creating a separate VIP for each subnet.
- */
-
-public class LBaaSPoolHandler extends AbstractHandler
- implements INeutronLoadBalancerPoolAware, ConfigInterface {
-
- private static final Logger LOG = LoggerFactory.getLogger(LBaaSPoolHandler.class);
-
- // The implementation for each of these services is resolved by the OSGi Service Manager
- private volatile INeutronLoadBalancerCRUD neutronLBCache;
- private volatile INeutronPortCRUD neutronPortCache;
- private volatile INeutronNetworkCRUD neutronNetworkCache;
- private volatile INeutronSubnetCRUD neutronSubnetCache;
- private volatile LoadBalancerProvider loadBalancerProvider;
- private volatile NodeCacheManager nodeCacheManager;
-
- @Override
- public int canCreateNeutronLoadBalancerPool(NeutronLoadBalancerPool neutronLBPool) {
- String poolProtocol = neutronLBPool.getLoadBalancerPoolProtocol();
- if (poolProtocol == null) {
- return HttpURLConnection.HTTP_BAD_REQUEST;
- } else if (!(poolProtocol.equalsIgnoreCase(LoadBalancerConfiguration.PROTOCOL_TCP) ||
- poolProtocol.equalsIgnoreCase(LoadBalancerConfiguration.PROTOCOL_HTTP) ||
- poolProtocol.equalsIgnoreCase(LoadBalancerConfiguration.PROTOCOL_HTTPS))) {
- return HttpURLConnection.HTTP_NOT_ACCEPTABLE;
- } else {
- return HttpURLConnection.HTTP_OK;
- }
- }
-
- @Override
- public void neutronLoadBalancerPoolCreated(NeutronLoadBalancerPool neutronLBPool) {
- LOG.debug("Neutron LB Pool Creation : {}", neutronLBPool.toString());
- enqueueEvent(new NorthboundEvent(neutronLBPool, Action.ADD));
- }
-
- /**
- * Assuming that the pool information is fully populated before this call is made,
- * we go with creating the LoadBalancerConfiguration object for this call with
- * all information that is necessary to insert flow_mods
- */
- private void doNeutronLoadBalancerPoolCreate(NeutronLoadBalancerPool neutronLBPool) {
- Preconditions.checkNotNull(loadBalancerProvider);
- List<LoadBalancerConfiguration> lbConfigList = extractLBConfiguration(neutronLBPool);
- final List<Node> nodes = nodeCacheManager.getBridgeNodes();
- if (lbConfigList == null) {
- LOG.debug("Neutron LB configuration invalid for pool {} ", neutronLBPool.getID());
- } else if (lbConfigList.size() == 0) {
- LOG.debug("No Neutron LB VIP not created yet for pool {} ", neutronLBPool.getID());
- } else if (nodes.isEmpty()) {
- LOG.debug("Noop with LB pool {} creation because no nodes available.", neutronLBPool.getID());
- } else {
- for (LoadBalancerConfiguration lbConfig: lbConfigList) {
- if (!lbConfig.isValid()) {
- LOG.debug("Neutron LB pool configuration invalid for {} ", lbConfig.getName());
- } else {
- for (Node node : nodes) {
- loadBalancerProvider.programLoadBalancerRules(node, lbConfig, Action.ADD);
- }
- }
- }
- }
- }
-
- @Override
- public int canUpdateNeutronLoadBalancerPool(NeutronLoadBalancerPool delta, NeutronLoadBalancerPool original) {
- return HttpURLConnection.HTTP_NOT_IMPLEMENTED;
- }
-
- @Override
- public void neutronLoadBalancerPoolUpdated(NeutronLoadBalancerPool neutronLBPool) {
- LOG.debug("Neutron LB Pool Update : {}", neutronLBPool.toString());
- enqueueEvent(new NorthboundEvent(neutronLBPool, Action.UPDATE));
- }
-
- @Override
- public int canDeleteNeutronLoadBalancerPool(NeutronLoadBalancerPool neutronLBPool) {
- String poolProtocol = neutronLBPool.getLoadBalancerPoolProtocol();
- if (poolProtocol == null) {
- return HttpURLConnection.HTTP_BAD_REQUEST;
- } else if (!(poolProtocol.equalsIgnoreCase(LoadBalancerConfiguration.PROTOCOL_TCP) ||
- poolProtocol.equalsIgnoreCase(LoadBalancerConfiguration.PROTOCOL_HTTP) ||
- poolProtocol.equalsIgnoreCase(LoadBalancerConfiguration.PROTOCOL_HTTPS))) {
- return HttpURLConnection.HTTP_NOT_ACCEPTABLE;
- } else {
- return HttpURLConnection.HTTP_OK;
- }
- }
-
- @Override
- public void neutronLoadBalancerPoolDeleted(NeutronLoadBalancerPool neutronLBPool) {
- LOG.debug("Neutron LB Pool Deletion : {}", neutronLBPool.toString());
- enqueueEvent(new NorthboundEvent(neutronLBPool, Action.DELETE));
- }
-
- private void doNeutronLoadBalancerPoolDelete(NeutronLoadBalancerPool neutronLBPool) {
- Preconditions.checkNotNull(loadBalancerProvider);
-
- List<LoadBalancerConfiguration> lbConfigList = extractLBConfiguration(neutronLBPool);
- final List<Node> nodes = nodeCacheManager.getBridgeNodes();
- if (lbConfigList == null) {
- LOG.debug("Neutron LB configuration invalid for pool {} ", neutronLBPool.getID());
- } else if (lbConfigList.size() == 0) {
- LOG.debug("No Neutron LB VIP not created yet for pool {} ", neutronLBPool.getID());
- } else if (nodes.isEmpty()) {
- LOG.debug("Noop with LB pool {} deletion because no nodes available.", neutronLBPool.getID());
- } else {
- for (LoadBalancerConfiguration lbConfig: lbConfigList) {
- if (!lbConfig.isValid()) {
- LOG.debug("Neutron LB pool configuration invalid for {} ", lbConfig.getName());
- } else {
- for (Node node : nodes) {
- loadBalancerProvider.programLoadBalancerRules(node, lbConfig, Action.DELETE);
- }
- }
- }
- }
- }
-
- /**
- * Process the event.
- *
- * @param abstractEvent the {@link AbstractEvent} event to be handled.
- * @see EventDispatcher
- */
- @Override
- public void processEvent(AbstractEvent abstractEvent) {
- LOG.debug("Processing Loadbalancer Pool event {}", abstractEvent);
- if (!(abstractEvent instanceof NorthboundEvent)) {
- LOG.error("Unable to process abstract event {}", abstractEvent);
- return;
- }
- NorthboundEvent ev = (NorthboundEvent) abstractEvent;
- switch (ev.getAction()) {
- case ADD:
- doNeutronLoadBalancerPoolCreate(ev.getLoadBalancerPool());
- break;
- case DELETE:
- doNeutronLoadBalancerPoolDelete(ev.getLoadBalancerPool());
- break;
- case UPDATE:
- /**
- * Typical upgrade involves changing algorithm. Right now
- * we do not support this flexibility. TODO
- */
- LOG.warn("Load balancer pool update is not supported");
- break;
- default:
- LOG.warn("Unable to process event action {}", ev.getAction());
- break;
- }
- }
-
- /**
- * Useful utility for extracting the loadbalancer instance. With
- * each LB pool, we allow multiple VIP and LB to be instantiated.
- * @param neutronLBPool Neutron load balancer pool object
- * @return list of loadbalancer configuration of pool members
- */
- public List<LoadBalancerConfiguration> extractLBConfiguration(NeutronLoadBalancerPool neutronLBPool) {
- String poolProtocol = neutronLBPool.getLoadBalancerPoolProtocol();
- if (poolProtocol == null) {
- return null;
- }
- if (!(poolProtocol.equalsIgnoreCase(LoadBalancerConfiguration.PROTOCOL_HTTP) ||
- poolProtocol.equalsIgnoreCase(LoadBalancerConfiguration.PROTOCOL_HTTPS))) {
- return null;
- }
-
- List<NeutronLoadBalancerPoolMember> poolMembers = neutronLBPool.getLoadBalancerPoolMembers();
- if (poolMembers.size() == 0) {
- LOG.debug("Neutron LB pool is empty: {}", neutronLBPool);
- return null;
- }
-
- List<LoadBalancerConfiguration> lbConfigList = new LinkedList<>();
-
- /* Iterate over all the Loadbalancers created so far and identify VIP
- */
- for (NeutronLoadBalancer neutronLB: neutronLBCache.getAllNeutronLoadBalancers()) {
- String loadBalancerSubnetID = neutronLB.getLoadBalancerVipSubnetID();
- String loadBalancerName = neutronLB.getLoadBalancerName();
- String loadBalancerVip = neutronLB.getLoadBalancerVipAddress();
-
- LoadBalancerConfiguration lbConfig = new LoadBalancerConfiguration(loadBalancerName, loadBalancerVip);
- Map.Entry<String,String> providerInfo = NeutronCacheUtils.getProviderInformation(neutronNetworkCache, neutronSubnetCache, loadBalancerSubnetID);
- if (providerInfo != null) {
- lbConfig.setProviderNetworkType(providerInfo.getKey());
- lbConfig.setProviderSegmentationId(providerInfo.getValue());
- }
- lbConfig.setVmac(NeutronCacheUtils.getMacAddress(neutronPortCache, loadBalancerSubnetID, loadBalancerVip));
-
- /* Iterate over all the members in this pool and find those in same
- * subnet as the VIP. Those will be included in the lbConfigList
- */
- String memberSubnetID, memberIP, memberID, memberMAC;
- Integer memberPort;
- Boolean memberAdminStateIsUp;
- for (NeutronLoadBalancerPoolMember neutronLBPoolMember: neutronLBPool.getLoadBalancerPoolMembers()) {
- memberAdminStateIsUp = neutronLBPoolMember.getPoolMemberAdminStateIsUp();
- memberSubnetID = neutronLBPoolMember.getPoolMemberSubnetID();
- if (memberSubnetID != null && memberAdminStateIsUp != null &&
- memberSubnetID.equals(loadBalancerSubnetID) && memberAdminStateIsUp) {
- memberID = neutronLBPoolMember.getID();
- memberIP = neutronLBPoolMember.getPoolMemberAddress();
- memberPort = neutronLBPoolMember.getPoolMemberProtoPort();
- if (memberID == null || memberIP == null || memberPort == null) {
- LOG.debug("Neutron LB pool member details incomplete: {}", neutronLBPoolMember);
- continue;
- }
- memberMAC = NeutronCacheUtils.getMacAddress(neutronPortCache, memberSubnetID, memberIP);
- if (memberMAC == null) {
- continue;
- }
- lbConfig.addMember(memberID, memberIP, memberMAC, poolProtocol, memberPort);
- }
- }
-
- if (lbConfig.getMembers().size() > 0) {
- lbConfigList.add(lbConfig);
- }
- }
-
- return lbConfigList;
- }
-
- @Override
- public void setDependencies(ServiceReference serviceReference) {
- loadBalancerProvider =
- (LoadBalancerProvider) ServiceHelper.getGlobalInstance(LoadBalancerProvider.class, this);
- nodeCacheManager =
- (NodeCacheManager) ServiceHelper.getGlobalInstance(NodeCacheManager.class, this);
- eventDispatcher =
- (EventDispatcher) ServiceHelper.getGlobalInstance(EventDispatcher.class, this);
- eventDispatcher.eventHandlerAdded(serviceReference, this);
- }
-
- @Override
- public void setDependencies(Object impl) {
- if (impl instanceof INeutronNetworkCRUD) {
- neutronNetworkCache = (INeutronNetworkCRUD)impl;
- } else if (impl instanceof INeutronPortCRUD) {
- neutronPortCache = (INeutronPortCRUD)impl;
- } else if (impl instanceof INeutronSubnetCRUD) {
- neutronSubnetCache = (INeutronSubnetCRUD)impl;
- } else if (impl instanceof INeutronLoadBalancerCRUD) {
- neutronLBCache = (INeutronLoadBalancerCRUD)impl;
- } else if (impl instanceof LoadBalancerProvider) {
- loadBalancerProvider = (LoadBalancerProvider)impl;
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 SDN Hub, LLC. 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.netvirt.openstack.netvirt;
-
-import java.net.HttpURLConnection;
-import java.util.List;
-import java.util.Map;
-
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheManager;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancerPoolMember;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronLoadBalancerPoolCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronNetworkCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancer;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancerPool;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronLoadBalancerCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronPortCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSubnetCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronLoadBalancerPoolMemberAware;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.EventDispatcher;
-import org.opendaylight.netvirt.openstack.netvirt.api.LoadBalancerConfiguration;
-import org.opendaylight.netvirt.openstack.netvirt.api.LoadBalancerProvider;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Preconditions;
-
-/**
- * Handle requests for OpenStack Neutron v2.0 LBaaS API calls for
- * /v2.0/pools/{pool_id}/members
- */
-
-public class LBaaSPoolMemberHandler extends AbstractHandler
- implements INeutronLoadBalancerPoolMemberAware, ConfigInterface {
- private static final Logger LOG = LoggerFactory.getLogger(LBaaSPoolMemberHandler.class);
-
- // The implementation for each of these services is resolved by the OSGi Service Manager
- private volatile INeutronLoadBalancerPoolCRUD neutronLBPoolCache;
- private volatile INeutronLoadBalancerCRUD neutronLBCache;
- private volatile INeutronPortCRUD neutronPortCache;
- private volatile INeutronNetworkCRUD neutronNetworkCache;
- private volatile INeutronSubnetCRUD neutronSubnetCache;
- private volatile LoadBalancerProvider loadBalancerProvider;
- private volatile NodeCacheManager nodeCacheManager;
-
- @Override
- public int canCreateNeutronLoadBalancerPoolMember(NeutronLoadBalancerPoolMember neutronLBPoolMember) {
- LoadBalancerConfiguration lbConfig = extractLBConfiguration(neutronLBPoolMember);
- if (lbConfig == null) {
- return HttpURLConnection.HTTP_BAD_REQUEST;
- } else if (!lbConfig.isValid()) {
- return HttpURLConnection.HTTP_NOT_ACCEPTABLE;
- } else {
- return HttpURLConnection.HTTP_OK;
- }
- }
-
- @Override
- public void neutronLoadBalancerPoolMemberCreated(NeutronLoadBalancerPoolMember neutronLBPoolMember) {
- LOG.debug("Neutron LB Pool Member Creation : {}", neutronLBPoolMember.toString());
- enqueueEvent(new NorthboundEvent(neutronLBPoolMember, Action.ADD));
- }
-
- /**
- * Assuming that the pool information is fully populated before this call is made,
- * we go with creating the LoadBalancerConfiguration object for this call with
- * all information that is necessary to insert flow_mods
- */
- private void doNeutronLoadBalancerPoolMemberCreate(NeutronLoadBalancerPoolMember neutronLBPoolMember) {
- Preconditions.checkNotNull(loadBalancerProvider);
- LoadBalancerConfiguration lbConfig = extractLBConfiguration(neutronLBPoolMember);
- final List<Node> nodes =
- nodeCacheManager.getBridgeNodes();
- if (lbConfig == null) {
- LOG.debug("Neutron LB configuration invalid for member {} ", neutronLBPoolMember.getPoolMemberAddress());
- } else if (lbConfig.getVip() == null) {
- LOG.debug("Neutron LB VIP not created yet for member {} ", neutronLBPoolMember.getID());
- } else if (!lbConfig.isValid()) {
- LOG.debug("Neutron LB pool configuration invalid for {} ", lbConfig.getName());
- } else if (nodes.isEmpty()) {
- LOG.debug("Noop with LB pool member {} creation because no nodes available.", neutronLBPoolMember.getID());
- } else {
- for (Node node : nodes) {
- loadBalancerProvider.programLoadBalancerPoolMemberRules(node,
- lbConfig,
- lbConfig.getMembers().get(neutronLBPoolMember.getID()), Action.ADD);
- }
- }
- }
-
- @Override
- public int canUpdateNeutronLoadBalancerPoolMember(NeutronLoadBalancerPoolMember delta, NeutronLoadBalancerPoolMember original) {
- return HttpURLConnection.HTTP_NOT_IMPLEMENTED;
- }
-
- @Override
- public void neutronLoadBalancerPoolMemberUpdated(NeutronLoadBalancerPoolMember neutronLBPoolMember) {
- LOG.debug("Neutron LB Pool Member Update : {}", neutronLBPoolMember.toString());
- enqueueEvent(new NorthboundEvent(neutronLBPoolMember, Action.UPDATE));
- }
-
- @Override
- public int canDeleteNeutronLoadBalancerPoolMember(NeutronLoadBalancerPoolMember neutronLBPoolMember) {
- LoadBalancerConfiguration lbConfig = extractLBConfiguration(neutronLBPoolMember);
- if (lbConfig == null) {
- return HttpURLConnection.HTTP_BAD_REQUEST;
- } else if (!lbConfig.isValid()) {
- return HttpURLConnection.HTTP_NOT_ACCEPTABLE;
- } else {
- return HttpURLConnection.HTTP_OK;
- }
- }
-
- @Override
- public void neutronLoadBalancerPoolMemberDeleted(NeutronLoadBalancerPoolMember neutronLBPoolMember) {
- LOG.debug("Neutron LB Pool Member Deletion : {}", neutronLBPoolMember.toString());
- enqueueEvent(new NorthboundEvent(neutronLBPoolMember, Action.DELETE));
- }
-
- private void doNeutronLoadBalancerPoolMemberDelete(NeutronLoadBalancerPoolMember neutronLBPoolMember) {
- Preconditions.checkNotNull(loadBalancerProvider);
-
- LoadBalancerConfiguration lbConfig = extractLBConfiguration(neutronLBPoolMember);
- final List<Node> nodes = nodeCacheManager.getBridgeNodes();
- if (lbConfig == null) {
- LOG.debug("Neutron LB configuration invalid for member {} ", neutronLBPoolMember.getPoolMemberAddress());
- } else if (lbConfig.getVip() == null) {
- LOG.debug("Neutron LB VIP not created yet for member {} ", neutronLBPoolMember.getID());
- } else if (!lbConfig.isValid()) {
- LOG.debug("Neutron LB pool configuration invalid for {} ", lbConfig.getName());
- } else if (nodes.isEmpty()) {
- LOG.debug("Noop with LB pool member {} deletion because no nodes available.", neutronLBPoolMember.getID());
- } else {
- /* As of now, deleting a member involves recomputing member indices.
- * This is best done through a complete update of the load balancer instance.
- */
- LoadBalancerConfiguration newLBConfig = new LoadBalancerConfiguration(lbConfig);
- newLBConfig.removeMember(neutronLBPoolMember.getID());
-
- for (Node node : nodes) {
- loadBalancerProvider.programLoadBalancerRules(node, lbConfig, Action.DELETE);
- loadBalancerProvider.programLoadBalancerRules(node, newLBConfig, Action.ADD);
- }
- }
- }
-
- /**
- * Process the event.
- *
- * @param abstractEvent the {@link AbstractEvent} event to be handled.
- * @see EventDispatcher
- */
- @Override
- public void processEvent(AbstractEvent abstractEvent) {
- LOG.debug("Processing Loadbalancer member event {}", abstractEvent);
- if (!(abstractEvent instanceof NorthboundEvent)) {
- LOG.error("Unable to process abstract event {}", abstractEvent);
- return;
- }
- NorthboundEvent ev = (NorthboundEvent) abstractEvent;
- switch (ev.getAction()) {
- case ADD:
- doNeutronLoadBalancerPoolMemberCreate(ev.getLoadBalancerPoolMember());
- break;
- case DELETE:
- doNeutronLoadBalancerPoolMemberDelete(ev.getLoadBalancerPoolMember());
- break;
- case UPDATE:
- /**
- * Typical upgrade involves changing weights. Since weights are not
- * supported yet, updates are not supported either. TODO
- */
- LOG.warn("Load balancer pool member update is not supported");
- break;
- default:
- LOG.warn("Unable to process event action {}", ev.getAction());
- break;
- }
- }
-
- /**
- * Useful utility for extracting the loadbalancer instance
- * configuration from the neutron LB cache based on member info
- * @param neutronLBPoolMember Neutron LB pool member object
- * @return load balancer configuration of the pool member
- */
- public LoadBalancerConfiguration extractLBConfiguration(NeutronLoadBalancerPoolMember neutronLBPoolMember) {
- String memberID = neutronLBPoolMember.getID();
- String memberIP = neutronLBPoolMember.getPoolMemberAddress();
- String memberSubnetID = neutronLBPoolMember.getPoolMemberSubnetID();
- Integer memberPort = neutronLBPoolMember.getPoolMemberProtoPort();
- String memberPoolID = neutronLBPoolMember.getPoolID();
-
- if (memberSubnetID == null || memberID == null || memberPoolID == null) {
- LOG.debug("Neutron LB pool member details incomplete [id={}, pool_id={},subnet_id={}",
- memberID, memberPoolID, memberSubnetID);
- return null;
- }
- String memberMAC = NeutronCacheUtils.getMacAddress(neutronPortCache, memberSubnetID, memberIP);
- if (memberMAC == null) {
- LOG.debug("Neutron LB pool member {} MAC address unavailable", memberID);
- return null;
- }
- NeutronLoadBalancerPool neutronLBPool = neutronLBPoolCache.getNeutronLoadBalancerPool(memberPoolID);
- if (neutronLBPool == null) {
- LOG.debug("Neutron LB pool {} unavailable", memberPoolID);
- return null;
- }
- String memberProtocol = neutronLBPool.getLoadBalancerPoolProtocol();
- if (!(memberProtocol.equalsIgnoreCase(LoadBalancerConfiguration.PROTOCOL_TCP) ||
- memberProtocol.equalsIgnoreCase(LoadBalancerConfiguration.PROTOCOL_HTTP) ||
- memberProtocol.equalsIgnoreCase(LoadBalancerConfiguration.PROTOCOL_HTTPS))) {
- return null;
- }
-
- String loadBalancerSubnetID=null, loadBalancerVip=null, loadBalancerName=null;
- for (NeutronLoadBalancer neutronLB: neutronLBCache.getAllNeutronLoadBalancers()) {
- loadBalancerSubnetID = neutronLB.getLoadBalancerVipSubnetID();
- if (memberSubnetID.equals(loadBalancerSubnetID)) {
- loadBalancerName = neutronLB.getLoadBalancerName();
- loadBalancerVip = neutronLB.getLoadBalancerVipAddress();
- break;
- }
- }
-
- /**
- * It is possible that the VIP has not been created yet.
- * In that case, we create dummy configuration that will not program rules.
- */
- LoadBalancerConfiguration lbConfig = new LoadBalancerConfiguration(loadBalancerName, loadBalancerVip);
- Map.Entry<String,String> providerInfo = NeutronCacheUtils.getProviderInformation(neutronNetworkCache, neutronSubnetCache, memberSubnetID);
- if (providerInfo != null) {
- lbConfig.setProviderNetworkType(providerInfo.getKey());
- lbConfig.setProviderSegmentationId(providerInfo.getValue());
- }
- lbConfig.setVmac(NeutronCacheUtils.getMacAddress(neutronPortCache, loadBalancerSubnetID, loadBalancerVip));
-
- /* Extract all other active members and include in LB config
- */
- String otherMemberID, otherMemberSubnetID, otherMemberIP, otherMemberMAC, otherMemberProtocol;
- Boolean otherMemberAdminStateIsUp;
- Integer otherMemberPort;
-
- for (NeutronLoadBalancerPoolMember otherMember: neutronLBPool.getLoadBalancerPoolMembers()) {
- otherMemberID = otherMember.getID();
- if (otherMemberID.equals(memberID)) {
- continue; //skip
- }
-
- otherMemberIP = otherMember.getPoolMemberAddress();
- otherMemberAdminStateIsUp = otherMember.getPoolMemberAdminStateIsUp();
- otherMemberSubnetID = otherMember.getPoolMemberSubnetID();
- otherMemberPort = otherMember.getPoolMemberProtoPort();
- otherMemberProtocol = memberProtocol;
-
- if (otherMemberIP != null && otherMemberSubnetID != null && otherMemberAdminStateIsUp != null &&
- otherMemberAdminStateIsUp) {
- otherMemberMAC = NeutronCacheUtils.getMacAddress(neutronPortCache, otherMemberSubnetID, otherMemberIP);
- if (otherMemberMAC == null) {
- continue;
- }
- lbConfig.addMember(otherMemberID, otherMemberIP, otherMemberMAC, otherMemberProtocol, otherMemberPort);
- }
- }
-
- lbConfig.addMember(memberID, memberIP, memberMAC, memberProtocol, memberPort);
- return lbConfig;
- }
-
- @Override
- public void setDependencies(ServiceReference serviceReference) {
- loadBalancerProvider =
- (LoadBalancerProvider) ServiceHelper.getGlobalInstance(LoadBalancerProvider.class, this);
- nodeCacheManager =
- (NodeCacheManager) ServiceHelper.getGlobalInstance(NodeCacheManager.class, this);
- eventDispatcher =
- (EventDispatcher) ServiceHelper.getGlobalInstance(EventDispatcher.class, this);
- eventDispatcher.eventHandlerAdded(serviceReference, this);
- }
-
- @Override
- public void setDependencies(Object impl) {
- if (impl instanceof INeutronNetworkCRUD) {
- neutronNetworkCache = (INeutronNetworkCRUD)impl;
- } else if (impl instanceof INeutronPortCRUD) {
- neutronPortCache = (INeutronPortCRUD)impl;
- } else if (impl instanceof INeutronSubnetCRUD) {
- neutronSubnetCache = (INeutronSubnetCRUD)impl;
- } else if (impl instanceof INeutronLoadBalancerCRUD) {
- neutronLBCache = (INeutronLoadBalancerCRUD)impl;
- } else if (impl instanceof INeutronLoadBalancerPoolCRUD) {
- neutronLBPoolCache = (INeutronLoadBalancerPoolCRUD)impl;
- } else if (impl instanceof LoadBalancerProvider) {
- loadBalancerProvider = (LoadBalancerProvider)impl;
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt;
-
-import com.google.common.base.Preconditions;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeBase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeDpdk;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeDpdkr;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeDpdkvhost;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeDpdkvhostuser;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeGeneve;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeGre;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeGre64;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeInternal;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeIpsecGre;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeIpsecGre64;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeLisp;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypePatch;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeSystem;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeTap;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeVxlan;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeProtocolBase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeProtocolOpenflow10;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeProtocolOpenflow11;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeProtocolOpenflow12;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeProtocolOpenflow13;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeProtocolOpenflow14;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeProtocolOpenflow15;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbFailModeBase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbFailModeSecure;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbFailModeStandalone;
-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.NodeKey;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPoint;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPointKey;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.ImmutableBiMap;
-
-public class MdsalHelper {
- private static final Logger LOG = LoggerFactory.getLogger(MdsalHelper.class);
- public static final TopologyId OVSDB_TOPOLOGY_ID = new TopologyId(new Uri("ovsdb:1"));
- public static final String OVSDB_URI_PREFIX = "ovsdb";
- public static final String BRIDGE_URI_PREFIX = "bridge";
- public static final String TP_URI_PREFIX = "termination-point";
- public static final String DISABLE_IN_BAND = "disable-in-band";
- public static final String HWADDR = "hwaddr";
-
- public static final ImmutableBiMap<Class<? extends OvsdbBridgeProtocolBase>,String> OVSDB_PROTOCOL_MAP
- = new ImmutableBiMap.Builder<Class<? extends OvsdbBridgeProtocolBase>,String>()
- .put(OvsdbBridgeProtocolOpenflow10.class,"OpenFlow10")
- .put(OvsdbBridgeProtocolOpenflow11.class,"OpenFlow11")
- .put(OvsdbBridgeProtocolOpenflow12.class,"OpenFlow12")
- .put(OvsdbBridgeProtocolOpenflow13.class,"OpenFlow13")
- .put(OvsdbBridgeProtocolOpenflow14.class,"OpenFlow14")
- .put(OvsdbBridgeProtocolOpenflow15.class,"OpenFlow15")
- .build();
-
- public static final ImmutableBiMap<Class<? extends OvsdbFailModeBase>,String> OVSDB_FAIL_MODE_MAP
- = new ImmutableBiMap.Builder<Class<? extends OvsdbFailModeBase>,String>()
- .put(OvsdbFailModeStandalone.class,"standalone")
- .put(OvsdbFailModeSecure.class,"secure")
- .build();
-
- public static final ImmutableBiMap<String, Class<? extends InterfaceTypeBase>> OVSDB_INTERFACE_TYPE_MAP
- = new ImmutableBiMap.Builder<String, Class<? extends InterfaceTypeBase>>()
- .put("internal", InterfaceTypeInternal.class)
- .put("vxlan", InterfaceTypeVxlan.class)
- .put("patch", InterfaceTypePatch.class)
- .put("system", InterfaceTypeSystem.class)
- .put("tap", InterfaceTypeTap.class)
- .put("geneve", InterfaceTypeGeneve.class)
- .put("gre", InterfaceTypeGre.class)
- .put("ipsec_gre", InterfaceTypeIpsecGre.class)
- .put("gre64", InterfaceTypeGre64.class)
- .put("ipsec_gre64", InterfaceTypeIpsecGre64.class)
- .put("lisp", InterfaceTypeLisp.class)
- .put("dpdk", InterfaceTypeDpdk.class)
- .put("dpdkr", InterfaceTypeDpdkr.class)
- .put("dpdkvhost", InterfaceTypeDpdkvhost.class)
- .put("dpdkvhostuser", InterfaceTypeDpdkvhostuser.class)
- .build();
-
-
- public static NodeId createManagedNodeId(InstanceIdentifier<Node> iid) {
- NodeKey nodeKey = iid.firstKeyOf(Node.class, NodeKey.class);
- return nodeKey.getNodeId();
- }
-
- public static InstanceIdentifier<Topology> createInstanceIdentifier() {
- return InstanceIdentifier
- .create(NetworkTopology.class)
- .child(Topology.class, new TopologyKey(OVSDB_TOPOLOGY_ID));
- }
-
- public static InstanceIdentifier<Node> createInstanceIdentifier(NodeId nodeId) {
- return InstanceIdentifier
- .create(NetworkTopology.class)
- .child(Topology.class, new TopologyKey(OVSDB_TOPOLOGY_ID))
- .child(Node.class,new NodeKey(nodeId));
- }
-
- public static InstanceIdentifier<Node> createInstanceIdentifier(NodeKey ovsdbNodeKey, String bridgeName) {
- return createInstanceIdentifier(createManagedNodeId(ovsdbNodeKey.getNodeId(), bridgeName));
- }
-
- public static NodeId createManagedNodeId(NodeId ovsdbNodeId, String bridgeName) {
- return new NodeId(ovsdbNodeId.getValue()
- + "/" + BRIDGE_URI_PREFIX + "/" + bridgeName);
- }
-
- public static InstanceIdentifier<TerminationPoint> createTerminationPointInstanceIdentifier(Node node, String portName){
-
- InstanceIdentifier<TerminationPoint> terminationPointPath = InstanceIdentifier
- .create(NetworkTopology.class)
- .child(Topology.class, new TopologyKey(OVSDB_TOPOLOGY_ID))
- .child(Node.class,node.getKey())
- .child(TerminationPoint.class, new TerminationPointKey(new TpId(portName)));
-
- LOG.debug("Termination point InstanceIdentifier generated : {}",terminationPointPath);
- return terminationPointPath;
- }
-
- public static String createOvsdbInterfaceType(Class<? extends InterfaceTypeBase> mdsaltype) {
- Preconditions.checkNotNull(mdsaltype);
- ImmutableBiMap<Class<? extends InterfaceTypeBase>, String> mapper =
- OVSDB_INTERFACE_TYPE_MAP.inverse();
- return mapper.get(mdsaltype);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt;
-
-import com.google.common.base.Optional;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
-import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
-import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipState;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.FrameworkUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * @author Sam Hague (shague@redhat.com)
- */
-public class NetvirtProvider implements AutoCloseable {
- private static final Logger LOG = LoggerFactory.getLogger(NetvirtProvider.class);
- private final BundleContext bundleContext;
- private final DataBroker dataBroker;
- private ConfigActivator activator;
- private static EntityOwnershipService entityOwnershipService;
- private static final Entity ownerInstanceEntity = new Entity(
- Constants.NETVIRT_OWNER_ENTITY_TYPE, Constants.NETVIRT_OWNER_ENTITY_TYPE);
- private boolean conntrackEnabled;
- private boolean intBridgeGenMac;
-
- public NetvirtProvider(final DataBroker dataBroker,
- final EntityOwnershipService eos,
- final boolean conntrackEnabled,
- final boolean intBridgeGenMac) {
- LOG.info("NetvirtProvider started");
- this.dataBroker = dataBroker;
- NetvirtProvider.entityOwnershipService = eos;
- this.conntrackEnabled = conntrackEnabled;
- this.intBridgeGenMac = intBridgeGenMac;
- this.bundleContext = FrameworkUtil.getBundle(NetvirtProvider.class).getBundleContext();
- }
-
- public static boolean isMasterProviderInstance() {
- if (entityOwnershipService != null) {
- Optional<EntityOwnershipState> state = entityOwnershipService.getOwnershipState(ownerInstanceEntity);
- return state.isPresent() && state.get().isOwner();
- }
- return false;
- }
-
- public static boolean isMasterElected(){
- if (entityOwnershipService != null) {
- Optional<EntityOwnershipState> state = entityOwnershipService.getOwnershipState(ownerInstanceEntity);
- return state.isPresent() && state.get().hasOwner();
- }
- return false;
- }
-
- @Override
- public void close() throws Exception {
- LOG.info("NetvirtProvider closed");
- if (activator != null) {
- activator.stop(bundleContext);
- }
- }
-
- public void start() {
- LOG.info("NetvirtProvider: onSessionInitiated dataBroker: {}", dataBroker);
- LOG.info("NetvirtProvider: onSessionInitiated isConntrackEnabled: {}", this.conntrackEnabled);
- this.activator = new ConfigActivator(dataBroker);
- activator.setConntrackEnabled(this.conntrackEnabled);
- activator.setIntBridgeGenMac(this.intBridgeGenMac);
- try {
- activator.start(bundleContext);
- } catch (Exception e) {
- LOG.warn("Failed to start Netvirt: ", e);
- }
- }
-
- public boolean isConntrackEnabled() {
- return conntrackEnabled;
- }
-
- public void setConntrackEnabled(boolean conntackEnabled) {
- this.conntrackEnabled = conntackEnabled;
- }
-
- public boolean getIntBridgeGenMac() {
- return intBridgeGenMac;
- }
-
- public void setIntBridgeGenMac(boolean intBridgeGenMac) {
- this.intBridgeGenMac = intBridgeGenMac;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt;
-
-import java.net.HttpURLConnection;
-import java.util.List;
-
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheManager;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronNetworkCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronNetworkAware;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.BridgeConfigurationManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.EventDispatcher;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.openstack.netvirt.api.TenantNetworkManager;
-import org.opendaylight.netvirt.openstack.netvirt.impl.NeutronL3Adapter;
-import org.opendaylight.netvirt.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.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Handle requests for Neutron Network.
- */
-public class NetworkHandler extends AbstractHandler implements INeutronNetworkAware, ConfigInterface {
- private static final Logger LOG = LoggerFactory.getLogger(NetworkHandler.class);
- public static final String NETWORK_TYPE_VXLAN = "vxlan";
- public static final String NETWORK_TYPE_GRE = "gre";
- public static final String NETWORK_TYPE_VLAN = "vlan";
-
- // The implementation for each of these services is resolved by the OSGi Service Manager
- private volatile TenantNetworkManager tenantNetworkManager;
- private volatile BridgeConfigurationManager bridgeConfigurationManager;
- private volatile NodeCacheManager nodeCacheManager;
- private volatile INeutronNetworkCRUD neutronNetworkCache;
- private volatile NeutronL3Adapter neutronL3Adapter;
- private volatile Southbound southbound;
-
- /**
- * Invoked when a network creation is requested
- * to indicate if the specified network can be created.
- *
- * @param network An instance of proposed new Neutron Network object.
- * @return A HTTP status code to the creation request.
- */
- @Override
- public int canCreateNetwork(NeutronNetwork network) {
- return HttpURLConnection.HTTP_OK;
- }
-
- /**
- * Invoked to take action after a network has been created.
- *
- * @param network An instance of new Neutron Network object.
- */
- @Override
- public void neutronNetworkCreated(NeutronNetwork network) {
- enqueueEvent(new NorthboundEvent(network, Action.ADD));
- }
- private void doNeutronNetworkCreated(NeutronNetwork network) {
- neutronL3Adapter.handleNeutronNetworkEvent(network, Action.ADD);
- }
-
- /**
- * Invoked when a network update is requested
- * to indicate if the specified network can be changed
- * using the specified delta.
- *
- * @param delta Updates to the network object using patch semantics.
- * @param original An instance of the Neutron Network object
- * to be updated.
- * @return A HTTP status code to the update request.
- */
- @Override
- public int canUpdateNetwork(NeutronNetwork delta,
- NeutronNetwork original) {
- return HttpURLConnection.HTTP_OK;
- }
-
- /**
- * Invoked to take action after a network has been updated.
- *
- * @param network An instance of modified Neutron Network object.
- */
- @Override
- public void neutronNetworkUpdated(NeutronNetwork network) {
- enqueueEvent(new NorthboundEvent(network, Action.UPDATE));
- }
- private void doNeutronNetworkUpdated(NeutronNetwork network) {
- neutronL3Adapter.handleNeutronNetworkEvent(network, Action.UPDATE);
- }
-
- /**
- * Invoked when a network deletion is requested
- * to indicate if the specified network can be deleted.
- *
- * @param network An instance of the Neutron Network object to be deleted.
- * @return A HTTP status code to the deletion request.
- */
- @Override
- public int canDeleteNetwork(NeutronNetwork network) {
- return HttpURLConnection.HTTP_OK;
- }
-
- /**
- * Invoked to take action after a network has been deleted.
- *
- * @param network An instance of deleted Neutron Network object.
- */
- @Override
- public void neutronNetworkDeleted(NeutronNetwork network) {
- enqueueEvent(new NorthboundEvent(network, Action.DELETE));
- }
- private void doNeutronNetworkDeleted(NeutronNetwork network) {
- neutronL3Adapter.handleNeutronNetworkEvent(network, Action.DELETE);
-
- /* Is this the last Neutron tenant network */
- List <NeutronNetwork> networks;
- if (neutronNetworkCache != null) {
- networks = neutronNetworkCache.getAllNetworks();
- if (networks.isEmpty()) {
- LOG.trace("neutronNetworkDeleted: last tenant network, delete tunnel ports...");
- List<Node> nodes = nodeCacheManager.getNodes();
-
- for (Node node : nodes) {
- List<String> phyIfName = bridgeConfigurationManager.getAllPhysicalInterfaceNames(node);
- try {
- List<OvsdbTerminationPointAugmentation> ports = southbound.getTerminationPointsOfBridge(node);
- for (OvsdbTerminationPointAugmentation port : ports) {
- if (southbound.isTunnel(port)) {
- LOG.trace("Delete tunnel interface {}", port.getName());
- southbound.deleteTerminationPoint(node, port.getName());
- } else if (!phyIfName.isEmpty() && phyIfName.contains(port.getName())) {
- LOG.trace("Delete physical interface {}", port.getName());
- southbound.deleteTerminationPoint(node, port.getName());
- }
- }
- } catch (Exception e) {
- LOG.error("Exception during handlingNeutron network delete", e);
- }
- }
- }
- }
- tenantNetworkManager.networkDeleted(network.getID());
- }
-
- /**
- * Process the event.
- *
- * @param abstractEvent the {@link AbstractEvent} event to be handled.
- * @see EventDispatcher
- */
- @Override
- public void processEvent(AbstractEvent abstractEvent) {
- if (!(abstractEvent instanceof NorthboundEvent)) {
- LOG.error("Unable to process abstract event {}", abstractEvent);
- return;
- }
- NorthboundEvent ev = (NorthboundEvent) abstractEvent;
- switch (ev.getAction()) {
- case ADD:
- doNeutronNetworkCreated(ev.getNeutronNetwork());
- break;
- case UPDATE:
- doNeutronNetworkUpdated(ev.getNeutronNetwork());
- break;
- case DELETE:
- doNeutronNetworkDeleted(ev.getNeutronNetwork());
- break;
- default:
- LOG.warn("Unable to process event action {}", ev.getAction());
- break;
- }
- }
-
- @Override
- public void setDependencies(ServiceReference serviceReference) {
- tenantNetworkManager =
- (TenantNetworkManager) ServiceHelper.getGlobalInstance(TenantNetworkManager.class, this);
- bridgeConfigurationManager =
- (BridgeConfigurationManager) ServiceHelper.getGlobalInstance(BridgeConfigurationManager.class, this);
- nodeCacheManager =
- (NodeCacheManager) ServiceHelper.getGlobalInstance(NodeCacheManager.class, this);
- neutronL3Adapter =
- (NeutronL3Adapter) ServiceHelper.getGlobalInstance(NeutronL3Adapter.class, this);
- southbound =
- (Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this);
- eventDispatcher =
- (EventDispatcher) ServiceHelper.getGlobalInstance(EventDispatcher.class, this);
- eventDispatcher.eventHandlerAdded(serviceReference, this);
- }
-
- @Override
- public void setDependencies(Object impl) {
- if (impl instanceof INeutronNetworkCRUD) {
- neutronNetworkCache = (INeutronNetworkCRUD)impl;
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 SDN Hub, LLC. 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.netvirt.openstack.netvirt;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronNetworkCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSubnet;
-import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronPortCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSubnetCRUD;
-
-import java.util.AbstractMap;
-import java.util.List;
-import java.util.Map;
-
-public class NeutronCacheUtils {
-
- /**
- * Look up in the NeutronPortsCRUD cache and return the MAC address for a corresponding IP address
- * @param neutronPortsCache Reference to port cache to get existing port related data. This interface
- * basically read data from the md-sal data store.
- * @param subnetID subnet to which given port is attached
- * @param ipAddr IP address of a member or VM
- * @return MAC address registered with that IP address
- */
- public static String getMacAddress(INeutronPortCRUD neutronPortsCache, String subnetID, String ipAddr) {
- if (ipAddr == null || subnetID == null) {
- return null;
- }
-
- List<NeutronPort> allPorts = neutronPortsCache.getAllPorts();
- for (NeutronPort port : allPorts) {
- List<Neutron_IPs> fixedIPs = port.getFixedIPs();
- if (fixedIPs != null && !fixedIPs.isEmpty()) {
- for (Neutron_IPs ip : fixedIPs) {
- if (ip.getIpAddress().equals(ipAddr) && ip.getSubnetUUID().equals(subnetID)) {
- return port.getMacAddress();
- }
- }
- }
- }
- return null;
- }
-
- /**
- * Look up in the NeutronNetworkCRUD cache and NeutronSubnetCRUD cache for
- * extracting the provider segmentation_type and segmentation_id
- * @param neutronNetworkCache Reference to neutron network cache to get existing network related data.
- * This interface basically read data from the md-sal data store.
- * @param neutronSubnetCache Reference to neutron subnet cache to get existing subnet related data.
- * This interface basically read data from the md-sal data store.
- * @param subnetID Subnet UUID
- * @return {Type: ID} pair for that subnet ID
- */
- public static Map.Entry<String,String> getProviderInformation(INeutronNetworkCRUD neutronNetworkCache,
- INeutronSubnetCRUD neutronSubnetCache, String subnetID) {
-
- String networkID = null;
-
- List<NeutronSubnet> allSubnets = neutronSubnetCache.getAllSubnets();
- for (NeutronSubnet subnet: allSubnets) {
- if (subnet.getID().equals(subnetID)) {
- networkID = subnet.getNetworkUUID();
- break;
- }
- }
- if (networkID == null) {
- return null;
- }
-
- List<NeutronNetwork> allNetworks = neutronNetworkCache.getAllNetworks();
- for (NeutronNetwork network: allNetworks) {
- if (network.getID().equals(networkID)) {
- return new AbstractMap.SimpleEntry<>(
- network.getProviderNetworkType(), network.getProviderSegmentationID());
- }
- }
- return null;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt;
-
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
-
-public class NeutronL3AdapterEvent extends AbstractEvent {
- public enum SubType {
- SUBTYPE_EXTERNAL_MAC_UPDATE; // TODO: Add more subtypes as they come here
-
- public static final int size = HandlerType.values().length;
- }
-
- private final SubType subtype;
-
- private final Long bridgeDpid;
- private final IpAddress gatewayIpAddress;
- private final MacAddress macAddress;
-
- public NeutronL3AdapterEvent(final Long bridgeDpid, final IpAddress gatewayIpAddress, final MacAddress macAddress) {
- super(HandlerType.NEUTRON_L3_ADAPTER, Action.UPDATE);
-
- this.subtype = SubType.SUBTYPE_EXTERNAL_MAC_UPDATE;
- this.bridgeDpid = bridgeDpid;
- this.gatewayIpAddress = gatewayIpAddress;
- this.macAddress = macAddress;
- }
-
- public SubType getSubType() {
- return subtype;
- }
-
- public Long getBridgeDpid() {
- return bridgeDpid;
- }
- public IpAddress getGatewayIpAddress() {
- return gatewayIpAddress;
- }
- public MacAddress getMacAddress() {
- return macAddress;
- }
-
- @Override
- public String toString() {
- return "NeutronL3AdapterEvent [handler=" + super.getHandlerType()
- + ", action=" + super.getAction()
- + ", subtype=" + subtype
- + ", bridgeDpid=" + bridgeDpid
- + ", gatewayIpAddress=" + gatewayIpAddress
- + ", macAddress=" + macAddress
- + "]";
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = super.hashCode();
- result = prime * result + ((subtype == null) ? 0 : subtype.hashCode());
- result = prime * result + ((bridgeDpid == null) ? 0 : bridgeDpid.hashCode());
- result = prime * result + ((gatewayIpAddress == null) ? 0 : gatewayIpAddress.hashCode());
- result = prime * result + ((macAddress == null) ? 0 : macAddress.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- if (!super.equals(obj)) {
- return false;
- }
- NeutronL3AdapterEvent other = (NeutronL3AdapterEvent) obj;
- if (subtype == null) {
- if (other.subtype != null) {
- return false;
- }
- } else if (!subtype.equals(other.subtype)) {
- return false;
- }
- if (bridgeDpid == null) {
- if (other.bridgeDpid != null) {
- return false;
- }
- } else if (!bridgeDpid.equals(other.bridgeDpid)) {
- return false;
- }
- if (gatewayIpAddress == null) {
- if (other.gatewayIpAddress != null) {
- return false;
- }
- } else if (!gatewayIpAddress.equals(other.gatewayIpAddress)) {
- return false;
- }
- if (macAddress == null) {
- if (other.macAddress != null) {
- return false;
- }
- } else if (!macAddress.equals(other.macAddress)) {
- return false;
- }
- return true;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt;
-
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.netvirt.utils.mdsal.utils.MdsalUtils;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.Routers;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.Networks;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.networks.Network;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.networks.NetworkKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.Ports;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.PortKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class NeutronModelsDataStoreHelper {
-
- private static final Logger LOG = LoggerFactory.getLogger(MdsalUtils.class);
- private DataBroker databroker = null;
- private MdsalUtils mdsalClient = null;
-
- /**
- * Class constructor setting the data broker.
- *
- * @param dataBroker the {@link org.opendaylight.controller.md.sal.binding.api.DataBroker}
- */
- public NeutronModelsDataStoreHelper(DataBroker dataBroker) {
- this.databroker = dataBroker;
- this.mdsalClient = new MdsalUtils(this.databroker);
- }
-
- public Routers readAllNeutronRouters() {
- Routers routers = this.mdsalClient.read(LogicalDatastoreType.CONFIGURATION, getNeutrounRoutersPath());
- if(routers != null ) {
- LOG.debug("{} routers present in data store", routers.getRouter()!=null? routers.getRouter().size():0);
- }
- return routers;
- }
-
- public Ports readAllNeutronPorts() {
- Ports ports = this.mdsalClient.read(LogicalDatastoreType.CONFIGURATION, getNeutrounPortsPath());
- if(ports != null ) {
- LOG.debug("{} ports present in data store", ports.getPort()!=null? ports.getPort().size():0);
- }
- return ports;
- }
- public Port readNeutronPort(Uuid portId) {
- Port mdsalPort = this.mdsalClient.read(LogicalDatastoreType.CONFIGURATION, getNeutronPortPath(portId));
- if (mdsalPort != null) {
- LOG.debug("Port {} fetched from config data store for router interface {}",mdsalPort, portId);
- }
- return mdsalPort;
- }
-
- public InstanceIdentifier<Routers> getNeutrounRoutersPath() {
- return InstanceIdentifier
- .create(Neutron.class)
- .child(Routers.class);
- }
-
- public InstanceIdentifier<Ports> getNeutrounPortsPath() {
- return InstanceIdentifier
- .create(Neutron.class)
- .child(Ports.class);
- }
-
- public InstanceIdentifier<Port> getNeutronPortPath(Uuid portId) {
- return InstanceIdentifier
- .create(Neutron.class)
- .child(Ports.class)
- .child(Port.class,new PortKey(portId));
- }
-
- public InstanceIdentifier<Network> getNeutronNetworkPath(Uuid networkId) {
- return InstanceIdentifier
- .create(Neutron.class)
- .child(Networks.class)
- .child(Network.class,new NetworkKey(networkId));
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt;
-
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-
-/**
- * @author Flavio Fernandes (ffernand@redhat.com)
- * @author Sam Hague (shague@redhat.com)
- */
-public class NodeCacheManagerEvent extends AbstractEvent {
- private Node node;
-
- public NodeCacheManagerEvent(Node node, Action action) {
- super(HandlerType.NODE, action);
- this.node = node;
- }
-
- public Node getNode() {
- return node;
- }
-
- public String getNodeIdentifier() {
- return node.getNodeId().getValue();
- }
-
- @Override
- public String toString() {
- return "NodeCacheManagerEvent [action=" + super.getAction()
- + ", node=" + node
- + "]";
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = super.hashCode();
- result = prime * result + ((node == null) ? 0 : node.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- if (!super.equals(obj)) {
- return false;
- }
- NodeCacheManagerEvent other = (NodeCacheManagerEvent) obj;
- if (node == null) {
- if (other.node != null) {
- return false;
- }
- } else if (!node.equals(other.node)) {
- return false;
- }
- return true;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt;
-
-import java.util.LinkedList;
-import java.util.Queue;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-
-public class NodeConfiguration {
- private java.util.Queue<Integer> internalVlans = new LinkedList<>();
- private ConcurrentMap<String, Integer> tenantVlanMap = new ConcurrentHashMap<>();
-
- public NodeConfiguration() {
- for (int i = 1; i < Constants.MAX_VLAN; i++) {
- internalVlans.add(i);
-
- }
- }
-
- public Queue<Integer> getInternalVlans() {
- return internalVlans;
- }
-
- public ConcurrentMap<String, Integer> getTenantVlanMap() {
- return tenantVlanMap;
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt;
-
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronFloatingIP;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancer;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancerPool;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancerPoolMember;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronRouter_Interface;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityRule;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronRouter;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSubnet;
-
-public class NorthboundEvent extends AbstractEvent {
-
- private NeutronPort port;
- private NeutronSubnet subnet;
- private NeutronRouter router;
- private NeutronRouter_Interface routerInterface;
- private NeutronFloatingIP neutronFloatingIP;
- private NeutronNetwork neutronNetwork;
- private NeutronLoadBalancer loadBalancer;
- private NeutronLoadBalancerPool loadBalancerPool;
- private NeutronLoadBalancerPoolMember loadBalancerPoolMember;
- private NeutronSecurityRule neutronSecurityRule;
-
- NorthboundEvent(NeutronPort port, Action action) {
- super(HandlerType.NEUTRON_PORT, action);
- this.port = port;
- }
-
- NorthboundEvent(NeutronSubnet subnet, Action action) {
- super(HandlerType.NEUTRON_SUBNET, action);
- this.subnet = subnet;
- }
-
- NorthboundEvent(NeutronRouter router, Action action) {
- super(HandlerType.NEUTRON_ROUTER, action);
- this.router = router;
- }
-
- NorthboundEvent(NeutronRouter router, NeutronRouter_Interface routerInterface, Action action) {
- super(HandlerType.NEUTRON_ROUTER, action);
- this.router = router;
- this.routerInterface = routerInterface;
- }
-
- NorthboundEvent(NeutronFloatingIP neutronFloatingIP, Action action) {
- super(HandlerType.NEUTRON_FLOATING_IP, action);
- this.neutronFloatingIP = neutronFloatingIP;
- }
-
- NorthboundEvent(NeutronNetwork neutronNetwork, Action action) {
- super(HandlerType.NEUTRON_NETWORK, action);
- this.neutronNetwork = neutronNetwork;
- }
-
- NorthboundEvent(NeutronLoadBalancer loadBalancer, Action action) {
- super(HandlerType.NEUTRON_LOAD_BALANCER, action);
- this.loadBalancer = loadBalancer;
- }
-
- NorthboundEvent(NeutronLoadBalancerPool loadBalancerPool, Action action) {
- super(HandlerType.NEUTRON_LOAD_BALANCER_POOL, action);
- this.loadBalancerPool = loadBalancerPool;
- }
-
- NorthboundEvent(NeutronLoadBalancerPoolMember loadBalancerPoolMember, Action action) {
- super(HandlerType.NEUTRON_LOAD_BALANCER_POOL_MEMBER, action);
- this.loadBalancerPoolMember = loadBalancerPoolMember;
- }
-
- NorthboundEvent(NeutronSecurityRule neutronSecurityRule, Action action) {
- super(HandlerType.NEUTRON_PORT_SECURITY, action);
- this.neutronSecurityRule = neutronSecurityRule;
- }
-
- public NeutronPort getPort() {
- return port;
- }
- public NeutronSubnet getSubnet() {
- return subnet;
- }
- public NeutronRouter getRouter() {
- return router;
- }
- public NeutronRouter_Interface getRouterInterface() {
- return routerInterface;
- }
- public NeutronFloatingIP getNeutronFloatingIP() {
- return neutronFloatingIP;
- }
- public NeutronNetwork getNeutronNetwork() {
- return neutronNetwork;
- }
- public NeutronLoadBalancer getLoadBalancer() {
- return loadBalancer;
- }
- public NeutronLoadBalancerPool getLoadBalancerPool() {
- return loadBalancerPool;
- }
- public NeutronLoadBalancerPoolMember getLoadBalancerPoolMember() {
- return loadBalancerPoolMember;
- }
- public NeutronSecurityRule getNeutronSecurityRule() {
- return neutronSecurityRule;
- }
-
- @Override
- public String toString() {
- return "NorthboundEvent [handler=" + super.getHandlerType()
- + ", action=" + super.getAction()
- + ", port=" + port
- + ", subnet=" + subnet
- + ", router=" + router
- + ", routerInterface=" + routerInterface
- + ", floatingIP=" + neutronFloatingIP
- + ", network=" + neutronNetwork
- + ", loadBalancer=" + loadBalancer
- + ", loadBalancerPool=" + loadBalancerPool
- + ", loadBalancerPoolMember=" + loadBalancerPoolMember
- + ", neutronsecurityRule=" + neutronSecurityRule
- + "]";
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = super.hashCode();
- result = prime * result + ((port == null) ? 0 : port.hashCode());
- result = prime * result + ((subnet == null) ? 0 : subnet.hashCode());
- result = prime * result + ((router == null) ? 0 : router.hashCode());
- result = prime * result + ((routerInterface == null) ? 0 : routerInterface.hashCode());
- result = prime * result + ((neutronFloatingIP == null) ? 0 : neutronFloatingIP.hashCode());
- result = prime * result + ((neutronNetwork == null) ? 0 : neutronNetwork.hashCode());
- result = prime * result + ((neutronSecurityRule == null) ? 0 : neutronSecurityRule.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- if (!super.equals(obj)) {
- return false;
- }
- NorthboundEvent other = (NorthboundEvent) obj;
- if (port == null) {
- if (other.port != null) {
- return false;
- }
- } else if (!port.equals(other.port)) {
- return false;
- }
- if (subnet == null) {
- if (other.subnet != null) {
- return false;
- }
- } else if (!subnet.equals(other.subnet)) {
- return false;
- }
- if (router == null) {
- if (other.router != null) {
- return false;
- }
- } else if (!router.equals(other.router)) {
- return false;
- }
- if (routerInterface == null) {
- if (other.routerInterface != null) {
- return false;
- }
- } else if (!routerInterface.equals(other.routerInterface)) {
- return false;
- }
- if (neutronFloatingIP == null) {
- if (other.neutronFloatingIP != null) {
- return false;
- }
- } else if (!neutronFloatingIP.equals(other.neutronFloatingIP)) {
- return false;
- }
- if (neutronNetwork == null) {
- if (other.neutronNetwork != null) {
- return false;
- }
- } else if (!neutronNetwork.equals(other.neutronNetwork)) {
- return false;
- }
- if (loadBalancer == null) {
- if (other.loadBalancer != null) {
- return false;
- }
- } else if (!loadBalancer.equals(other.loadBalancer)) {
- return false;
- }
- if (loadBalancerPool == null) {
- if (other.loadBalancerPool != null) {
- return false;
- }
- } else if (!loadBalancerPool.equals(other.loadBalancerPool)) {
- return false;
- }
- if (loadBalancerPoolMember == null) {
- if (other.loadBalancerPoolMember != null) {
- return false;
- }
- } else if (!loadBalancerPoolMember.equals(other.loadBalancerPoolMember)) {
- return false;
- }
- if (neutronSecurityRule == null) {
- if (other.neutronSecurityRule != null) {
- return false;
- }
- } else if (!neutronSecurityRule.equals(other.neutronSecurityRule)) {
- return false;
- }
- return true;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt;
-
-import java.net.HttpURLConnection;
-import java.util.List;
-
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.BridgeConfigurationManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.NetworkingProviderManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheListener;
-import org.opendaylight.netvirt.openstack.netvirt.api.TenantNetworkManager;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronPortCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronPortAware;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-import org.opendaylight.netvirt.openstack.netvirt.api.EventDispatcher;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.openstack.netvirt.impl.NeutronL3Adapter;
-import org.opendaylight.netvirt.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.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Handle requests for Neutron Port.
- */
-public class PortHandler extends AbstractHandler implements INeutronPortAware, NodeCacheListener, ConfigInterface {
- private static final Logger LOG = LoggerFactory.getLogger(PortHandler.class);
-
- // The implementation for each of these services is resolved by the OSGi Service Manager
- private volatile NodeCacheManager nodeCacheManager;
- private volatile BridgeConfigurationManager bridgeConfigurationManager;
- private volatile TenantNetworkManager tenantNetworkManager;
- private volatile NetworkingProviderManager networkingProviderManager;
- private volatile NeutronL3Adapter neutronL3Adapter;
- private volatile Southbound southbound;
- private volatile INeutronPortCRUD neutronPortCache;
-
- /**
- * Invoked when a port creation is requested
- * to indicate if the specified port can be created.
- *
- * @param port An instance of proposed new Port object.
- * @return A HTTP status code to the creation request.
- */
- @Override
- public int canCreatePort(NeutronPort port) {
- return HttpURLConnection.HTTP_OK;
- }
-
- /**
- * Invoked to take action after a port has been created.
- *
- * @param neutronPort An instance of new Neutron Port object.
- */
- @Override
- public void neutronPortCreated(NeutronPort neutronPort) {
- enqueueEvent(new NorthboundEvent(neutronPort, Action.ADD));
- }
- private void doNeutronPortCreated(NeutronPort neutronPort) {
- LOG.debug(" Port-ADD successful for tenant-id - {}, network-id - {}, port-id - {}",
- neutronPort.getTenantID(), neutronPort.getNetworkUUID(),
- neutronPort.getID());
-
- //TODO: Need to implement getNodes
- List<Node> nodes = nodeCacheManager.getNodes();
- for (Node node : nodes) {
- OvsdbTerminationPointAugmentation port = findPortOnNode(node, neutronPort);
- // if the port already exist on the node it means that the southbound event already arrived
- // and was not handled because we could not find the tenant network
- if (port != null) {
- NeutronNetwork network = tenantNetworkManager.getTenantNetwork(port);
- if (network != null && !network.getRouterExternal()) {
- LOG.trace("handleInterfaceUpdate <{}> <{}> network: {}", node, port, network.getNetworkUUID());
- if (bridgeConfigurationManager.createLocalNetwork(node, network)) {
- networkingProviderManager.getProvider(node).handleInterfaceUpdate(network, node, port);
- }
- }
- break;
- }
- }
-
- neutronL3Adapter.handleNeutronPortEvent(neutronPort, Action.ADD);
- }
-
- /**
- * Invoked when a port update is requested
- * to indicate if the specified port can be changed
- * using the specified delta.
- *
- * @param delta Updates to the port object using patch semantics.
- * @param original An instance of the Neutron Port object
- * to be updated.
- * @return A HTTP status code to the update request.
- */
- @Override
- public int canUpdatePort(NeutronPort delta,
- NeutronPort original) {
- return HttpURLConnection.HTTP_OK;
- }
-
- /**
- * Invoked to take action after a port has been updated.
- *
- * @param neutronPort An instance of modified Neutron Port object.
- */
- @Override
- public void neutronPortUpdated(NeutronPort neutronPort) {
- enqueueEvent(new NorthboundEvent(neutronPort, Action.UPDATE));
- }
- private void doNeutronPortUpdated(NeutronPort neutronPort) {
- LOG.debug("Handling neutron update port {}", neutronPort);
- neutronL3Adapter.handleNeutronPortEvent(neutronPort, Action.UPDATE);
- }
-
- /**
- * Invoked when a port deletion is requested
- * to indicate if the specified port can be deleted.
- *
- * @param port An instance of the Neutron Port object to be deleted.
- * @return A HTTP status code to the deletion request.
- */
- @Override
- public int canDeletePort(NeutronPort port) {
- return HttpURLConnection.HTTP_OK;
- }
-
- /**
- * Invoked to take action after a port has been deleted.
- *
- * @param neutronPort An instance of deleted Neutron Port object.
- */
- @Override
- public void neutronPortDeleted(NeutronPort neutronPort) {
- enqueueEvent(new NorthboundEvent(neutronPort, Action.DELETE));
- }
- private void doNeutronPortDeleted(NeutronPort neutronPort) {
- LOG.debug("Handling neutron delete port {}", neutronPort);
- neutronL3Adapter.handleNeutronPortEvent(neutronPort, Action.DELETE);
-
- //TODO: Need to implement getNodes
- List<Node> nodes = nodeCacheManager.getNodes();
- for (Node node : nodes) {
- OvsdbTerminationPointAugmentation port = findPortOnNode(node, neutronPort);
- if (port != null) {
- LOG.trace("neutronPortDeleted: Delete interface {}", port.getName());
- southbound.deleteTerminationPoint(node, port.getName());
- break;
- }
- }
-
- LOG.debug(" PORT delete successful for tenant-id - {}, network-id - {}, port-id - {}",
- neutronPort.getTenantID(), neutronPort.getNetworkUUID(),
- neutronPort.getID());
- }
-
- private OvsdbTerminationPointAugmentation findPortOnNode(Node node, NeutronPort neutronPort){
- try {
- List<OvsdbTerminationPointAugmentation> ports = southbound.readTerminationPointAugmentations(node);
- for (OvsdbTerminationPointAugmentation port : ports) {
- String neutronPortId =
- southbound.getInterfaceExternalIdsValue(port, Constants.EXTERNAL_ID_INTERFACE_ID);
- if (neutronPortId != null && neutronPortId.equalsIgnoreCase(neutronPort.getPortUUID())) {
- return port;
- }
- }
- } catch (Exception e) {
- LOG.error("Exception while reading ports", e);
- }
- return null;
- }
-
- @Override
- public void notifyNode(Node node, Action action) {
- if (action == Action.ADD) {
- List<NeutronPort> neutronPorts = neutronPortCache.getAllPorts();
- for (NeutronPort neutronPort : neutronPorts) {
- LOG.info("in notifyNode, neutronPort {} will be added", neutronPort);
- neutronPortCreated(neutronPort);
- }
- }
- }
-
- /**
- * Process the event.
- *
- * @param abstractEvent the {@link AbstractEvent} event to be handled.
- * @see EventDispatcher
- */
- @Override
- public void processEvent(AbstractEvent abstractEvent) {
- if (!(abstractEvent instanceof NorthboundEvent)) {
- LOG.error("Unable to process abstract event {}", abstractEvent);
- return;
- }
- NorthboundEvent ev = (NorthboundEvent) abstractEvent;
- switch (ev.getAction()) {
- case ADD:
- doNeutronPortCreated(ev.getPort());
- break;
- case DELETE:
- doNeutronPortDeleted(ev.getPort());
- break;
- case UPDATE:
- doNeutronPortUpdated(ev.getPort());
- break;
- default:
- LOG.warn("Unable to process event action {}", ev.getAction());
- break;
- }
- }
-
- @Override
- public void setDependencies(ServiceReference serviceReference) {
- nodeCacheManager =
- (NodeCacheManager) ServiceHelper.getGlobalInstance(NodeCacheManager.class, this);
- nodeCacheManager.cacheListenerAdded(serviceReference, this);
- networkingProviderManager =
- (NetworkingProviderManager) ServiceHelper.getGlobalInstance(NetworkingProviderManager.class, this);
- tenantNetworkManager =
- (TenantNetworkManager) ServiceHelper.getGlobalInstance(TenantNetworkManager.class, this);
- bridgeConfigurationManager =
- (BridgeConfigurationManager) ServiceHelper.getGlobalInstance(BridgeConfigurationManager.class, this);
- neutronL3Adapter =
- (NeutronL3Adapter) ServiceHelper.getGlobalInstance(NeutronL3Adapter.class, this);
- southbound =
- (Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this);
- eventDispatcher =
- (EventDispatcher) ServiceHelper.getGlobalInstance(EventDispatcher.class, this);
- eventDispatcher.eventHandlerAdded(serviceReference, this);
-
- }
-
- @Override
- public void setDependencies(Object impl) {
- if (impl instanceof INeutronPortCRUD) {
- neutronPortCache = (INeutronPortCRUD)impl;
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt;
-
-import java.net.HttpURLConnection;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-import org.opendaylight.netvirt.openstack.netvirt.api.EventDispatcher;
-import org.opendaylight.netvirt.openstack.netvirt.api.SecurityGroupCacheManger;
-import org.opendaylight.netvirt.openstack.netvirt.api.SecurityServicesManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronSecurityRuleAware;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSecurityGroupCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityGroup;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityRule;
-import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronPortCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronSecurityGroupAware;
-import org.opendaylight.netvirt.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.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Handle requests for OpenStack Neutron v2.0 Port Security API calls.
- */
-public class PortSecurityHandler extends AbstractHandler
- implements INeutronSecurityGroupAware, INeutronSecurityRuleAware, ConfigInterface {
-
- private static final Logger LOG = LoggerFactory.getLogger(PortSecurityHandler.class);
- private volatile Southbound southbound;
- private volatile INeutronPortCRUD neutronPortCache;
- private volatile SecurityServicesManager securityServicesManager;
- private volatile SecurityGroupCacheManger securityGroupCacheManger;
-
- @Override
- public int canCreateNeutronSecurityGroup(NeutronSecurityGroup neutronSecurityGroup) {
- return HttpURLConnection.HTTP_CREATED;
- }
-
- @Override
- public void neutronSecurityGroupCreated(NeutronSecurityGroup neutronSecurityGroup) {
- int result = canCreateNeutronSecurityGroup(neutronSecurityGroup);
- if (result != HttpURLConnection.HTTP_CREATED) {
- LOG.debug("Neutron Security Group creation failed {} ", result);
- }
- }
-
- @Override
- public int canUpdateNeutronSecurityGroup(NeutronSecurityGroup delta, NeutronSecurityGroup original) {
- return HttpURLConnection.HTTP_OK;
- }
-
- @Override
- public void neutronSecurityGroupUpdated(NeutronSecurityGroup neutronSecurityGroup) {
- // Nothing to do
- }
-
- @Override
- public int canDeleteNeutronSecurityGroup(NeutronSecurityGroup neutronSecurityGroup) {
- return HttpURLConnection.HTTP_OK;
- }
-
- @Override
- public void neutronSecurityGroupDeleted(NeutronSecurityGroup neutronSecurityGroup) {
- //TODO: Trigger flowmod removals
- int result = canDeleteNeutronSecurityGroup(neutronSecurityGroup);
- if (result != HttpURLConnection.HTTP_OK) {
- LOG.error(" delete Neutron Security Rule validation failed for result - {} ", result);
- }
- }
-
- /**
- * Invoked when a Security Rules creation is requested
- * to indicate if the specified Rule can be created.
- *
- * @param neutronSecurityRule An instance of proposed new Neutron Security Rule object.
- * @return A HTTP status code to the creation request.
- */
-
- @Override
- public int canCreateNeutronSecurityRule(NeutronSecurityRule neutronSecurityRule) {
- return HttpURLConnection.HTTP_CREATED;
- }
-
- @Override
- public void neutronSecurityRuleCreated(NeutronSecurityRule neutronSecurityRule) {
- enqueueEvent(new NorthboundEvent(neutronSecurityRule, Action.ADD));
- }
-
- @Override
- public int canUpdateNeutronSecurityRule(NeutronSecurityRule delta, NeutronSecurityRule original) {
- return HttpURLConnection.HTTP_OK;
- }
-
- @Override
- public void neutronSecurityRuleUpdated(NeutronSecurityRule neutronSecurityRule) {
- // Nothing to do
- }
-
- @Override
- public int canDeleteNeutronSecurityRule(NeutronSecurityRule neutronSecurityRule) {
- return HttpURLConnection.HTTP_OK;
- }
-
- @Override
- public void neutronSecurityRuleDeleted(NeutronSecurityRule neutronSecurityRule) {
- enqueueEvent(new NorthboundEvent(neutronSecurityRule, Action.DELETE));
- }
-
- /**
- * Process the event.
- *
- * @param abstractEvent the {@link AbstractEvent} event to be handled.
- * @see EventDispatcher
- */
- @Override
- public void processEvent(AbstractEvent abstractEvent) {
- if (!(abstractEvent instanceof NorthboundEvent)) {
- LOG.error("Unable to process abstract event {}", abstractEvent);
- return;
- }
- NorthboundEvent ev = (NorthboundEvent) abstractEvent;
- switch (ev.getAction()) {
- case ADD:
- processNeutronSecurityRuleAdded(ev.getNeutronSecurityRule());
- break;
- case DELETE:
- processNeutronSecurityRuleDeleted(ev.getNeutronSecurityRule());
- break;
- default:
- LOG.warn("Unable to process event action {}", ev.getAction());
- break;
- }
- }
-
- private void processNeutronSecurityRuleAdded(NeutronSecurityRule neutronSecurityRule) {
- List<NeutronPort> portList = getPortWithSecurityGroup(neutronSecurityRule.getSecurityRuleGroupID());
- Map<String, NodeId> portNodeCache = getPortNodeCache();
- INeutronSecurityGroupCRUD groupCRUD =
- (INeutronSecurityGroupCRUD) ServiceHelper.getGlobalInstance(INeutronSecurityGroupCRUD.class, this);
- NeutronSecurityGroup securityGroup = groupCRUD.getNeutronSecurityGroup(neutronSecurityRule.getSecurityRuleGroupID());
- if (null != portNodeCache) {
- for (NeutronPort port:portList) {
- syncSecurityGroup(neutronSecurityRule, port, portNodeCache.get(port.getID()), securityGroup, true);
- }
- }
-
- }
-
- private void processNeutronSecurityRuleDeleted(NeutronSecurityRule neutronSecurityRule) {
- List<NeutronPort> portList = getPortWithSecurityGroup(neutronSecurityRule.getSecurityRuleGroupID());
- Map<String, NodeId> portNodeCache = getPortNodeCache();
- INeutronSecurityGroupCRUD groupCRUD =
- (INeutronSecurityGroupCRUD) ServiceHelper.getGlobalInstance(INeutronSecurityGroupCRUD.class, this);
- NeutronSecurityGroup securityGroup = groupCRUD.getNeutronSecurityGroup(neutronSecurityRule.getSecurityRuleGroupID());
- if (null != portNodeCache) {
- for (NeutronPort port:portList) {
- syncSecurityGroup(neutronSecurityRule, port, portNodeCache.get(port.getID()), securityGroup, false);
- }
- }
- }
-
- private void syncSecurityGroup(NeutronSecurityRule securityRule, NeutronPort port, NodeId nodeId,
- NeutronSecurityGroup securityGroup, boolean write) {
- LOG.debug("syncSecurityGroup {} port {} ", securityRule, port);
- if (!port.getPortSecurityEnabled()) {
- LOG.info("Port security not enabled port {}", port);
- return;
- }
- if (null != securityRule.getSecurityRemoteGroupID()) {
- List<Neutron_IPs> vmIpList = securityServicesManager
- .getVmListForSecurityGroup(port.getID(), securityRule.getSecurityRemoteGroupID());
-
- // the returned vmIpList contains the list of VMs belong to the remote security group
- // excluding ones on this port.
- // If the list is empty, this port is the first member of the remote security group
- // we need to add/remove from the remote security group cache accordingly
- if (vmIpList.isEmpty()) {
- if (write) {
- securityGroupCacheManger.addToCache(securityRule.getSecurityRemoteGroupID(), port.getPortUUID(), nodeId);
- } else {
- securityGroupCacheManger.removeFromCache(securityRule.getSecurityRemoteGroupID(), port.getPortUUID(), nodeId);
- }
- } else {
- for (Neutron_IPs vmIp : vmIpList) {
- securityServicesManager.syncSecurityRule(port, securityRule, vmIp, nodeId, write);
- }
- }
- } else {
- securityServicesManager.syncSecurityRule(port, securityRule, null, nodeId, write);
- }
- }
-
- private Map<String, NodeId> getPortNodeCache() {
- Map<String, NodeId> portNodeCache = new HashMap();
- List<Node> toplogyNodes = southbound.readOvsdbTopologyNodes();
-
- for (Node topologyNode : toplogyNodes) {
- try {
- Node node = southbound.getBridgeNode(topologyNode,Constants.INTEGRATION_BRIDGE);
- if (node == null) {
- LOG.error("getNode: br-int interface is not found for node:{}", topologyNode.getNodeId().getValue());
- }
- List<OvsdbTerminationPointAugmentation> ovsdbPorts = southbound.getTerminationPointsOfBridge(node);
- for (OvsdbTerminationPointAugmentation ovsdbPort : ovsdbPorts) {
- String uuid = southbound.getInterfaceExternalIdsValue(ovsdbPort,
- Constants.EXTERNAL_ID_INTERFACE_ID);
- NodeId nodeId = node.getNodeId();
- if (null != uuid && null != nodeId) {
- portNodeCache.put(uuid, nodeId);
- }
- }
- } catch (Exception e) {
- LOG.error("Exception during handlingNeutron network delete", e);
- }
- }
- return portNodeCache;
- }
-
- private List<NeutronPort> getPortWithSecurityGroup(String securityGroupUuid) {
-
- List<NeutronPort> neutronPortList = neutronPortCache.getAllPorts();
- List<NeutronPort> neutronPortInSg = new ArrayList<>();
- for (NeutronPort neutronPort:neutronPortList) {
- List<NeutronSecurityGroup> securityGroupList = neutronPort.getSecurityGroups();
- for (NeutronSecurityGroup neutronSecurityGroup:securityGroupList) {
- if (neutronSecurityGroup.getID().equals(securityGroupUuid)) {
- neutronPortInSg.add(neutronPort);
- break;
- }
- }
- }
- return neutronPortInSg;
- }
-
- @Override
- public void setDependencies(ServiceReference serviceReference) {
- eventDispatcher =
- (EventDispatcher) ServiceHelper.getGlobalInstance(EventDispatcher.class, this);
- eventDispatcher.eventHandlerAdded(serviceReference, this);
- southbound =
- (Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this);
- neutronPortCache = (INeutronPortCRUD) ServiceHelper.getGlobalInstance(INeutronPortCRUD.class, this);
- securityServicesManager =
- (SecurityServicesManager) ServiceHelper.getGlobalInstance(SecurityServicesManager.class, this);
- securityGroupCacheManger =
- (SecurityGroupCacheManger) ServiceHelper.getGlobalInstance(SecurityGroupCacheManger.class, this);
- }
-
- @Override
- public void setDependencies(Object impl) {}
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt;
-
-import java.net.HttpURLConnection;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronRouter;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronRouter_Interface;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronRouterAware;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.EventDispatcher;
-import org.opendaylight.netvirt.openstack.netvirt.impl.NeutronL3Adapter;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Handle requests for Neutron Router.
- */
-public class RouterHandler extends AbstractHandler implements INeutronRouterAware, ConfigInterface {
- private static final Logger LOG = LoggerFactory.getLogger(RouterHandler.class);
-
- // The implementation for each of these services is resolved by the OSGi Service Manager
- private volatile NeutronL3Adapter neutronL3Adapter;
-
- /**
- * Services provide this interface method to indicate if the specified router can be created
- *
- * @param router
- * instance of proposed new Neutron Router object
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the create operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- @Override
- public int canCreateRouter(NeutronRouter router) {
- return HttpURLConnection.HTTP_OK;
- }
-
- /**
- * Services provide this interface method for taking action after a router has been created
- *
- * @param router
- * instance of new Neutron Router object
- */
- @Override
- public void neutronRouterCreated(NeutronRouter router) {
- enqueueEvent(new NorthboundEvent(router, Action.ADD));
- }
-
- /**
- * Services provide this interface method to indicate if the specified router can be changed using the specified
- * delta
- *
- * @param delta
- * updates to the router object using patch semantics
- * @param original
- * instance of the Neutron Router object to be updated
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the update operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- @Override
- public int canUpdateRouter(NeutronRouter delta, NeutronRouter original) {
- return HttpURLConnection.HTTP_OK;
- }
-
- /**
- * Services provide this interface method for taking action after a router has been updated
- *
- * @param router
- * instance of modified Neutron Router object
- */
- @Override
- public void neutronRouterUpdated(NeutronRouter router) {
- enqueueEvent(new NorthboundEvent(router, Action.UPDATE));
- }
-
- /**
- * Services provide this interface method to indicate if the specified router can be deleted
- *
- * @param router
- * instance of the Neutron Router object to be deleted
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the delete operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- @Override
- public int canDeleteRouter(NeutronRouter router) {
- return HttpURLConnection.HTTP_OK;
- }
-
- /**
- * Services provide this interface method for taking action after a router has been deleted
- *
- * @param router
- * instance of deleted Router Network object
- */
- @Override
- public void neutronRouterDeleted(NeutronRouter router) {
- enqueueEvent(new NorthboundEvent(router, Action.DELETE));
- }
-
- /**
- * Services provide this interface method to indicate if the specified interface can be attached to the specified
- * route
- *
- * @param router
- * instance of the base Neutron Router object
- * @param routerInterface
- * instance of the NeutronRouter_Interface to be attached to the router
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the attach operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- @Override
- public int canAttachInterface(NeutronRouter router, NeutronRouter_Interface routerInterface) {
- LOG.debug(" Router {} asked if it can attach interface {}. Subnet {}",
- router.getName(),
- routerInterface.getPortUUID(),
- routerInterface.getSubnetUUID());
- return HttpURLConnection.HTTP_OK;
- }
-
- /**
- * Services provide this interface method for taking action after an interface has been added to a router
- *
- * @param router
- * instance of the base Neutron Router object
- * @param routerInterface
- * instance of the NeutronRouter_Interface being attached to the router
- */
- @Override
- public void neutronRouterInterfaceAttached(NeutronRouter router, NeutronRouter_Interface routerInterface) {
- enqueueEvent(new NorthboundEvent(router, routerInterface, Action.ADD));
- }
-
- /**
- * Services provide this interface method to indicate if the specified interface can be detached from the specified
- * router
- *
- * @param router
- * instance of the base Neutron Router object
- * @param routerInterface
- * instance of the NeutronRouter_Interface to be detached to the router
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the detach operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- @Override
- public int canDetachInterface(NeutronRouter router, NeutronRouter_Interface routerInterface) {
- LOG.debug(" Router {} asked if it can detach interface {}. Subnet {}",
- router.getName(),
- routerInterface.getPortUUID(),
- routerInterface.getSubnetUUID());
-
- return HttpURLConnection.HTTP_OK;
- }
-
- /**
- * Services provide this interface method for taking action after an interface has been removed from a router
- *
- * @param router
- * instance of the base Neutron Router object
- * @param routerInterface
- * instance of the NeutronRouter_Interface being detached from the router
- */
- @Override
- public void neutronRouterInterfaceDetached(NeutronRouter router, NeutronRouter_Interface routerInterface) {
- enqueueEvent(new NorthboundEvent(router, routerInterface, Action.DELETE));
- }
-
- /**
- * Process the event.
- *
- * @param abstractEvent the {@link AbstractEvent} event to be handled.
- * @see EventDispatcher
- */
- @Override
- public void processEvent(AbstractEvent abstractEvent) {
- if (!(abstractEvent instanceof NorthboundEvent)) {
- LOG.error("Unable to process abstract event {}", abstractEvent);
- return;
- }
- NorthboundEvent ev = (NorthboundEvent) abstractEvent;
- switch (ev.getAction()) {
- case ADD:
- // fall through
- case DELETE:
- // fall through
- case UPDATE:
- if (ev.getRouterInterface() == null) {
- neutronL3Adapter.handleNeutronRouterEvent(ev.getRouter(), ev.getAction());
- } else {
- neutronL3Adapter.handleNeutronRouterInterfaceEvent(ev.getRouter(),
- ev.getRouterInterface(),
- ev.getAction());
- }
- break;
- default:
- LOG.warn("Unable to process event action {}", ev.getAction());
- break;
- }
- }
-
- @Override
- public void setDependencies(ServiceReference serviceReference) {
- neutronL3Adapter =
- (NeutronL3Adapter) ServiceHelper.getGlobalInstance(NeutronL3Adapter.class, this);
- eventDispatcher =
- (EventDispatcher) ServiceHelper.getGlobalInstance(EventDispatcher.class, this);
- eventDispatcher.eventHandlerAdded(serviceReference, this);
- }
-
- @Override
- public void setDependencies(Object impl) {}
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt;
-
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation;
-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.DataObject;
-
-public class SouthboundEvent extends AbstractEvent {
- public enum Type { NODE, OPENVSWITCH, BRIDGE, CONTROLLER, PORT }
- private Type type;
- private Node node;
- private String tableName;
- private String uuid;
- private Object context;
- private DataObject augmentationData;
- private OvsdbBridgeAugmentation bridge;
- private OvsdbTerminationPointAugmentation port;
- private String portName;
- public SouthboundEvent(Node node, Action action) {
- super(HandlerType.SOUTHBOUND, action);
- this.type = Type.NODE;
- this.node = node;
- }
- public SouthboundEvent(Node node, OvsdbBridgeAugmentation bridge, Action action) {
- super(HandlerType.SOUTHBOUND, action);
- this.type = Type.BRIDGE;
- this.node = node;
- this.bridge = bridge;
- }
- public SouthboundEvent(Node node, OvsdbTerminationPointAugmentation port, String portName, Action action) {
- super(HandlerType.SOUTHBOUND, action);
- this.type = Type.PORT;
- this.node = node;
- this.port = port;
- this.portName = portName;
- }
-
- public SouthboundEvent(Node node, Type type, Action action) {
- super(HandlerType.SOUTHBOUND, action);
- this.type = type;
- this.node = node;
- }
-
- public SouthboundEvent(Node node, DataObject resourceAugmentationData, Type type, Action action) {
- super(HandlerType.SOUTHBOUND, action);
- this.type = type;
- this.node = node;
- this.augmentationData = resourceAugmentationData;
- }
-
-
- public Type getType() {
- return type;
- }
- public Node getNode() {
- return node;
- }
- public String getTableName() {
- return tableName;
- }
- public String getUuid() {
- return uuid;
- }
- public Object getContext() {
- return context;
- }
- public OvsdbBridgeAugmentation getBridge() {
- return bridge;
- }
- public OvsdbTerminationPointAugmentation getPort() {
- return port;
- }
- public String getPortName() {
- return portName;
- }
-
- public DataObject getAugmentationData() {
- return augmentationData;
- }
-
- @Override
- public String toString() {
- //if (type == Type.NODE) {
- return "SouthboundEvent [type=" + type
- + ", action=" + super.getAction()
- + ", augmentationData=" + augmentationData
- + ", node=" + node + "]";
- //} else {
- // return "SouthboundEvent [type=" + type + "]";
- //}
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = super.hashCode();
- result = prime * result + ((node == null) ? 0 : node.hashCode());
- result = prime * result + ((tableName == null) ? 0 : tableName.hashCode());
- result = prime * result + ((type == null) ? 0 : type.hashCode());
- result = prime * result + ((uuid == null) ? 0 : uuid.hashCode());
- result = prime * result + ((augmentationData == null) ? 0 : augmentationData.hashCode());
- return result;
- }
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- if (!super.equals(obj)) {
- return false;
- }
- SouthboundEvent other = (SouthboundEvent) obj;
- if (node == null) {
- if (other.node != null) {
- return false;
- }
- } else if (!node.equals(other.node)) {
- return false;
- }
- if (tableName == null) {
- if (other.tableName != null) {
- return false;
- }
- } else if (!tableName.equals(other.tableName)) {
- return false;
- }
- if (type == null) {
- if (other.type != null) {
- return false;
- }
- } else if (!type.equals(other.type)) {
- return false;
- }
- if (uuid == null) {
- if (other.uuid != null) {
- return false;
- }
- } else if (!uuid.equals(other.uuid)) {
- return false;
- }
- return true;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt;
-
-import java.net.InetAddress;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
-import org.apache.commons.lang3.tuple.Pair;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.BridgeConfigurationManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.ConfigurationService;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-import org.opendaylight.netvirt.openstack.netvirt.api.EventDispatcher;
-import org.opendaylight.netvirt.openstack.netvirt.api.L2ForwardingProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.NetworkingProviderManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheListener;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.OvsdbInventoryListener;
-import org.opendaylight.netvirt.openstack.netvirt.api.OvsdbInventoryService;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.openstack.netvirt.api.TenantNetworkManager;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronNetworkCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.impl.DistributedArpService;
-import org.opendaylight.netvirt.openstack.netvirt.impl.NeutronL3Adapter;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeVxlan;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbTerminationPointAugmentation;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.Options;
-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.node.TerminationPoint;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * @author Madhu Venugopal
- * @author Brent Salisbury
- * @author Dave Tucker
- * @author Sam Hague (shague@redhat.com)
- */
-public class SouthboundHandler extends AbstractHandler
- implements ConfigInterface, NodeCacheListener, OvsdbInventoryListener {
- private static final Logger LOG = LoggerFactory.getLogger(SouthboundHandler.class);
-
- // The implementation for each of these services is resolved by the OSGi Service Manager
- private volatile ConfigurationService configurationService;
- private volatile BridgeConfigurationManager bridgeConfigurationManager;
- private volatile TenantNetworkManager tenantNetworkManager;
- private volatile NetworkingProviderManager networkingProviderManager;
- private volatile NeutronL3Adapter neutronL3Adapter;
- private volatile DistributedArpService distributedArpService;
- private volatile NodeCacheManager nodeCacheManager;
- private volatile INeutronNetworkCRUD neutronNetworkCache;
- private volatile OvsdbInventoryService ovsdbInventoryService;
- private volatile Southbound southbound;
- private volatile VLANProvider vlanProvider;
- private volatile L2ForwardingProvider l2ForwardingProvider;
-
- private SouthboundEvent.Type ovsdbTypeToSouthboundEventType(OvsdbType ovsdbType) {
- SouthboundEvent.Type type = SouthboundEvent.Type.NODE;
-
- switch (ovsdbType) {
- case NODE:
- type = SouthboundEvent.Type.NODE;
- break;
- case BRIDGE:
- type = SouthboundEvent.Type.BRIDGE;
- break;
- case PORT:
- type = SouthboundEvent.Type.PORT;
- break;
- case CONTROLLER:
- type = SouthboundEvent.Type.CONTROLLER;
- break;
- case OPENVSWITCH:
- type = SouthboundEvent.Type.OPENVSWITCH;
- break;
- default:
- LOG.warn("Invalid OvsdbType: {}", ovsdbType);
- break;
- }
- return type;
- }
-
- @Override
- public void ovsdbUpdate(Node node, DataObject resourceAugmentationData, OvsdbType ovsdbType, Action action) {
- LOG.debug("Received ovsdbUpdate for : {} with action : {} for the OVS node : {} Resource Data : {}",
- ovsdbType, action, node, resourceAugmentationData);
- enqueueEvent(new SouthboundEvent(node, resourceAugmentationData,
- ovsdbTypeToSouthboundEventType(ovsdbType), action));
- }
-
- private void handleInterfaceUpdate (Node node, OvsdbTerminationPointAugmentation tp, Action action) {
- NeutronNetwork network = tenantNetworkManager.getTenantNetwork(tp);
- if (network != null && !network.getRouterExternal()) {
- LOG.trace("InterfaceUpdate for OVS Node :{} OvsdbTerminationPointAugmentation :" + " {} for the network : {}", node, tp, network.getNetworkUUID());
- if (bridgeConfigurationManager.createLocalNetwork(node, network)) {
- networkingProviderManager.getProvider(node).handleInterfaceUpdate(network, node, tp);
- }
- } else {
- LOG.debug("No tenant network found on node : {} for interface: {}", node, tp);
- }
- if (action.equals(Action.UPDATE)) {
- distributedArpService.processInterfaceEvent(node, tp, network, false, action);
- }
- neutronL3Adapter.handleInterfaceEvent(node, tp, network, action);
- }
- /**
- * Get dpid from node.
- *
- * @param node the {@link Node Node} of interest in the notification
- * @return dpid value
- */
- private Long getDpidForIntegrationBridge(Node node) {
- // Check if node is integration bridge; and only then return its dpid
- if (southbound.getBridge(node, configurationService.getIntegrationBridgeName()) != null) {
- return southbound.getDataPathId(node);
- }
- return null;
- }
-
- /**
- * Returns true, if the port is migrated else false.
- *
- * @param node the node associated with Neutron Port.
- * @param neutronPort the port details.
- * @return boolean true, if the port is migrated else false.
- */
- private boolean isMigratedPort(Node node, NeutronPort neutronPort) {
- boolean isMigratedPort = false;
- final Long dpId = getDpidForIntegrationBridge(node);
- final Pair<Long, Uuid> nodeDpIdPair = neutronL3Adapter.getDpIdOfNeutronPort(neutronPort.getPortUUID());
- Long dpIdNeutronPort = (nodeDpIdPair == null ? null : nodeDpIdPair.getLeft());
- if(dpIdNeutronPort != null && !dpIdNeutronPort.equals(dpId)) {
- isMigratedPort = true;
- }
- LOG.trace("isMigratedPort {}, node {}, neutronPort {}, dpIdNeutronPort {} ", isMigratedPort, node.getNodeId(),
- neutronPort.getMacAddress(), dpIdNeutronPort);
- return isMigratedPort;
- }
-
- private void handleInterfaceDelete (Node node, OvsdbTerminationPointAugmentation intf,
- boolean isLastInstanceOnNode, NeutronNetwork network) {
- LOG.debug("handleInterfaceDelete: node: <{}>, isLastInstanceOnNode: {}, interface: <{}>",
- node, isLastInstanceOnNode, intf);
-
- final NeutronPort neutronPort = tenantNetworkManager.getTenantPort(intf);
- boolean isMigratedPort = isMigratedPort(node, neutronPort);
- distributedArpService.processInterfaceEvent(node, intf, network, isMigratedPort, Action.DELETE);
- neutronL3Adapter.handleInterfaceEvent(node, intf, network, Action.DELETE);
- programVLANNetworkFlowProvider(node, intf, network, neutronPort, false);
- List<String> phyIfName = bridgeConfigurationManager.getAllPhysicalInterfaceNames(node);
- if (isInterfaceOfInterest(intf, phyIfName)) {
- // delete tunnel or physical interfaces
- networkingProviderManager.getProvider(node).handleInterfaceDelete(network.getProviderNetworkType(),
- network, node, intf, isLastInstanceOnNode, isMigratedPort);
- } else if (network != null) {
- // vlan doesn't need a tunnel endpoint
- if (!network.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VLAN) &&
- configurationService.getTunnelEndPoint(node) == null) {
- LOG.error("Tunnel end-point configuration missing. Please configure it in OpenVSwitch Table");
- return;
- }
- networkingProviderManager.getProvider(node).handleInterfaceDelete(network.getProviderNetworkType(),
- network, node, intf, isLastInstanceOnNode, isMigratedPort);
- }
-
- }
-
- @Override
- public void triggerUpdates() {
- List<Node> ovsdbNodes = southbound.readOvsdbTopologyNodes();
- for (Node node : ovsdbNodes) {
- ovsdbUpdate(node, node.getAugmentation(OvsdbNodeAugmentation.class),
- OvsdbInventoryListener.OvsdbType.NODE, Action.ADD);
- }
- }
-
- private void processPortDelete(Node node, OvsdbTerminationPointAugmentation ovsdbTerminationPointAugmentation,
- Object context) {
- LOG.debug("processPortDelete for Node : {} ovsdbTerminationPointAugmentation : {}",
- node, ovsdbTerminationPointAugmentation);
- NeutronNetwork network;
- if (context == null) {
- network = tenantNetworkManager.getTenantNetwork(ovsdbTerminationPointAugmentation);
- } else {
- network = (NeutronNetwork)context;
- }
- List<String> phyIfName = bridgeConfigurationManager.getAllPhysicalInterfaceNames(node);
- if (isInterfaceOfInterest(ovsdbTerminationPointAugmentation, phyIfName)) {
- if (network != null) {
- this.handleInterfaceDelete(node, ovsdbTerminationPointAugmentation, false, network);
- } else {
- LOG.warn("processPortDelete: network was null, ignoring update");
- }
- } else if (network != null && !network.getRouterExternal()) {
- LOG.debug("Network {}: Delete interface {} attached to bridge {}", network.getNetworkUUID(),
- ovsdbTerminationPointAugmentation.getInterfaceUuid(), node.getNodeId());
- try {
- OvsdbBridgeAugmentation ovsdbBridgeAugmentation = southbound.getBridge(node);
- if (ovsdbBridgeAugmentation != null) {
- List<TerminationPoint> terminationPoints = node.getTerminationPoint();
- if (!terminationPoints.isEmpty()){
- boolean isLastInstanceOnNode = true;
- for (TerminationPoint terminationPoint : terminationPoints) {
- OvsdbTerminationPointAugmentation tpAugmentation =
- terminationPoint.getAugmentation( OvsdbTerminationPointAugmentation.class);
- if (tpAugmentation.getInterfaceUuid().equals(
- ovsdbTerminationPointAugmentation.getInterfaceUuid())) {
- continue;
- }
- NeutronNetwork neutronNetwork = tenantNetworkManager.getTenantNetwork(tpAugmentation);
- if (neutronNetwork != null) {
- String neutronNetworkSegId = neutronNetwork.getProviderSegmentationID();
- String networkSegId = network.getProviderSegmentationID();
- // vxlan ports should not be removed in table 110 flow entry
- // unless last VM instance removed from the openstack node(Bug# 5813)
- if (neutronNetworkSegId != null && neutronNetworkSegId.equals(networkSegId)) {
- isLastInstanceOnNode = false;
- break;
- }
- }
- }
- this.handleInterfaceDelete(node, ovsdbTerminationPointAugmentation,
- isLastInstanceOnNode, network);
- }
- }
- } catch (Exception e) {
- LOG.error("Error fetching Interface Rows for node {}", node, e);
- }
- } else if (network != null && network.getRouterExternal()) {
- this.handleInterfaceDelete(node, ovsdbTerminationPointAugmentation, false, network);
- }
- //remove neutronPort from the CleanupCache, if it has the entry.
- NeutronPort neutronPort = null;
- String neutronPortId = southbound.getInterfaceExternalIdsValue(ovsdbTerminationPointAugmentation,
- Constants.EXTERNAL_ID_INTERFACE_ID);
- if (neutronPortId != null) {
- LOG.trace("Clean up the NeutronPortCache for {} ", neutronPortId);
- neutronPort = neutronL3Adapter.getPortFromCleanupCache(neutronPortId);
- }
- if (neutronPort != null) {
- LOG.debug("Clean up the NeutronPortCache ");
- neutronL3Adapter.removePortFromCleanupCache(neutronPort);
- neutronL3Adapter.removeNetworkFromCleanupCache(neutronPort.getNetworkUUID());
- } else {
- LOG.trace("Nothing to Clean up in the NeutronPortCache ");
- }
-
- }
-
- private boolean isInterfaceOfInterest(OvsdbTerminationPointAugmentation terminationPoint, List<String> phyIfName) {
- LOG.trace("SouthboundHandler#isInterfaceOfInterest: Interface : {}", terminationPoint);
-
- if(terminationPoint.getInterfaceType() == null){
- // This is OK since eth ports don't have an interface type
- return false;
- }
- return MdsalHelper.createOvsdbInterfaceType(
- terminationPoint.getInterfaceType()).equals(NetworkHandler.NETWORK_TYPE_VXLAN)
- ||
- MdsalHelper.createOvsdbInterfaceType(
- terminationPoint.getInterfaceType()).equals(NetworkHandler.NETWORK_TYPE_GRE)
- ||
- phyIfName.contains(terminationPoint.getName());
- }
-
- /**
- * Notification about an OpenFlow Node
- *
- * @param node the {@link Node Node} of interest in the notification
- * @param action the {@link Action}
- * @see NodeCacheListener#notifyNode
- */
- @Override
- public void notifyNode (Node node, Action action) {
- LOG.trace("notifyNode : action: {}, Node : {} ", action, node);
-
- if ((action == Action.ADD) && (southbound.getBridge(node) != null)) {
- networkingProviderManager.getProvider(node).initializeOFFlowRules(node);
- }
- }
-
- /**
- * Process the event.
- *
- * @param abstractEvent the {@link AbstractEvent} event to be handled.
- * @see EventDispatcher
- */
- @Override
- public void processEvent(AbstractEvent abstractEvent) {
- if (!(abstractEvent instanceof SouthboundEvent)) {
- LOG.error("processEvent Unable to process abstract event : {}", abstractEvent);
- return;
- }
- SouthboundEvent ev = (SouthboundEvent) abstractEvent;
- LOG.trace("processEvent : {} for TransactionId : {}", ev, ev.getTransactionId());
- switch (ev.getType()) {
- case NODE:
- processOvsdbNodeEvent(ev);
- break;
-
- case BRIDGE:
- processBridgeEvent(ev);
- break;
-
- case PORT:
- processPortEvent(ev);
- break;
-
- case OPENVSWITCH:
- processOpenVSwitchEvent(ev);
- break;
-
- default:
- LOG.warn("Unable to process type : {} action : {} for node : {}", ev.getType(), ev.getAction(), ev.getNode());
- break;
- }
- LOG.trace("processEvent exit : {} for TransactionId : {}", ev, ev.getTransactionId());
- }
-
- private void processOvsdbNodeEvent(SouthboundEvent ev) {
- switch (ev.getAction()) {
- case ADD:
- processOvsdbNodeCreate(ev.getNode(), (OvsdbNodeAugmentation) ev.getAugmentationData());
- break;
- case UPDATE:
- processOvsdbNodeUpdate(ev.getNode(), (OvsdbNodeAugmentation) ev.getAugmentationData());
- break;
- case DELETE:
- processOvsdbNodeDelete(ev.getNode(), (OvsdbNodeAugmentation) ev.getAugmentationData());
- break;
- }
- }
-
- private void processOvsdbNodeCreate(Node node, OvsdbNodeAugmentation ovsdbNode) {
- LOG.info("processOvsdb Node Create : {} ", ovsdbNode);
- nodeCacheManager.nodeAdded(node);
- bridgeConfigurationManager.prepareNode(node);
- }
-
- private void processOvsdbNodeUpdate(Node node, OvsdbNodeAugmentation ovsdbNode) {
- LOG.info("processOvsdb Node Update : {} ", ovsdbNode);
- nodeCacheManager.nodeAdded(node);
- }
-
- private void processOvsdbNodeDelete(Node node, OvsdbNodeAugmentation ovsdbNode) {
- LOG.info("processOvsdb Node Delete : {} ", ovsdbNode);
- nodeCacheManager.nodeRemoved(node);
- /* TODO SB_MIGRATION
- * I don't think we want to do this yet
- InstanceIdentifier<Node> bridgeNodeIid =
- MdsalHelper.createInstanceIdentifier(ovsdbNode.getConnectionInfo(),
- Constants.INTEGRATION_BRIDGE);
- southbound.delete(LogicalDatastoreType.CONFIGURATION, bridgeNodeIid);
- */
- }
-
- private void processPortEvent(SouthboundEvent ev) {
- switch (ev.getAction()) {
- case ADD:
- case UPDATE:
- processPortUpdate(ev.getNode(), (OvsdbTerminationPointAugmentation) ev.getAugmentationData(), ev.getAction());
- break;
- case DELETE:
- processPortDelete(ev.getNode(), (OvsdbTerminationPointAugmentation) ev.getAugmentationData(), null);
- break;
- }
- }
-
- private void processPortUpdate(Node node, OvsdbTerminationPointAugmentation port, Action action) {
- LOG.debug("processPortUpdate : action {}, {} for the Node: {}", action, port, node);
- NeutronNetwork network = tenantNetworkManager.getTenantNetwork(port);
- if (network != null) {
- final NeutronPort neutronPort = tenantNetworkManager.getTenantPort(port);
- if (!(Action.UPDATE.equals(action) && isMigratedPort(node, neutronPort))) {
- if (!network.getRouterExternal()) {
- handleInterfaceUpdate(node, port, action);
- } else if (Action.UPDATE.equals(action)) {
- programVLANNetworkFlowProvider(node, port, network, neutronPort, true);
- }
- }
- } else if (null != port.getInterfaceType() && null != port.getOfport()) {
- // Filter Vxlan interface request and install table#110 unicast flow (Bug 7392).
- if(port.getInterfaceType().equals(InterfaceTypeVxlan.class)) {
- List<Options> optionList = port.getOptions();
- if (null != optionList && !optionList.isEmpty()) {
- optionList.stream().filter(option -> isRemoteIp(option)).forEach(option ->
- handleTunnelOut(node, option.getValue(), port.getOfport()));
- }
- }
- }
- }
-
- private boolean isRemoteIp(Options option) {
- return option.getOption().equals(Constants.TUNNEL_ENDPOINT_KEY_REMOTE);
- }
-
- private void handleTunnelOut(Node node, String remoteIp, Long ofPort) {
- List<Node> nodes = nodeCacheManager.getBridgeNodes();
- if (null != nodes && !nodes.isEmpty()) {
- nodes.stream().filter(dstnode -> isDstNode(node, dstnode, remoteIp)).forEach(dstnode ->
- programTunnelOut(node, dstnode, ofPort));
- }
- }
-
- private boolean isDstNode(Node node, Node dstnode, String remoteIp) {
- if (!(node.getNodeId().getValue().equals(dstnode.getNodeId().getValue()))) {
- InetAddress dst = configurationService.getTunnelEndPoint(dstnode);
- String dstIp = dst.getHostAddress();
- if (remoteIp.equals(dstIp)) {
- return true;
- }
- }
- return false;
- }
-
- private void programTunnelOut(Node node, Node dstnode, Long ofPort) {
- List<OvsdbTerminationPointAugmentation> ports = southbound.readTerminationPointAugmentations(dstnode);
- for (OvsdbTerminationPointAugmentation destport : ports) {
- NeutronPort neutronPort = tenantNetworkManager.getTenantPort(destport);
- if (neutronPort != null) {
- final String networkUUID = neutronPort.getNetworkUUID();
- NeutronNetwork neutronNetwork = neutronNetworkCache.getNetwork(networkUUID);
- if (null == neutronNetwork) {
- neutronNetwork = neutronL3Adapter.getNetworkFromCleanupCache(networkUUID);
- }
- final String segmentationId = neutronNetwork != null ? neutronNetwork.getProviderSegmentationID() : null;
- final String macAddress = neutronPort.getMacAddress();
- long dpid = getIntegrationBridgeOFDPID(node);
- if (null != l2ForwardingProvider) {
- l2ForwardingProvider.programTunnelOut(dpid, segmentationId, ofPort, macAddress, true);
- }
- }
- }
- }
-
- private long getIntegrationBridgeOFDPID(Node node) {
- long dpid = 0L;
- if (southbound.getBridgeName(node).equals(configurationService.getIntegrationBridgeName())) {
- dpid = southbound.getDataPathId(node);
- }
- return dpid;
- }
-
- private void programVLANNetworkFlowProvider(final Node node, final OvsdbTerminationPointAugmentation port,
- final NeutronNetwork network, final NeutronPort neutronPort, final Boolean isWrite) {
- if (neutronPort != null && neutronPort.getDeviceOwner().equalsIgnoreCase(Constants.OWNER_ROUTER_GATEWAY) &&
- network.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VLAN) &&
- configurationService.isL3MultipleExternalNetworkEnabled()) {
- vlanProvider.programProviderNetworkFlow(node, port, network, neutronPort, isWrite);
- }
- }
-
- private void processOpenVSwitchEvent(SouthboundEvent ev) {
- switch (ev.getAction()) {
- case ADD:
- case UPDATE:
- processOpenVSwitchUpdate(ev.getNode());
- break;
- case DELETE:
- break;
- }
- }
-
- private void processOpenVSwitchUpdate(Node node) {
- LOG.debug("processOpenVSwitchUpdate : {}", node);
- // TODO this node might be the OvsdbNode and not have termination points
- // Would need to change listener or grab tp nodes in here.
- List<TerminationPoint> terminationPoints = southbound.extractTerminationPoints(node);
- for (TerminationPoint terminationPoint : terminationPoints) {
- processPortUpdate(node, terminationPoint.getAugmentation(OvsdbTerminationPointAugmentation.class), null);
- }
- }
-
- private void processBridgeEvent(SouthboundEvent ev) {
- switch (ev.getAction()) {
- case ADD:
- processBridgeCreate(ev.getNode(), (OvsdbBridgeAugmentation) ev.getAugmentationData());
- break;
- case UPDATE:
- processBridgeUpdate(ev.getNode(), (OvsdbBridgeAugmentation) ev.getAugmentationData());
- break;
- case DELETE:
- processBridgeDelete(ev.getNode(), (OvsdbBridgeAugmentation) ev.getAugmentationData());
- break;
- }
- }
-
- private void processBridgeCreate(Node node, OvsdbBridgeAugmentation bridge) {
- LOG.debug("BridgeCreate : {} for the Node : {}", bridge, node);
- String datapathId = southbound.getDatapathId(bridge);
- // Having a datapathId means the ovsdb node has connected to ODL
- if (datapathId != null) {
- nodeCacheManager.nodeAdded(node);
- } else {
- LOG.debug("processBridgeCreate datapathId not found");
- }
- }
-
- private void processBridgeUpdate(Node node, OvsdbBridgeAugmentation bridge) {
- LOG.debug("BridgeUpdate : {} for the node : {}", bridge, node);
- String datapathId = southbound.getDatapathId(bridge);
- // Having a datapathId means the ovsdb node has connected to ODL
- if (datapathId != null) {
- nodeCacheManager.nodeAdded(node);
- } else {
- LOG.debug("processBridgeUpdate datapathId not found");
- }
- }
-
- private void processBridgeDelete(Node node, OvsdbBridgeAugmentation bridge) {
- LOG.debug("BridgeDelete: Delete bridge from config data store : {}"
- +"Node : {}", bridge, node);
- nodeCacheManager.nodeRemoved(node);
-
- // Currently we only do not remove the integration bridge from configDS, which resolves
- // bug 7461 where upon a rapid connection flap, the integration bridge is sometimes
- // removed from the device due to ODL asynchronous processing of the connection flap.
- if (bridge.getBridgeName() != null &&
- !bridge.getBridgeName().getValue().equals(configurationService.getIntegrationBridgeName())) {
- southbound.deleteBridge(node);
- }
- }
- @Override
- public void setDependencies(ServiceReference serviceReference) {
- configurationService =
- (ConfigurationService) ServiceHelper.getGlobalInstance(ConfigurationService.class, this);
- networkingProviderManager =
- (NetworkingProviderManager) ServiceHelper.getGlobalInstance(NetworkingProviderManager.class, this);
- tenantNetworkManager =
- (TenantNetworkManager) ServiceHelper.getGlobalInstance(TenantNetworkManager.class, this);
- bridgeConfigurationManager =
- (BridgeConfigurationManager) ServiceHelper.getGlobalInstance(BridgeConfigurationManager.class, this);
- nodeCacheManager =
- (NodeCacheManager) ServiceHelper.getGlobalInstance(NodeCacheManager.class, this);
- nodeCacheManager.cacheListenerAdded(serviceReference, this);
- neutronL3Adapter =
- (NeutronL3Adapter) ServiceHelper.getGlobalInstance(NeutronL3Adapter.class, this);
- distributedArpService =
- (DistributedArpService) ServiceHelper.getGlobalInstance(DistributedArpService.class, this);
- southbound =
- (Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this);
- eventDispatcher =
- (EventDispatcher) ServiceHelper.getGlobalInstance(EventDispatcher.class, this);
- eventDispatcher.eventHandlerAdded(serviceReference, this);
- ovsdbInventoryService =
- (OvsdbInventoryService) ServiceHelper.getGlobalInstance(OvsdbInventoryService.class, this);
- ovsdbInventoryService.listenerAdded(this);
- vlanProvider =
- (VLANProvider) ServiceHelper.getGlobalInstance(VLANProvider.class, this);
- l2ForwardingProvider =
- (L2ForwardingProvider) ServiceHelper.getGlobalInstance(L2ForwardingProvider.class, this);
- }
-
- @Override
- public void setDependencies(Object impl) {
- if (impl instanceof INeutronNetworkCRUD) {
- neutronNetworkCache = (INeutronNetworkCRUD)impl;
- } else if (impl instanceof L2ForwardingProvider) {
- l2ForwardingProvider = (L2ForwardingProvider)impl;
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt;
-
-import java.net.HttpURLConnection;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSubnet;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronSubnetAware;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.EventDispatcher;
-import org.opendaylight.netvirt.openstack.netvirt.impl.NeutronL3Adapter;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Preconditions;
-
-public class SubnetHandler extends AbstractHandler implements INeutronSubnetAware, ConfigInterface {
-
- private static final Logger LOG = LoggerFactory.getLogger(SubnetHandler.class);
-
- // The implementation for each of these services is resolved by the OSGi Service Manager
- private volatile NeutronL3Adapter neutronL3Adapter;
-
- @Override
- public int canCreateSubnet(NeutronSubnet subnet) {
- return HttpURLConnection.HTTP_OK;
- }
-
- @Override
- public void neutronSubnetCreated(NeutronSubnet subnet) {
- enqueueEvent(new NorthboundEvent(subnet, Action.ADD));
- }
-
- @Override
- public int canUpdateSubnet(NeutronSubnet delta, NeutronSubnet original) {
- return HttpURLConnection.HTTP_OK;
- }
-
- @Override
- public void neutronSubnetUpdated(NeutronSubnet subnet) {
- enqueueEvent(new NorthboundEvent(subnet, Action.UPDATE));
- }
-
- @Override
- public int canDeleteSubnet(NeutronSubnet subnet) {
- return HttpURLConnection.HTTP_OK;
- }
-
- @Override
- public void neutronSubnetDeleted(NeutronSubnet subnet) {
- enqueueEvent(new NorthboundEvent(subnet, Action.DELETE));
- }
-
- /**
- * Process the event.
- *
- * @param abstractEvent the {@link AbstractEvent} event to be handled.
- * @see EventDispatcher
- */
- @Override
- public void processEvent(AbstractEvent abstractEvent) {
- if (!(abstractEvent instanceof NorthboundEvent)) {
- LOG.error("Unable to process abstract event {}", abstractEvent);
- return;
- }
- NorthboundEvent ev = (NorthboundEvent) abstractEvent;
- switch (ev.getAction()) {
- case ADD:
- // fall through
- case DELETE:
- // fall through
- case UPDATE:
- Preconditions.checkNotNull(neutronL3Adapter);
- neutronL3Adapter.handleNeutronSubnetEvent(ev.getSubnet(), ev.getAction());
- break;
- default:
- LOG.warn("Unable to process event action {}", ev.getAction());
- break;
- }
- }
-
- @Override
- public void setDependencies(ServiceReference serviceReference) {
- neutronL3Adapter =
- (NeutronL3Adapter) ServiceHelper.getGlobalInstance(NeutronL3Adapter.class, this);
- eventDispatcher =
- (EventDispatcher) ServiceHelper.getGlobalInstance(EventDispatcher.class, this);
- eventDispatcher.eventHandlerAdded(serviceReference, this);
- }
-
- @Override
- public void setDependencies(Object impl) {
-
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 NEC Corporation 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.netvirt.openstack.netvirt;
-
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.opendaylight.netvirt.openstack.netvirt.api.ConfigurationService;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.VlanResponderProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.openstack.netvirt.impl.NeutronL3Adapter;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronNetworkCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronPortCRUD;
-import org.opendaylight.netvirt.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.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPoint;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Preconditions;
-
-/**
- * This class is used to add the flows when l3 is disabled in the ODL.
- */
-public class VLANProvider implements ConfigInterface {
- private final Logger LOG = LoggerFactory.getLogger(VLANProvider.class);
-
- // The implementation for each of these services is resolved by the OSGi Service Manager
- private volatile ConfigurationService configurationService;
- private volatile NodeCacheManager nodeCacheManager;
- private volatile VlanResponderProvider vlanResponderProvider;
- private volatile INeutronNetworkCRUD neutronNetworkCache;
- private volatile INeutronPortCRUD neutronPortCache;
- private Southbound southbound;
- private volatile NeutronL3Adapter neutronL3Adapter;
- private Map<String, Set<String>> vlanProviderCache = new ConcurrentHashMap<>();
- private volatile boolean isCachePopulationDone = false;
-
- public void programProviderNetworkFlow(Node envNode, OvsdbTerminationPointAugmentation port, NeutronNetwork network,
- NeutronPort neutronPort, Boolean write) {
- try {
- final String brExt = configurationService.getExternalBridgeName();
- final String portNameInt = getPatchPortName(brExt);
- final String portNameExt = Constants.PATCH_PORT_TO_INTEGRATION_BRIDGE_NAME;
- Long ofPort = port.getOfport();
- String macAddress = neutronPort.getMacAddress();
- final Long dpIdInt = getDpidForIntegrationBridge(envNode, portNameInt);
- final Long dpIdExt = getDpidForExternalBridge();
- Long patchIntPort = getPatchPort(dpIdInt, portNameInt);
- Long patchExtPort = getPatchPort(dpIdExt, portNameExt);
- Preconditions.checkNotNull(dpIdInt);
- Preconditions.checkNotNull(dpIdExt);
- Preconditions.checkNotNull(portNameInt);
- vlanResponderProvider.programProviderNetworkRulesInternal(dpIdInt, network.getProviderSegmentationID(), ofPort,
- patchIntPort, macAddress, vlanProviderCache, write);
-
- vlanResponderProvider.programProviderNetworkRulesExternal(dpIdExt, network.getProviderSegmentationID(),
- patchExtPort, macAddress, vlanProviderCache, write);
- } catch(Exception e) {
- LOG.error("programProviderNetworkFlow:Error while writing a flows. Caused due to, " + e.getMessage());
- }
- }
-
- /**
- * Construct patch port name based on external bridge name
- *
- * @param brExt String representing an External bridge.
- * @return the string portNameExt.
- */
- public static String getPatchPortName(String brExt) {
- String portNameExt = null;
- if (brExt.contains("-")) {
- String[] brExt_Ex = brExt.split("-");
- portNameExt = Constants.MULTIPLE_NETWORK_L3_PATCH.concat("-").concat(brExt_Ex[1]);
- } else {
- portNameExt = Constants.MULTIPLE_NETWORK_L3_PATCH.concat("-").concat(brExt);
- }
- return portNameExt;
- }
-
- private Long getPatchPort(final Long dpId, final String portName) {
- final Long dpidPrimitive = dpId;
- for (Node node : nodeCacheManager.getBridgeNodes()) {
- if (dpidPrimitive == southbound.getDataPathId(node)) {
- final OvsdbTerminationPointAugmentation terminationPointOfBridge =
- southbound.getTerminationPointOfBridge(node, portName);
- return (terminationPointOfBridge == null) ? null : terminationPointOfBridge.getOfport();
- }
- }
- return null;
- }
-
- private void populateVLANProviderCaches() {
- /*
- * Rebuild the cache in case of a restart.
- */
- if (this.isCachePopulationDone || this.neutronPortCache == null
- || this.neutronNetworkCache == null) {
- return;
- }
- this.isCachePopulationDone = true;
- Set<String> lstMacAddress;
- List<NeutronPort> neutronPorts = neutronPortCache.getAllPorts();
- for (NeutronPort neutronPort : neutronPorts) {
- if (neutronPort != null && neutronPort.getDeviceOwner().equalsIgnoreCase(Constants.OWNER_ROUTER_GATEWAY)) {
- final String macAddress = neutronPort.getMacAddress();
- final String networkUUID = neutronPort.getNetworkUUID();
- NeutronNetwork neutronNetwork = neutronNetworkCache.getNetwork(networkUUID);
- if (neutronNetwork == null) {
- neutronNetwork = neutronL3Adapter.getNetworkFromCleanupCache(networkUUID);
- }
- final String providerSegmentationId = neutronNetwork != null ?
- neutronNetwork.getProviderSegmentationID() : null;
- LOG.debug("In populateVLANProviderCaches macAddress:" + macAddress +
- "providerSegmentationId:" + providerSegmentationId);
- if (providerSegmentationId == null || providerSegmentationId.isEmpty()
- || macAddress == null || macAddress.isEmpty()) {
- return;
- }
- if (vlanProviderCache != null && !vlanProviderCache.isEmpty() &&
- vlanProviderCache.containsKey(providerSegmentationId)) {
- lstMacAddress = vlanProviderCache.get(providerSegmentationId);
- } else {
- lstMacAddress = new HashSet<>();
- vlanProviderCache.put(providerSegmentationId, lstMacAddress);
- }
- lstMacAddress.add(macAddress);
- }
- }
- }
-
- @Override
- public void setDependencies(final ServiceReference serviceReference) {
- vlanResponderProvider =
- (VlanResponderProvider) ServiceHelper.getGlobalInstance(VlanResponderProvider.class, this);
- configurationService =
- (ConfigurationService) ServiceHelper.getGlobalInstance(ConfigurationService.class, this);
- southbound =
- (Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this);
- nodeCacheManager =
- (NodeCacheManager) ServiceHelper.getGlobalInstance(NodeCacheManager.class, this);
- neutronL3Adapter =
- (NeutronL3Adapter) ServiceHelper.getGlobalInstance(NeutronL3Adapter.class, this);
- }
-
- @Override
- public void setDependencies(final Object impl) {
- if (impl instanceof VlanResponderProvider) {
- vlanResponderProvider = (VlanResponderProvider)impl;
- } else if (impl instanceof INeutronNetworkCRUD) {
- neutronNetworkCache = (INeutronNetworkCRUD)impl;
- } else if (impl instanceof INeutronPortCRUD) {
- neutronPortCache = (INeutronPortCRUD)impl;
- }
- populateVLANProviderCaches();
- }
-
- private Long getDpidForIntegrationBridge(Node node, final String portName) {
- if (southbound.getBridgeName(node).equals(configurationService.getIntegrationBridgeName())) {
- TerminationPoint tp = southbound.readTerminationPoint(node, null, portName);
- if (tp != null) {
- final long dpid = southbound.getDataPathId(node);
- return dpid;
- }
- }
- return null;
- }
-
- private Long getDpidForExternalBridge() {
- List<Long> dpids = nodeCacheManager.getBridgeDpids(configurationService.getExternalBridgeName());
- return dpids.get(0);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-/**
- * This enumeration represents the type of action being performed
- */
-public enum Action {
- ADD,
- UPDATE,
- DELETE
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-import java.net.InetAddress;
-
-/**
- * This interface allows ARP flows to be written to devices
- */
-public interface ArpProvider {
-
- Status programStaticArpEntry(Long dpid, String segmentationId,
- String macAddress, InetAddress ipAddress, Action action);
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-
-import java.util.List;
-
-/**
- * OpenStack Neutron with the Open vSwitch plugin relies on a typical bridge configuration that
- * consists of br-int (Integration Bridge), br-net (Network bridge), br-ex (External bridge).
- *
- * This class ensures that the bridges on each {@link Node}
- * are correctly configured for OpenStack Neutron
- *
- */
-public interface BridgeConfigurationManager {
-
- /**
- * A helper function to get the UUID of a given Bridge
- * @param node the {@link Node} where the bridge is configured
- * @param bridgeName the name of the bridge
- * @return the UUID of the bridge
- */
- String getBridgeUuid(Node node, String bridgeName);
-
- /**
- * Checks for the existence of the Integration Bridge on a given Node
- * @param node the {@link Node} where the bridge should be configured
- * @return True if the bridge exists, False if it does not
- */
- boolean isNodeNeutronReady(Node node);
-
- /**
- * Checks for the existence of the Network Bridge on a given Node
- * @param node the {@link Node} where the bridge should be configured
- * @return True if the bridge exists, False if it does not
- */
- boolean isNodeOverlayReady(Node node);
-
- /**
- * Checks for the existence of the Network Bridge on a given Node
- * @param node the {@link Node} where the bridge should be configured
- * @return True if the bridge exists, False if it does not
- */
-
- /**
- * Checks that a Node is ready for a Tunnel Network Provider
- * For OpenFlow 1.0 the Integration, Network Bridge and corresponding patch ports are required
- * For OpenFlow 1.3 only the Integration Bridge is required
- * @param bridgeNode the {@link Node} that represents bridge
- * @param ovsdbNode the {@link Node} where the bridge is configured
- * @return True or False
- */
- boolean isNodeTunnelReady(Node bridgeNode, Node ovsdbNode);
-
- /* Determine if internal network is ready for vlan network types.
- * - OF 1.0 requires br-int, br-net, a patch connecting them and
- * physical device added to br-net.
- * - OF 1.3 requires br-int and physical device added to br-int.
- */
-
- /**
- * Checks that a Node is ready for a VLAN Network Provider for the given Network
- * For OpenFlow 1.0 the Integration Bridge, Network Bridge, patch ports and a physical device connected to the
- * Network Bridge are required.
- * For OpenFlow 1.3 the Integration Bridge is required and must have a physical device connected.
- * @param bridgeNode the {@link Node} that represents bridge
- * @param ovsdbNode the {@link Node} where the bridge is configured
- * @param network the {@link org.opendaylight.netvirt.openstack.netvirt.translator}
- * @return True or False
- */
- boolean isNodeVlanReady(Node bridgeNode, Node ovsdbNode, NeutronNetwork network);
-
- /**
- * A helper function to determine if a port exists on a given bridge
- * @param node the {@link Node} where the bridge is configured
- * @param portName the name of the port to search for
- * @return True if the port exists, otherwise False
- */
- boolean isPortOnBridge(Node node, String portName);
-
-
- /**
- * Returns true if the bridges required for the provider network type are created
- * If the bridges are not created, this method will attempt to create them
- * @param node the {@link Node} to query
- * @param network the {@link org.opendaylight.netvirt.openstack.netvirt.translator}
- * @return True or False
- */
- boolean createLocalNetwork(Node node, NeutronNetwork network);
-
- /**
- * Prepares the given Node for Neutron Networking by creating the Integration Bridge
- * @param node the {@link Node} to prepare
- */
- void prepareNode(Node node);
-
- /**
- * Returns the physical interface mapped to the given neutron physical network.
- * @param node the {@link Node} to query
- * @param physicalNetwork neutron physical network
- * @return name of the physical interface
- */
- String getPhysicalInterfaceName(Node node, String physicalNetwork);
-
- /** Returns all physical interfaces configured in the bridge mapping
- * Bridge mappings will be of the following format:
- * @param node the {@link Node} to query
- * @return a List in the format {eth1, eth2} given bridge_mappings=physnet1:eth1,physnet2:eth2
- */
- List<String> getAllPhysicalInterfaceNames(Node node);
-
- /*
- * Return br-ex interface configured in the bridge_mappings.
- * Return null if br-ex is not configured in bridge_mappings.
- * @param node the {@link Node} to query
- * @param externalNetwork
- * @return the interface as a string like eth3 given bridge_mappings=br-ex:eth3
- */
- String getExternalInterfaceName (Node node, String externalNetwork);
-
-
- /**
- *
- * @param node the {@link Node} to query
- * @return a list of controllers
- */
- List<String> getControllersFromOvsdbNode(Node node);
-
- /**
- * Returns all physical interfaces configured in the provider mapping
- * @param node the {@link Node} to query
- * @return name of the physical interface
- */
- String getMultipleExternalBridge(Node node);
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-
-/**
- * This interface allows Classifier flows to be written to devices
- */
-public interface ClassifierProvider {
- void programLocalInPort(Long dpidLong, String segmentationId, Long inPort, String attachedMac, boolean write);
- void programLocalInPortSetVlan(Long dpidLong, String segmentationId, Long inPort, String attachedMac, boolean write);
- void programDropSrcIface(Long dpidLong, Long inPort, boolean write);
- void programTunnelIn(Long dpidLong, String segmentationId, Long ofPort, boolean write);
- void programVlanIn(Long dpidLong, String segmentationId, Long ethPort, boolean write);
- void programLLDPPuntRule(Long dpidLong);
- void programGotoTable(Long dpidLong, boolean write);
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-
-import java.net.InetAddress;
-import java.util.Map;
-import org.apache.commons.lang3.tuple.Pair;
-
-/**
- * The ConfigurationService handles the configuration of the OpenStack Neutron Integration
- * It exposes a set of Configuration variables and helper functions for obtaining node-specific
- * configuration from the Open_vSwitch table of an OVS instance.
- */
-public interface ConfigurationService {
-
- /**
- * @return the name configured name of the Integration Bridge
- */
- String getIntegrationBridgeName();
-
- /**
- * Configures the name of the Integration Bridge
- * @param integrationBridgeName name of integration bridge
- */
- void setIntegrationBridgeName(String integrationBridgeName);
-
- /**
- * @return the name configured name of the Network Bridge
- */
- String getNetworkBridgeName();
-
- /**
- * Configures the name of the Network Bridge
- * @param networkBridgeName Name of the network bridge
- */
- void setNetworkBridgeName(String networkBridgeName);
-
- /**
- * @return the name configured name of the ExternalBridge
- */
- String getExternalBridgeName();
-
- /**
- * Configures the name of the External Bridge
- * @param externalBridgeName Name of external bridge
- */
- void setExternalBridgeName(String externalBridgeName);
-
- /**
- * @return the key used to access the Tunnel Endpoint configuration from Open vSwitch
- */
- String getTunnelEndpointKey();
-
- /**
- * Sets the key used to access the Tunnel Endpoint configuration from Open vSwitch
- * @param tunnelEndpointKey key of tunnel end point
- */
- void setTunnelEndpointKey(String tunnelEndpointKey);
-
- /**
- * @return a Map of patch port names where the key is a tuple of source bridge and destination bridge
- */
- Map<Pair<String, String>, String> getPatchPortNames();
-
- /**
- * Sets the Map of source/destination bridges to patch port name
- * @param patchPortNames Map of source/destination bridges to patch port name
- */
- void setPatchPortNames(Map<Pair<String, String>, String> patchPortNames);
-
- /**
- * Get the name of a patch port
- * @param portTuple a {@link org.apache.commons.lang3.tuple.Pair} where L
- * is the source bridge and R the destination bridge
- * @return the name of the patch port
- */
- String getPatchPortName(Pair portTuple);
-
- /**
- * @return the key used to access the Tunnel Endpoint configuration from Open vSwitch
- */
- String getProviderMappingsKey();
-
- /**
- * Sets the key used to access the Tunnel Endpoint configuration from Open vSwitch
- * @param providerMappingsKey provide mapping key
- */
- void setProviderMappingsKey(String providerMappingsKey);
-
- /**
- * @return Gets the default provider mapping
- */
- String getDefaultProviderMapping();
-
- /**
- * Sets the default provider mapping
- * @param providerMapping provider mapping
- */
- void setDefaultProviderMapping(String providerMapping);
-
- /**
- * Gets the tunnel endpoint address for a given Node
- * @param node a {@link Node}
- * @return the tunnel endpoint
- * @see java.net.InetAddress
- */
- InetAddress getTunnelEndPoint(Node node);
-
- /**
- * Returns the OpenFlow version to be used by the {@link NetworkingProvider}
- * Default is OpenFlow 1.0. OVS versions greater than 1.10.0 will use OpenFlow 1.3
- * @param node the node to query
- * @return the OpenFlow version to use
- */
- String getOpenflowVersion(Node node);
-
- /**
- * Determine if L3 forwarding is enabled
- * @return true if ovsdb net-virt is configured to perform L3 forwarding
- */
- boolean isL3ForwardingEnabled();
-
- /**
- * Determine if Distributed ARP Responder is enabled
- * @return true if ovsdb net-virt is configured for distributed arp responder
- */
- boolean isDistributedArpDisabled();
-
- /**
- * Determine if Remote mac learned is enabled
- * @return true if ovsdb net-virt is configured for remote mac learned
- */
- boolean isRemoteMacLearnEnabled();
-
- /**
- * Determine if Multiple External Network is enabled
- * @return true if ovsdb net-virt is configured to perform Multiple External Network
- */
- boolean isL3MultipleExternalNetworkEnabled();
-
- /**
- * Returns the MacAddress to be used for the default gateway by the {@link L3ForwardingProvider}
- * There is no default.
- * @param node the node to query
- * @return the MacAddress to use for the default gateway; or null if none is configured.
- */
- String getDefaultGatewayMacAddress(Node node);
-
- boolean isUserSpaceEnabled();
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-/**
- * A collection of configuration constants
- */
-public final class Constants {
-
- /*
- * External ID's used by OpenStack Neutron
- */
- public static final String EXTERNAL_ID_VM_ID = "vm-id";
- public static final String EXTERNAL_ID_INTERFACE_ID = "iface-id";
- public static final String EXTERNAL_ID_VM_MAC = "attached-mac";
- public static final String EXTERNAL_NETWORK = "external";
-
- /*
- * @see http://docs.openstack.org/grizzly/openstack-network/admin/content/ovs_quantum_plugin.html
- */
- public static final String TUNNEL_ENDPOINT_KEY = "local_ip";
- public static final String TUNNEL_ENDPOINT_KEY_REMOTE = "remote_ip";
- public static final String INTEGRATION_BRIDGE = "br-int";
- public static final String NETWORK_BRIDGE = "br-net";
- public static final String EXTERNAL_BRIDGE = "br-ex";
- public static final String PATCH_PORT_TO_INTEGRATION_BRIDGE_NAME = "patch-int";
- public static final String PATCH_PORT_TO_NETWORK_BRIDGE_NAME = "patch-net";
- public static final String PATCH_PORT_TO_EXTERNAL_BRIDGE_NAME = "patch-ext";
- public static final String PROVIDER_MAPPINGS_KEY = "provider_mappings";
- public static final String PROVIDER_MAPPING = "physnet1:eth1";
-
- /*
- * Flow Priority Defaults
- */
- public static final int LLDP_PRIORITY = 1000;
- public static final int NORMAL_PRIORITY = 0;
-
- /*
- * OpenFlow Versions
- */
- public static final String OPENFLOW13 = "OpenFlow13";
-
- /*
- * VLAN Constants
- */
- public static final int MAX_VLAN = 4094;
-
- /*
- * OSGi Service Properties
- */
- public static final String SOUTHBOUND_PROTOCOL_PROPERTY = "southboundProtocol";
- public static final String PROVIDER_TYPE_PROPERTY = "providerType";
- public static final String OPENFLOW_VERSION_PROPERTY = "openflowVersion";
- public static final String EVENT_HANDLER_TYPE_PROPERTY = "eventHandlerType";
- public static final String PROVIDER_NAME_PROPERTY = "providerName";
- public static final String NAT_PROVIDER_DIRECTION = "natDirection";
-
- /*
- * MD-SAL
- */
-
- public static final String OPENFLOW_NODE_PREFIX = "openflow:";
- public static final String NETVIRT_TOPOLOGY_ID = "netvirt:1";
-
- /*
- * Ethertypes
- */
- public static final long ARP_ETHERTYPE = 0x0806L;
-
-
- /*
- * ACL
- */
- public static final Integer PROTO_DHCP_CLIENT_SPOOF_MATCH_PRIORITY_DROP = 61011;
- public static final Integer PROTO_MATCH_PRIORITY_DROP = 36006;
- public static final Integer PROTO_PORT_MATCH_PRIORITY_DROP = 36005;
- public static final Integer PREFIX_MATCH_PRIORITY_DROP = 36004;
- public static final Integer PROTO_PREFIX_MATCH_PRIORITY_DROP = 36003;
- public static final Integer PREFIX_PORT_MATCH_PRIORITY_DROP = 36002;
-
- public static final Integer PROTO_DHCP_CLIENT_TRAFFIC_MATCH_PRIORITY = 61012;
- public static final Integer PROTO_MATCH_PRIORITY = 61010;
- public static final Integer PROTO_DHCP_SERVER_MATCH_PRIORITY = 61008;
- public static final Integer PROTO_PORT_MATCH_PRIORITY = 61007;
- public static final Integer PROTO_IP_PORT_MATCH_PRIORITY = 61006;
- public static final Integer PROTO_REG6_MATCH_PRIORITY = 61005;
- public static final Integer PROTO_OTHER_MATCH_PRIORITY = 61004;
- public static final Integer PROTO_PORT_ICMP_MATCH_PRIORITY = 61003;
- public static final Integer PROTO_PORT_DROP_PRIORITY = 61002;
- public static final Integer CT_STATE_UNTRACKED_PRIORITY = 62030;
- public static final Integer CT_STATE_TRACKED_EXIST_PRIORITY = 62020;
- public static final Integer CT_STATE_TRACKED_NEW_PRIORITY = 62010;
- public static final Integer CT_STATE_NEW_PRIORITY_DROP = 36007;
-
- public static final int TCP_SYN = 0x002;
- public static final short INGRESS_ACL = 40; // Flows Destined to the VM Port go here
- public static final short OUTBOUND_SNAT = 110; // Ingress ACL table drains traffic to this table
-
- private static Long groupId = 1L;
-
- //6653 is official openflow port.
- public static short OPENFLOW_PORT = 6653;
- public static String OPENFLOW_CONNECTION_PROTOCOL = "tcp";
-
- /*
- * Clustering
- */
- public static final String NETVIRT_OWNER_ENTITY_TYPE = "ovsdb-netvirt-provider";
-
- public static final String MULTIPLE_NETWORK_L3_PATCH = "patch";
-
- public static final String OWNER_ROUTER_GATEWAY = "network:router_gateway";
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityGroup;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityRule;
-import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
-
-import java.util.List;
-
-/**
- * This interface allows egress Port Security flows to be written to devices.
- */
-public interface EgressAclProvider {
-
- /**
- * Program port security Group.
- *
- * @param dpid the dpid
- * @param segmentationId the segmentation id
- * @param attachedMac the attached mac
- * @param localPort the local port
- * @param securityGroup the security group
- * @param portUuid the uuid of the port.
- * @param nodeId the NodeId of the node.
- * @param write is this flow write or delete
- */
- void programPortSecurityGroup(Long dpid, String segmentationId, String attachedMac,
- long localPort, NeutronSecurityGroup securityGroup,
- String portUuid, NodeId nodeId, boolean write);
- /**
- * Program port security rule.
- *
- * @param dpid the dpid
- * @param segmentationId the segmentation id
- * @param attachedMac the attached mac
- * @param portSecurityRule the security rule
- * @param vmIp the ip of the remote vm if it has a remote security group.
- * @param write is this flow write or delete
- */
- void programPortSecurityRule(Long dpid, String segmentationId, String attachedMac,
- NeutronSecurityRule portSecurityRule, Neutron_IPs vmIp, boolean write);
- /**
- * Program fixed egress security group rules that will be associated with the VM port when a vm is spawned.
- *
- * @param dpid the dpid
- * @param segmentationId the segmentation id
- * @param attachedMac the attached mac
- * @param localPort the local port
- * @param srcAddressList the list of source ip address assigned to vm
- * @param write is this flow writing or deleting
- */
- void programFixedSecurityGroup(Long dpid, String segmentationId,String attachedMac, long localPort,
- List<Neutron_IPs> srcAddressList, boolean write);
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-import org.opendaylight.netvirt.openstack.netvirt.AbstractHandler;
-import org.opendaylight.netvirt.openstack.netvirt.AbstractEvent;
-import org.osgi.framework.ServiceReference;
-
-/**
- * Openstack related events will be enqueued into a common event queue.
- * This interface provides access to an event dispatcher, as well as registration to link dispatcher to which handlers
- * dispatcher will utilize.
- */
-public interface EventDispatcher {
- /**
- * Enqueue the event.
- * @param event the {@link AbstractEvent} event to be handled.
- */
- void enqueueEvent(AbstractEvent event);
- void eventHandlerAdded(final ServiceReference ref, AbstractHandler handler);
- void eventHandlerRemoved(final ServiceReference ref);
-}
-
+++ /dev/null
-/*
- * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
-
-import com.google.common.util.concurrent.ListenableFuture;
-
-/**
-*
-* @author Anil Vishnoi (avishnoi@Brocade.com)
-*
-*/
-
-public interface GatewayMacResolver {
-
- /**
- * Method will trigger the mac resolution for gateway IP. If user set periodicRefresh to true,
- * it will periodically trigger the gateway resolution after a specific time interval using the
- * given source IP and MAC addresses. It will also cache the source IP and MAC in case of periodicRefresh.
- * If periodicRefresh is false, it will just do one time gateway resolution and won't cache any internal data.
- * If user call the same method with different source ip and mac address, GatewayMacResolver service will
- * update the internally cached data with these new source ip and mac address and will use it as per
- * periodicRefresh flag.
- * @param gatewayMacResolverListener An optional listener for mac update callback (can be null)
- * @param externalNetworkBridgeDpid This bridge will be used for sending ARP request
- * @param refreshExternalNetworkBridgeDpidIfNeeded Instructs resolver to change bridge dpid if resolve is failing
- * @param gatewayIp ARP request will be send for this ip address
- * @param sourceIpAddress Source IP address for the ARP request (localhost)
- * @param sourceMacAddress Source MAC address for the ARP request (localhost)
- * @param periodicRefresh Do you want to periodically refresh the gateway mac?
- * @return ListenableFuture that contains the mac address of gateway ip.
- */
- ListenableFuture<MacAddress> resolveMacAddress(
- final GatewayMacResolverListener gatewayMacResolverListener,
- final Long externalNetworkBridgeDpid, final Boolean refreshExternalNetworkBridgeDpidIfNeeded,
- final Ipv4Address gatewayIp, final Ipv4Address sourceIpAddress,
- final MacAddress sourceMacAddress, final Boolean periodicRefresh);
-
- /**
- * Method will stop the periodic refresh of the given gateway ip address.
- * @param gatewayIp Gateway IP Address
- */
- void stopPeriodicRefresh(final Ipv4Address gatewayIp);
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
-
-/**
- * This interface allows for notifications from GatewayMacResolver to a generic listener.
- */
-public interface GatewayMacResolverListener {
-
- /**
- * Method will trigger when the mac for gateway IP is resolved or updated.
- *
- * @param externalNetworkBridgeDpid Bridge used for sending ARP request
- * @param gatewayIpAddress Ip address that Mac Resolver ARPed for
- * @param macAddress Mac Address associated with the gatewayIpAddress
- */
- void gatewayMacResolved(final Long externalNetworkBridgeDpid, final IpAddress gatewayIpAddress,
- final MacAddress macAddress);
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-import java.net.InetAddress;
-
-/**
- * @author Josh Hershberg (jhershbe@redhat.com)
- */
-public interface IcmpEchoProvider {
-
- Status programIcmpEchoEntry(Long dpid, String segmentationId,
- String macAddress, InetAddress ipAddress, Action action);
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-import java.net.InetAddress;
-
-/**
- * This interface allows NAT flows to be written to devices
- */
-public interface InboundNatProvider {
- Status programIpRewriteRule(Long dpid, Long inPort, String destSegId, InetAddress matchAddress,
- InetAddress rewriteAddress, Action action);
-
- Status programIpRewriteExclusion(Long dpid, String segmentationId,
- String excludedCidr, Action action);
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityGroup;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityRule;
-import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
-
-/**
- * This interface allows ingress Port Security flows to be written to devices.
- */
-public interface IngressAclProvider {
-
- /**
- * Program port security Group.
- *
- * @param dpid the dpid
- * @param segmentationId the segmentation id
- * @param attachedMac the attached mac
- * @param localPort the local port
- * @param securityGroup the security group
- * @param portUuid the uuid of the port.
- * @param nodeId the NodeId of the node.
- * @param write is this flow write or delete
- */
- void programPortSecurityGroup(Long dpid, String segmentationId, String attachedMac,
- long localPort, NeutronSecurityGroup securityGroup,
- String portUuid, NodeId nodeId, boolean write);
-
- /**
- * Program port security rule.
- *
- * @param dpid the dpid
- * @param segmentationId the segmentation id
- * @param attachedMac the attached mac
- * @param portSecurityRule the security rule
- * @param vmIp the ip of the remote vm if it has a remote security group.
- * @param write is this flow write or delete
- */
- void programPortSecurityRule(Long dpid, String segmentationId, String attachedMac,
- NeutronSecurityRule portSecurityRule, Neutron_IPs vmIp, boolean write);
-
- /**
- * Program fixed ingress ACL rules that will be associated with the VM port when a vm is spawned.
- * *
- *
- * @param dpid the dpid
- * @param segmentationId the segmentation id
- * @param attachedMac the dhcp mac
- * @param localPort the local port
- * @param attachedMac2 the src mac
- * @param write is this flow writing or deleting
- */
- void programFixedSecurityGroup(Long dpid, String segmentationId, String attachedMac, long localPort,
- String attachedMac2, boolean write);
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (c) 2016 NEC Corporation 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.netvirt.openstack.netvirt.api;
-
-/**
- * This Interface allows L2Forwarding learn flows to be written to devices
- */
-public interface L2ForwardingLearnProvider {
- void programL2ForwardingLearnRule(Long dpidLong);
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-/**
- * This interface allows L2Forwarding flows to be written to devices
- */
-public interface L2ForwardingProvider {
- void programLocalUcastOut(Long dpidLong, String segmentationId, Long localPort, String attachedMac, boolean write);
- void programLocalVlanUcastOut(Long dpidLong, String segmentationId, Long localPort, String attachedMac, boolean write);
- void programLocalBcastOut(Long dpidLong, String segmentationId, Long localPort, boolean write);
- void programLocalVlanBcastOut(Long dpidLong, String segmentationId, Long localPort, Long ethPort, boolean write);
- void programLocalVlanTableMiss(Long dpidLong, String segmentationId, boolean write);
- void programTunnelOut(Long dpidLong, String segmentationId, Long OFPortOut, String attachedMac, boolean write);
- void programVlanOut(Long dpidLong, String segmentationId, Long ethPort, String attachedMac, boolean write);
- void programTunnelFloodOut(Long dpidLong, String segmentationId, Long OFPortOut, boolean write);
- void programTunnelUnknownUcastFloodOut(Long dpidLong, String segmentationId, Long OFPortOut, boolean write);
- void programVlanMiss(Long dpidLong, String segmentationId, Long ethPort, boolean write);
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-/**
- * This interface allows L2Rewrite flows to be written to devices
- */
-public interface L2RewriteProvider {
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-import java.net.InetAddress;
-
-/**
- * This interface allows L3 Forwarding flows to be written to devices
- */
-public interface L3ForwardingProvider {
-
- Status programForwardingTableEntry(Long dpid, String segmentationId, InetAddress ipAddress,
- String macAddress, Action action);
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 NEC Corporation 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.netvirt.openstack.netvirt.api;
-
-import java.math.BigInteger;
-import java.util.HashMap;
-
-public class LearnConstants {
- public static final String LEARN_MATCH_REG_VALUE = "1";
- public static final int ETHTYPE_IPV4 = 0X0800;
- public static final int ETHTYPE_IPV6 = 0x86dd;
- public static final int IP_PROT_ICMP = 1;
- public static final int IP_PROT_TCP = 6;
- public static final int IP_PROT_UDP = 17;
- public static final String LEARN_PRIORITY = "61010";
- public static final String DELETE_LEARNED_FLAG_VALUE = "2";
- public static final HashMap<Integer, String> ICMP_TYPE_MAP = new HashMap<>();
- static
- {
- ICMP_TYPE_MAP.put(8, "0");
- ICMP_TYPE_MAP.put(13, "14");
- ICMP_TYPE_MAP.put(15, "16");
- ICMP_TYPE_MAP.put(17, "18");
- }
- public enum NxmOfFieldType {
- NXM_OF_IN_PORT(0x0000, 0, 2, 16),
- NXM_OF_ETH_DST(0x0000, 1, 6, 48),
- NXM_OF_ETH_SRC(0x0000, 2, 6, 48),
- NXM_NX_TUN_ID(0x001, 16, 8, 64),
- NXM_OF_ETH_TYPE(0x0000, 3, 2, 16),
- NXM_OF_VLAN_TCI(0x0000, 4, 2, 12),
- NXM_OF_IP_TOS(0x0000, 5, 1, 8),
- NXM_OF_IP_PROTO(0x0000, 6, 1, 8),
- NXM_OF_IP_SRC(0x0000, 7, 4, 32),
- NXM_OF_IP_DST(0x0000, 8, 4, 32),
- NXM_OF_TCP_SRC(0x0000, 9, 2, 16),
- NXM_OF_TCP_DST(0x0000, 10, 2, 16),
- NXM_OF_UDP_SRC(0x0000, 11, 2, 16),
- NXM_OF_UDP_DST(0x0000, 12, 2, 16),
- NXM_OF_ICMP_TYPE(0x0000, 13, 1, 8),
- NXM_OF_ICMP_CODE(0x0000, 14, 1, 8),
- NXM_OF_ARP_OP(0x0000, 15, 2, 16),
- NXM_OF_ARP_SPA(0x0000, 16, 4, 16),
- NXM_OF_ARP_TPA(0x0000, 17, 4, 16),
- NXM_NX_REG0(0x0001, 0, 4, -1),
- NXM_NX_REG1(0x0001, 1, 4, -1),
- NXM_NX_REG2(0x0001, 2, 4, -1),
- NXM_NX_REG3(0x0001, 3, 4, -1),
- NXM_NX_REG4(0x0001, 4, 4, -1),
- NXM_NX_REG5(0x0001, 5, 4, -1),
- NXM_NX_REG6(0x0001, 6, 4, -1),
- NXM_NX_REG7(0x0001, 7, 4, -1);
-
- long hexType;
- long flowModHeaderLen;
-
- NxmOfFieldType(long vendor, long field, long length, long flowModHeaderLen) {
- hexType = nxmHeader(vendor, field, length);
- this.flowModHeaderLen = flowModHeaderLen;
- }
-
- private static long nxmHeader(long vendor, long field, long length) {
- return ((vendor) << 16) | ((field) << 9) | (length);
- }
-
- public String getHexType() {
- return String.valueOf(hexType);
- }
-
- public String getFlowModHeaderLen() {
- return String.valueOf(flowModHeaderLen);
- }
- }
-
- public enum LearnFlowModsType {
- MATCH_FROM_FIELD, MATCH_FROM_VALUE, COPY_FROM_FIELD, COPY_FROM_VALUE, OUTPUT_TO_PORT;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 SDN Hub, LLC. 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.netvirt.openstack.netvirt.api;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Store configuration for each load balancer instance created.
- */
-
-public class LoadBalancerConfiguration {
- public static final String PROTOCOL_TCP = "TCP";
- public static final String PROTOCOL_HTTP = "HTTP";
- public static final String PROTOCOL_HTTPS = "HTTPS";
-
- public class LoadBalancerPoolMember {
- String ipAddr;
- String macAddr;
- String protocol;
- Integer port;
- int index;
-
- public LoadBalancerPoolMember(String ipAddr, String macAddr, String protocol, Integer port) {
- this.ipAddr = ipAddr;
- this.macAddr = macAddr;
- this.protocol = protocol;
- this.port = port;
- this.index = -1;
- }
- public LoadBalancerPoolMember(String ipAddr, String macAddr, String protocol, Integer port, int index) {
- this.ipAddr = ipAddr;
- this.macAddr = macAddr;
- this.protocol = protocol;
- this.port = port;
- this.index = index;
- }
- public String getIP() {
- return ipAddr;
- }
- public String getMAC() {
- return macAddr;
- }
- public String getProtocol() {
- return protocol;
- }
- public Integer getPort() {
- return port;
- }
- public int getIndex() {
- return index;
- }
- public void setIndex(int index) {
- this.index = index;
- }
-
- /**
- * Overridden equals() where index is not checked.
- */
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- LoadBalancerPoolMember other = (LoadBalancerPoolMember) obj;
- if (ipAddr == null) {
- if (other.ipAddr != null) {
- return false;
- }
- } else if (!ipAddr.equals(other.ipAddr)) {
- return false;
- }
- if (macAddr == null) {
- if (other.macAddr != null) {
- return false;
- }
- } else if (!macAddr.equals(other.macAddr)) {
- return false;
- }
- if (port == null) {
- if (other.port != null) {
- return false;
- }
- } else if (!port.equals(other.port)) {
- return false;
- }
- if (protocol == null) {
- if (other.protocol != null) {
- return false;
- }
- } else if (!protocol.equals(other.protocol)) {
- return false;
- }
- return true;
- }
-
- @Override
- public String toString() {
- return "LoadBalancerPoolMember [ip=" + ipAddr + ", mac=" + macAddr +
- ", protocol=" + protocol + ", port=" + port + ", index=" + index + "]";
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((ipAddr == null) ? 0 : ipAddr.hashCode());
- result = prime * result + ((macAddr == null) ? 0 : macAddr.hashCode());
- result = prime * result + ((protocol == null) ? 0 : protocol.hashCode());
- result = prime * result + ((port == null) ? 0 : port.hashCode());
- return result;
- }
- }
-
- private String name;
- private String vip;
- private String vmac; //Used when a dummy neutron port is created for the VIP
- private String providerNetworkType;
- private String providerSegmentationId;
- private Map <String, LoadBalancerPoolMember> members;
-
- public LoadBalancerConfiguration() {
- this.members = new HashMap<>();
- }
-
- public LoadBalancerConfiguration(String name, String vip) {
- this.members = new HashMap<>();
- this.name = name;
- this.vip = vip;
- this.vmac = null;
- }
-
- public LoadBalancerConfiguration(String name, String vip, String vmac) {
- this.members = new HashMap<>();
- this.name = name;
- this.vip = vip;
- this.vmac = vmac;
- }
-
- public LoadBalancerConfiguration(LoadBalancerConfiguration lbConfig) {
- this.members = new HashMap<>(lbConfig.getMembers());
- this.name = lbConfig.getName();
- this.vip = lbConfig.getVip();
- this.vmac = lbConfig.getVmac();
- this.providerNetworkType = lbConfig.getProviderNetworkType();
- this.providerSegmentationId = lbConfig.getProviderSegmentationId();
- }
-
- public Map<String, LoadBalancerPoolMember> getMembers() {
- return this.members;
- }
-
- public Map<String, LoadBalancerPoolMember> addMember(String uuid, LoadBalancerPoolMember member) {
- //If index is not set for this object, update it before inserting
- if (member.getIndex() == -1) {
- member.setIndex(members.size());
- }
- this.members.put(uuid, member);
- return this.members;
- }
- public Map<String, LoadBalancerPoolMember> addMember(String uuid, String ipAddr, String macAddr, String protocol, Integer port) {
- this.members.put(uuid,
- new LoadBalancerPoolMember(ipAddr, macAddr, protocol, port, members.size()));
- return this.members;
- }
- public Map<String, LoadBalancerPoolMember> removeMember(String uuid) {
- this.members.remove(uuid);
- /* Update indices of all other members
- */
- int index = 0;
- for(Map.Entry<String, LoadBalancerPoolMember> entry : this.getMembers().entrySet()) {
- entry.getValue().setIndex(index++);
- }
- return this.members;
- }
-
- public boolean isValid() {
- if (members.size() == 0) {
- return false;
- } else if (providerNetworkType == null) {
- return false;
- }
- return true;
- }
-
- public void setVip(String vip) {
- this.vip = vip;
- }
-
- public String getVip() {
- return this.vip;
- }
-
- public void setVmac(String vmac) {
- this.vmac = vmac;
- }
-
- public String getVmac() {
- return this.vmac;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getName() {
- return this.name;
- }
-
- public void setProviderSegmentationId(String providerSegmentationId) {
- this.providerSegmentationId = providerSegmentationId;
- }
-
- public String getProviderSegmentationId() {
- return this.providerSegmentationId;
- }
- public void setProviderNetworkType(String providerNetworkType) {
- this.providerNetworkType = providerNetworkType;
- }
-
- public String getProviderNetworkType() {
- return this.providerNetworkType;
- }
-
- @Override
- public String toString() {
- return "LoadBalancerConfiguration [name=" + name +
- ", vip=" + vip + ", vmac=" + vmac +
- ", networkType=" + providerNetworkType +
- ", segmentationId=" + providerSegmentationId +
- ", members=" + members + "]";
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 SDN Hub, LLC. 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.netvirt.openstack.netvirt.api;
-
-import org.opendaylight.netvirt.openstack.netvirt.api.LoadBalancerConfiguration.LoadBalancerPoolMember;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-
-/**
- * This interface allows load-balancer flows to be written to nodes
- */
-public interface LoadBalancerProvider {
-
- Status programLoadBalancerRules(Node node,
- LoadBalancerConfiguration lbConfig, Action action);
-
- Status programLoadBalancerPoolMemberRules(Node node,
- LoadBalancerConfiguration lbConfig, LoadBalancerPoolMember member, Action action);
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-import java.net.InetAddress;
-import java.util.UUID;
-
-/**
- * A Router that is Multi-Tenant Aware
- * Each tenant has a Unique Identifier which is used to isolate interfaces/routes
- */
-public interface MultiTenantAwareRouter {
-
- void addInterface(UUID tenantId, String interfaceName, InetAddress address, int mask);
-
- void addInterface(UUID tenantId, String interfaceName, String macAddress, InetAddress address, int mask);
-
- void updateInterface(UUID tenantId, String interfaceName, InetAddress address, int mask);
-
- void updateInterface(UUID tenantId, String interfaceName, String macAddress, InetAddress address, int mask);
-
- void removeInterface(UUID tenantId, String interfaceName);
-
- void addRoute(UUID tenantId, String destinationCidr, InetAddress nextHop);
-
- void addRoute(UUID tenantId, String destinationCidr, InetAddress nextHop, Integer priority);
-
- void removeRoute(UUID tenantId, String destinationCidr, InetAddress nextHop);
-
- void removeRoute(UUID tenantId, String destinationCidr, InetAddress nextHop, Integer priority);
-
- void addDefaultRoute(UUID tenantId, InetAddress nextHop);
-
- void addDefaultRoute(UUID tenantId, InetAddress nextHop, Integer priority);
-
- void addNatRule(UUID tenantId, InetAddress matchAddress, InetAddress rewriteAddress);
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-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;
-
-/**
- * The NetworkingProvider interface is implemented by Neutron Networking Providers
- */
-public interface NetworkingProvider {
-
- /**
- * @return the name of the NetworkingProvider
- */
- String getName();
-
- /**
- * @return true if the provider supports Network Service Instances
- */
- boolean supportsServices();
-
- /**
- * @return true if the provider supports per-tenant or "static" tunneling
- */
- boolean hasPerTenantTunneling();
-
- /**
- * Handle Interface Update Callback Method
- * @param network Neutron Network attached to the interface
- * @param source Source node where interface is attached
- * @param intf Termination point attached to the node
- * @return true if interface update handled successfully
- */
- boolean handleInterfaceUpdate(NeutronNetwork network, Node source, OvsdbTerminationPointAugmentation intf);
-
- /**
- * Handle Interface Delete Callback Method
- * @param tunnelType Type of the tunnel (e.g. vxlan)
- * @param network Neutron Network associated with the removed interface
- * @param source Source node where interface was attached
- * @param intf Termination point associated to the deleted interface
- * @param isLastInstanceOnNode is last interface attached to the node ?
- * @param isMigratedPort is the Neutron Port associated with the removed interface is being migrated to a new node?
- * @return true if interface delete handled successfully
- */
- boolean handleInterfaceDelete(String tunnelType, NeutronNetwork network, Node source,
- OvsdbTerminationPointAugmentation intf, boolean isLastInstanceOnNode, boolean isMigratedPort);
-
- /**
- * Initialize the Flow rules given the OVSDB node.
- * This method provides a set of common functionalities to initialize the Flow rules of an OVSDB node
- * that are Openflow Version specific. Hence we have this method in addition to the following
- * Openflow Node specific initialization method.
- * @param node Node on which flow rules are going to be installed
- */
- void initializeFlowRules(Node node);
-
- /**
- * Initialize the Flow rules for a given OpenFlow node
- * @param openflowNode Node on which flow rules are going to be installed
- */
- void initializeOFFlowRules(Node openflowNode);
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-import org.osgi.framework.ServiceReference;
-
-/**
- * The NetworkingProviderManager handles the mapping between {@link Node}
- * and registered {@link NetworkingProvider} implementations
- */
-public interface NetworkingProviderManager {
- /**
- * Returns the Networking Provider for a given node
- * @param ovsdbNode a {@link Node}
- * @return a NetworkProvider
- * @see NetworkingProvider
- */
- NetworkingProvider getProvider(Node ovsdbNode);
- void providerAdded(final ServiceReference ref, final NetworkingProvider provider);
- void providerRemoved(final ServiceReference ref);
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-
-/**
- * When this interface is used, instance owner will get callbacks on
- * changes that occur in NodeCacheManager
- *
- * @author Flavio Fernandes (ffernand@redhat.com)
- * @author Sam Hague (shague@redhat.com)
- */
-public interface NodeCacheListener {
- void notifyNode(Node node, Action action);
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-import java.util.List;
-import java.util.Map;
-
-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.network.topology.topology.Node;
-import org.osgi.framework.ServiceReference;
-
-/**
- * This interface is used to cache ids of nodes that are needed by net-virt.
- * The nodes are added and removed by an external listener.
- *
- * @author Flavio Fernandes (ffernand@redhat.com)
- * @author Sam Hague (shague@redhat.com)
- */
-public interface NodeCacheManager {
- void nodeAdded(Node node);
- void nodeRemoved(Node node);
- Node getNode(NodeId nodeId);
- List<Node> getNodes();
- Map<NodeId, Node> getOvsdbNodes();
- List<Node> getBridgeNodes();
- List<Long> getBridgeDpids(final String bridgeName);
- void cacheListenerAdded(final ServiceReference ref, NodeCacheListener handler);
- void cacheListenerRemoved(final ServiceReference ref);
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-import java.net.InetAddress;
-
-/**
- * This interface allows NAT flows to be written to devices
- */
-public interface OutboundNatProvider {
- Status programIpRewriteRule(Long dpidLong,
- String matchSegmentationId,
- String matchDestMacAddress,
- InetAddress matchSrcAddress,
- String rewriteSrcMacAddress,
- String rewriteDestMacAddress,
- InetAddress rewriteSrcAddress,
- Long OutPort,
- Action action);
-
- Status programIpRewriteExclusion(Long dpid, String segmentationId,
- String excludedCidr, Action action);
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-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.DataObject;
-
-public interface OvsdbInventoryListener {
- enum OvsdbType {
- NODE,
- ROW,
- OPENVSWITCH,
- BRIDGE,
- CONTROLLER,
- PORT
- }
- void ovsdbUpdate(Node node, DataObject augmentationDataChanges, OvsdbType type, Action action);
- void triggerUpdates();
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-/**
- * OvsdbInventoryService is the interface to the southbound for netvirt.
- *
- * @author Sam Hague (shague@redhat.com)
- */
-public interface OvsdbInventoryService {
- void listenerAdded(OvsdbInventoryListener listener);
- void listenerRemoved(OvsdbInventoryListener listener);
- void providersReady();
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-public class OvsdbPluginException extends RuntimeException {
- public OvsdbPluginException(String message){
- super(message);
- }
-
- public OvsdbPluginException(String message, Throwable cause){
- super(message, cause);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-/**
- * Enum for OVSDB tables
- *
- * @author Sam Hague (shague@redhat.com)
- */
-public enum OvsdbTables {
- BRIDGE,
- CONTROLLER,
- OPENVSWITCH,
- PORT
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 NEC Corporation 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.netvirt.openstack.netvirt.api;
-
-/**
- * This interface to resubmit the flows to ACL learn and Egress service.
- */
-public interface ResubmitAclLearnProvider {
- Status programResubmit(Long dpid);
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-import java.net.InetAddress;
-
-/**
- * A Router
- */
-public interface Router {
-
- void addInterface(String interfaceName, InetAddress address, int mask);
-
- void addInterface(String interfaceName, String macAddress, InetAddress address, int mask);
-
- void updateInterface(String interfaceName, InetAddress address, int mask);
-
- void updateInterface(String interfaceName, String macAddress, InetAddress address, int mask);
-
- void removeInterface(String interfaceName);
-
- void addRoute(String destinationCidr, InetAddress nextHop);
-
- void addRoute(String destinationCidr, InetAddress nextHop, Integer priority);
-
- void removeRoute(String destinationCidr, InetAddress nextHop);
-
- void removeRoute(String destinationCidr, InetAddress nextHop, Integer priority);
-
- void addDefaultRoute(InetAddress nextHop);
-
- void addDefaultRoute(InetAddress nextHop, Integer priority);
-
- void addNatRule(InetAddress matchAddress, InetAddress rewriteAddress);
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-import java.net.InetAddress;
-
-/**
- * This interface allows Routing flows to be written to devices
- */
-public interface RoutingProvider {
-
- Status programRouterInterface(Long dpid, String srcSegId, String dstSegId, String macAddress,
- InetAddress address, int mask, Action action);
-
- Status programDefaultRouteEntry(Long dpid, String segmentationId, String macAddress,
- InetAddress nextHop, Action action);
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 HP, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
-
-/**
- * This interface maintain a mapping between the security group and the ports
- * have this security group as a remote security group. Whenever a new port is
- * added with a security group associated with it, a rule will be added to allow
- * traffic from/to the vm from the vms which has the former as a remote sg in its rule.
- *
- * @author Aswin Suryanarayanan.
- */
-
-public interface SecurityGroupCacheManger {
-
- /**
- * Notifies that a new port in the security group with securityGroupUuid.
- * @param securityGroupUuid the uuid of the security group associated with the port.
- * @param portUuid the uuid of the port.
- */
- void portAdded(String securityGroupUuid, String portUuid);
- /**
- * Notifies that a port is removed with the securityGroupUuid.
- * @param securityGroupUuid the uuid of the security group associated with the port.
- * @param portUuid the uuid of the port.
- */
- void portRemoved(String securityGroupUuid, String portUuid);
- /**
- * A port with portUuid has a reference remote security group remoteSgUuid will be added
- * to the cache maintained.
- * @param remoteSgUuid the remote security group uuid.
- * @param portUuid the uuid of the port.
- * @param nodeId the NodeId of the node.
- */
- void addToCache(String remoteSgUuid, String portUuid, NodeId nodeId);
- /**A port with portUUID has a reference remote security group remoteSgUuid will be removed
- * from the cache maintained.
- * @param remoteSgUuid the remote security group uuid.
- * @param portUuid portUUID the uuid of the port.
- * @param nodeId the NodeId of the node.
- */
- void removeFromCache(String remoteSgUuid, String portUuid, NodeId nodeId);
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityGroup;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityRule;
-import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs;
-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.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
-
-import java.util.List;
-import java.util.Map;
-
-/**
- * Open vSwitch isolates Tenant Networks using VLANs on the Integration Bridge.
- * This class manages the provisioning of these VLANs
- */
-public interface SecurityServicesManager {
- /**
- * Is port security ready.
- *
- * @param intf the intf
- * @return the boolean
- */
- boolean isPortSecurityReady(OvsdbTerminationPointAugmentation intf);
- /**
- * Gets security group in port.
- *
- * @param intf the intf
- * @return the list of security group in port, returns empty list if no group associated.
- */
- List<NeutronSecurityGroup> getSecurityGroupInPortList(OvsdbTerminationPointAugmentation intf);
- /**
- * Gets the DHCP server port corresponding to a network.
- *
- * @param intf the intf
- * @return the dhcp server port
- */
- NeutronPort getDhcpServerPort(OvsdbTerminationPointAugmentation intf);
- /**
- * Gets the NeutronPort from the cleanup cache.
- *
- * @param intf the intf
- * @return the NeutronPort stored in the cleanupCache of NeutronL3Adapter
- */
- NeutronPort getNeutronPortFromCache(OvsdbTerminationPointAugmentation intf);
-
- /**
- * Check if the given interface corresponds to a DHCP server port.
- *
- * @param intf the intf
- * @return Return the DHCP neutron port
- */
- NeutronPort getNeutronPortFromDhcpIntf(OvsdbTerminationPointAugmentation intf);
-
- /**
- * Is the port a compute port.
- *
- * @param intf the intf
- * @return whether it is a compute port or not
- */
- boolean isComputePort(OvsdbTerminationPointAugmentation intf);
-
- /**
- * Is this the last port in the subnet to which interface belongs to.
- * @param node The node to which the intf is connected.
- * @param intf the interface
- * @return whether last port in the subnet
- */
- boolean isLastPortinSubnet(Node node, OvsdbTerminationPointAugmentation intf);
-
- /**
- * Is this the last port in the bridge to which interface belongs to.
- * @param node The node to which the intf is connected.
- * @param intf the intf
- * @return whether last port in bridge
- */
- boolean isLastPortinBridge(Node node, OvsdbTerminationPointAugmentation intf);
- /**
- * Returns the list of ip address assigned to the interface.
- * @param intf the intf
- * @return the list of ip address associated with the vm
- */
- List<Neutron_IPs> getIpAddressList(OvsdbTerminationPointAugmentation intf);
- /**
- * Get the list of vm belonging to a security group.
- * @param portUuid the uuid of the port.
- * @param securityGroupUuid the UUID of the remote security group.
- * @return the list of all vm belonging to the security group UUID passed.
- */
- List<Neutron_IPs> getVmListForSecurityGroup(String portUuid,
- String securityGroupUuid);
- /**
- * Add or remove the security groups from the port.
- * @param port the neutron port.
- * @param securityGroup the security group associated with the port.
- * @param write whether to add/delete flow.
- */
- void syncSecurityGroup(NeutronPort port, List<NeutronSecurityGroup> securityGroup, boolean write);
- /**
- * Add or remove the fixed security groups from the port.
- * @param port the neutron port.
- * @param write whether to add/delete flow.
- */
- void syncFixedSecurityGroup(NeutronPort port, boolean write);
- /**
- * Add or remove individual security rules from the port.
- * @param port the neutron port.
- * @param securityRule the security group associated with the port.
- * @param vmIp The list of remote vm ips.
- * @param nodeId the NodeId of the node.
- * @param write whether to add/delete flow.
- */
- void syncSecurityRule(NeutronPort port, NeutronSecurityRule securityRule, Neutron_IPs vmIp, NodeId nodeId,
- boolean write);
- /**
- * Is connection tracking enabled or not by the user (default is false).
- * @return whether connection tracking enabled.
- */
- boolean isConntrackEnabled();
- /**
- * Is the port a PortSecurity Enabled.
- *
- * @param intf the port
- * @return whether it is a compute port or not
- */
- boolean isPortSecurityEnabled(OvsdbTerminationPointAugmentation intf);
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (c) 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-import java.util.List;
-import java.util.Map;
-
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.DatapathTypeBase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbTerminationPointAugmentation;
-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.port._interface.attributes.Options;
-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.network.topology.Topology;
-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.node.TerminationPoint;
-
-/**
- * Utility class to wrap southbound transactions.
- *
- * @author Sam Hague (shague@redhat.com)
- */
-public interface Southbound {
- ConnectionInfo getConnectionInfo(Node node);
- OvsdbNodeAugmentation extractOvsdbNode(Node node);
- NodeId extractBridgeOvsdbNodeId(Node bridgeNode);
- List<Node> readOvsdbTopologyNodes();
- List<Node> readOvsdbTopologyBridgeNodes();
- Node readOvsdbNode(Node bridgeNode);
- boolean isBridgeOnOvsdbNode(Node node, String bridgeName);
- String getOvsdbNodeUUID(Node node);
- String getOsdbNodeExternalIdsValue(OvsdbNodeAugmentation ovsdbNodeAugmentation, String key);
- boolean addBridge(Node ovsdbNode, String bridgeName, List<String> controllersStr,
- final Class<? extends DatapathTypeBase> dpType);
- boolean addBridge(Node ovsdbNode, String bridgeName, List<String> controllersStr,
- final Class<? extends DatapathTypeBase> dpType, String mac);
- boolean deleteBridge(Node ovsdbNode);
- OvsdbBridgeAugmentation readBridge(Node node, String name);
- Node readBridgeNode(Node node, String name);
- Node getBridgeNode(Node node, String bridgeName);
- String getBridgeUuid(Node node, String name);
- long getDataPathId(Node node);
- String getDatapathId(Node node);
- String getDatapathId(OvsdbBridgeAugmentation ovsdbBridgeAugmentation);
- OvsdbBridgeAugmentation getBridge(Node node, String name);
- OvsdbBridgeAugmentation getBridge(Node node);
- String getBridgeName(Node node);
- String extractBridgeName(Node node);
- OvsdbBridgeAugmentation extractBridgeAugmentation(Node node);
- List<Node> getAllBridgesOnOvsdbNode(Node node);
- OvsdbNodeAugmentation extractNodeAugmentation(Node node);
- List<OvsdbTerminationPointAugmentation> getTerminationPointsOfBridge(Node node);
- OvsdbTerminationPointAugmentation getTerminationPointOfBridge(Node node, String terminationPoint);
- OvsdbTerminationPointAugmentation extractTerminationPointAugmentation(Node bridgeNode, String portName);
- List<TerminationPoint> extractTerminationPoints(Node node);
- List<OvsdbTerminationPointAugmentation> extractTerminationPointAugmentations(Node node);
- List<OvsdbTerminationPointAugmentation> readTerminationPointAugmentations(Node node);
- String getInterfaceExternalIdsValue(
- OvsdbTerminationPointAugmentation terminationPointAugmentation, String key);
- Boolean addTerminationPoint(Node bridgeNode, String bridgeName, String portName, String type);
- Boolean deleteTerminationPoint(Node bridgeNode, String portName);
- Boolean addTerminationPoint(Node bridgeNode, String bridgeName, String portName,
- String type, Map<String, String> options);
- TerminationPoint readTerminationPoint(Node bridgeNode, String bridgeName, String portName);
- Boolean addTunnelTerminationPoint(Node bridgeNode, String bridgeName, String portName, String type,
- Map<String, String> options);
- Boolean isTunnelTerminationPointExist(Node bridgeNode, String bridgeName, String portName);
- Boolean addPatchTerminationPoint(Node node, String bridgeName, String portName, String peerPortName);
- String getExternalId(Node node, OvsdbTables table, String key);
- String getOtherConfig(Node node, OvsdbTables table, String key);
- boolean addVlanToTp(long vlan);
- boolean isTunnel(OvsdbTerminationPointAugmentation port);
- String getOptionsValue(List<Options> options, String key);
- Topology getOvsdbTopology();
- Long getOFPort(OvsdbTerminationPointAugmentation port);
- Long getOFPort(Node bridgeNode, String portName);
- DataBroker getDatabroker();
- OvsdbBridgeAugmentation getBridgeFromConfig(Node ovsdbNode, String bridgeName);
- Node readConfigBridge(Node node, String name);
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-import java.io.Serializable;
-
-/**
- * Represents the return object of the osgi service interfaces function calls.
- * It contains a code {@code StatusCode} representing the result of the call and
- * a string which describes a failure reason (if any) in human readable form.
- */
-public class Status implements Serializable {
- private static final long serialVersionUID = 0L;
- private StatusCode code;
- private String description;
- private long requestId;
-
- /**
- * Generates an instance of the Status class. This is used as return code
- * for internal API2 function calls. This constructor allows to specify,
- * beside the Status Code, a custom human readable description to add more
- * information about the status.
- *
- * @param errorCode
- * The status code. If passed as null, code will be stored as
- * {@code StatusCode.UNDEFINED}
- * @param description
- * The human readable description of the status. If passed as
- * null, description will be inferred by the code
- */
- public Status(StatusCode errorCode, String description) {
- this.code = (errorCode != null) ? errorCode : StatusCode.UNDEFINED;
- this.description = (description != null) ? description : this.code
- .toString();
- this.requestId = 0;
- }
-
- /**
- * Generates an instance of the Status class based on the passed StatusCode
- * only. The description field of the Status object will be inferred by the
- * status code.
- *
- * @param errorCode
- * The status code. If passed as null, code will be stored as
- * {@code StatusCode.UNDEFINED}
- */
- public Status(StatusCode errorCode) {
- this.code = (errorCode != null) ? errorCode : StatusCode.UNDEFINED;
- this.description = (description != null) ? description : this.code
- .toString();
- this.requestId = 0;
- }
-
- /**
- * Generates an instance of the Status class to be used in case of
- * asynchronous call. It is supposed to be created by the underlying
- * infrastructure only when it was successful in allocating the asynchronous
- * request id, hence caller should expect StatusCode to be successful.
- *
- * @param errorCode
- * The status code. If passed as null, code will be stored as
- * {@code StatusCode.UNDEFINED}
- * @param requestId
- * The request id set by underlying infrastructure for this
- * request
- */
- public Status(StatusCode errorCode, long requestId) {
- this.code = (errorCode != null) ? errorCode : StatusCode.UNDEFINED;
- this.description = (description != null) ? description : this.code
- .toString();
- this.requestId = requestId;
- }
-
- /**
- * Returns the status code
- *
- * @return the {@code StatusCode} representing the status code
- */
- public StatusCode getCode() {
- return code;
- }
-
- /**
- * Returns a human readable description of the failure if any
- *
- * @return a string representing the reason of failure
- */
- public String getDescription() {
- return description;
- }
-
- /**
- * Tells whether the status is successful
- *
- * @return true if the Status code is {@code StatusCode.SUCCESS}
- */
- public boolean isSuccess() {
- return code == StatusCode.SUCCESS || code == StatusCode.CREATED;
- }
-
- /**
- * Return the request id assigned by underlying infrastructure in case of
- * asynchronous request. In case of synchronous requests, the returned id
- * is expected to be 0
- *
- * @return The request id assigned for this asynchronous request
- */
- public long getRequestId() {
- return requestId;
- }
-
- @Override
- public String toString() {
- return code + ": " + description + " (" + requestId + ")";
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((code == null) ? 0 : code.calculateConsistentHashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- Status other = (Status) obj;
- if (code != other.code) {
- return false;
- }
- return true;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-/**
- * The enum which describes the generic error conditions.
- * Each enum value is associated with a minimal description string.
- *
- */
-public enum StatusCode {
- SUCCESS("Success"),
- CREATED("Created"),
-
- BADREQUEST("Bad Request"),
- UNAUTHORIZED("UnAuthorized"),
- FORBIDDEN("Forbidden"),
- NOTFOUND("Not Found"),
- NOTALLOWED("Method Not Allowed"),
- NOTACCEPTABLE("Request Not Acceptable"),
- TIMEOUT("Request Timeout"),
- CONFLICT("Resource Conflict"),
- GONE("Resource Gone"),
- UNSUPPORTED("Unsupported"),
-
- INTERNALERROR("Internal Error"),
- NOTIMPLEMENTED("Not Implemented"),
- NOSERVICE("Service Not Available"),
-
- UNDEFINED("Undefined Error");
-
- private String description;
- StatusCode(String description) {
- this.description = description;
- }
-
- /**
- * Prints the description associated to the code value
- */
- @Override
- public String toString() {
- return description;
- }
-
- public int calculateConsistentHashCode() {
- if (this.description != null) {
- return this.description.hashCode();
- } else {
- return 0;
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-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;
-
-/**
- * Open vSwitch isolates Tenant Networks using VLANs on the Integration Bridge
- * This class manages the provisioning of these VLANs
- *
- * @author Dave Tucker
- * @author Sam Hague (shague@redhat.com)
- */
-public interface TenantNetworkManager {
-
- /**
- * Get the VLAN assigned to the provided Network
- * @param node the {@link Node} to query
- * @param networkId the Neutron Network ID
- * @return the assigned VLAN ID or 0 in case of an error
- */
- int getInternalVlan(Node node, String networkId);
-
- /**
- * Reclaim the assigned VLAN for the given Network
- * @param node the {@link Node} to query
- * @param network the Neutron Network ID
- */
- void reclaimInternalVlan(Node node, NeutronNetwork network);
-
- /**
- * Configures the VLAN for a Tenant Network
- * @param node the {@link Node} to configure
- * @param tp the termination point
- * @param network the Neutron Network ID
- */
- void programInternalVlan(Node node, OvsdbTerminationPointAugmentation tp, NeutronNetwork network);
-
- /**
- * Check is the given network is present on a Node
- * @param node the {@link Node} to query
- * @param segmentationId the Neutron Segementation ID
- * @return True or False
- */
- boolean isTenantNetworkPresentInNode(Node node, String segmentationId);
-
- /**
- * Get the Neutron Network ID for a given Segmentation ID
- * @param segmentationId segmentation id of the neutron network
- * @return Neutron network id associated with the given segmentation id
- */
- String getNetworkId(String segmentationId);
-
- /**
- * Network Created Callback
- * @param node target node
- * @param networkId Id of neutron network
- * @return vlan assigned to the network
- */
- int networkCreated(Node node, String networkId);
-
- /**
- * Network Deleted Callback
- * @param id Id of the neutron network
- */
- void networkDeleted(String id);
- NeutronNetwork getTenantNetwork(OvsdbTerminationPointAugmentation terminationPointAugmentation);
- NeutronPort getTenantPort(OvsdbTerminationPointAugmentation terminationPointAugmentation);
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.api;
-
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-
-/**
- * This cache stores the VLAN assignments used for tenant separation within a vSwitch
- * An assignment consists of a VLAN ID and a tenant network ID.
- */
-public interface VlanConfigurationCache {
-
- /**
- * Assigns a free VLAN ID for the given tenant network
- * @param node an Open vSwitch {@link Node}
- * @param networkId the Neutron Network ID
- * @return a VLAN ID or 0 in case of an error
- */
- Integer assignInternalVlan(Node node, String networkId);
-
- /**
- * Recovers an assigned VLAN ID when it is no longer required
- * @param node an Open vSwitch {@link Node}
- * @param networkId the Neutron Network ID
- * @return the reclaimed VLAN ID or 0 in case of an error
- */
- Integer reclaimInternalVlan(Node node, String networkId);
-
- /**
- * Returns a VLAN ID assigned to a given tenant network
- * @param node an Open vSwitch {@link Node}
- * @param networkId the Neutron Network ID
- * @return the VLAN ID or 0 in case of an error
- */
- Integer getInternalVlan(Node node, String networkId);
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 NEC Corporation 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.netvirt.openstack.netvirt.api;
-
-import java.util.Map;
-import java.util.Set;
-
-/**
- * This interface allows Vlan flows to be written to devices
- */
-public interface VlanResponderProvider {
- /**
- * Creates provider network flows for internal bridge.
- *
- * @param dpidLong dp Id
- * @param segmentationId segmentation id
- * @param patchPort patch port of internal bridge
- * @param ofPort of port value
- * @param macAddress mac address
- * @param vlanProviderCache Initial VLAN cache with processing cache
- * @param write - flag to indicate the operation
- */
- void programProviderNetworkRulesInternal(Long dpidLong, String segmentationId, Long ofPort, Long patchPort,
- String macAddress, Map<String, Set<String>> vlanProviderCache, boolean write);
-
- /**
- * Creates provider network flows for external bridge.
- *
- * @param dpidLong dp id
- * @param segmentationId segmentation id
- * @param patchExtPort patch port of external bridge
- * @param macAddress mac address
- * @param vlanProviderCache Initial VLAN cache with processing cache
- * @param write - flag indicate the operation
- */
- void programProviderNetworkRulesExternal(Long dpidLong, String segmentationId, Long patchExtPort,
- String macAddress, Map<String, Set<String>> vlanProviderCache, boolean write);
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.impl;
-
-import com.google.common.base.Preconditions;
-import java.net.InetAddress;
-import java.net.NetworkInterface;
-import java.net.UnknownHostException;
-import java.util.ArrayList;
-import java.util.Enumeration;
-import java.util.List;
-import java.util.Random;
-import java.util.stream.Collectors;
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.opendaylight.netvirt.openstack.netvirt.NetworkHandler;
-import org.opendaylight.netvirt.openstack.netvirt.VLANProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.OvsdbTables;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.openstack.netvirt.ConfigInterface;
-import org.opendaylight.netvirt.openstack.netvirt.MdsalHelper;
-import org.opendaylight.netvirt.openstack.netvirt.NetworkHandler;
-import org.opendaylight.netvirt.openstack.netvirt.api.BridgeConfigurationManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.ConfigurationService;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-import org.opendaylight.netvirt.openstack.netvirt.api.NetworkingProviderManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.OvsdbTables;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.utils.config.ConfigProperties;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.DatapathTypeBase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.DatapathTypeNetdev;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation;
-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.ManagerEntry;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * @author Madhu Venugopal
- * @author Brent Salisbury
- * @author Sam Hague (shague@redhat.com)
- */
-public class BridgeConfigurationManagerImpl implements BridgeConfigurationManager, ConfigInterface {
- private static final Logger LOG = LoggerFactory.getLogger(BridgeConfigurationManagerImpl.class);
-
- // The implementation for each of these services is resolved by the OSGi Service Manager
- private volatile ConfigurationService configurationService;
- private volatile NetworkingProviderManager networkingProviderManager;
- private volatile Southbound southbound;
- private boolean intBridgeGenMac;
- private Random random;
-
- public BridgeConfigurationManagerImpl() {
- this(true);
- }
-
- public BridgeConfigurationManagerImpl(boolean intBridgeGenMac) {
- this.intBridgeGenMac = intBridgeGenMac;
- this.random = new Random(System.currentTimeMillis());
- }
-
- public void setConfigurationService(ConfigurationService configurationService) {
- this.configurationService = configurationService;
- }
-
- public void setSouthbound(Southbound southbound) {
- this.southbound = southbound;
- }
-
- @Override
- public String getBridgeUuid(Node node, String bridgeName) {
- return southbound.getBridgeUuid(node, bridgeName);
- }
-
- @Override
- public boolean isNodeNeutronReady(Node node) {
- Preconditions.checkNotNull(configurationService);
- return southbound.getBridge(node, configurationService.getIntegrationBridgeName()) != null;
- }
-
- @Override
- public boolean isNodeOverlayReady(Node node) {
- Preconditions.checkNotNull(configurationService);
- return isNodeNeutronReady(node)
- && southbound.getBridge(node, configurationService.getNetworkBridgeName()) != null;
- }
-
- @Override
- public boolean isPortOnBridge (Node bridgeNode, String portName) {
- return southbound.extractTerminationPointAugmentation(bridgeNode, portName) != null;
- }
-
- @Override
- public boolean isNodeTunnelReady(Node bridgeNode, Node ovsdbNode) {
- Preconditions.checkNotNull(configurationService);
- if (!southbound.isBridgeOnOvsdbNode(ovsdbNode, configurationService.getIntegrationBridgeName())) {
- LOG.trace("isNodeTunnelReady: node: {}, {} missing",
- bridgeNode, configurationService.getIntegrationBridgeName());
- return false;
- }
-
- return isNodeL3Ready(bridgeNode, ovsdbNode);
- }
-
- @Override
- public boolean isNodeVlanReady(Node bridgeNode, Node ovsdbNode, NeutronNetwork network) {
- Preconditions.checkNotNull(configurationService);
-
- final String brInt = configurationService.getIntegrationBridgeName();
- if (!southbound.isBridgeOnOvsdbNode(ovsdbNode, brInt)) {
- LOG.trace("isNodeVlanReady: node: {}, {} missing", bridgeNode, brInt);
- return false;
- }
-
- /* Check if physical device is added to br-int. */
- String phyNetName = getPhysicalInterfaceName(ovsdbNode, network.getProviderPhysicalNetwork());
- if (!isPortOnBridge(bridgeNode, phyNetName)) {
- LOG.trace("isNodeVlanReady: node: {}, eth missing", bridgeNode);
- return false;
- }
-
- return isNodeL3Ready(bridgeNode, ovsdbNode);
- }
-
- public boolean isNodeL3Ready(Node bridgeNode, Node ovsdbNode) {
- Preconditions.checkNotNull(configurationService);
- boolean ready = false;
- if (configurationService.isL3ForwardingEnabled()) {
- final String brInt = configurationService.getIntegrationBridgeName();
- final String brExt = configurationService.getExternalBridgeName();
- final String portNameInt = configurationService.getPatchPortName(new ImmutablePair<>(brInt, brExt));
- final String portNameExt = configurationService.getPatchPortName(new ImmutablePair<>(brExt, brInt));
- Preconditions.checkNotNull(portNameInt);
- Preconditions.checkNotNull(portNameExt);
-
- if (southbound.isBridgeOnOvsdbNode(ovsdbNode, brExt)) {
- ready = isNetworkPatchCreated(bridgeNode, southbound.readBridgeNode(ovsdbNode, brExt));
- } else {
- LOG.trace("isNodeL3Ready: node: {}, {} missing",
- bridgeNode, brExt);
- }
- } else {
- ready = true;
- }
- return ready;
- }
-
- @Override
- public void prepareNode(Node ovsdbNode) {
- Preconditions.checkNotNull(configurationService);
-
- try {
- createIntegrationBridge(ovsdbNode);
- } catch (Exception e) {
- LOG.error("Error creating Integration Bridge on {}", ovsdbNode, e);
- return;
- }
-
- try {
- if (configurationService.isL3ForwardingEnabled()) {
- createExternalBridge(ovsdbNode);
- } else if (configurationService.isL3MultipleExternalNetworkEnabled()) {
- String brExt = getMultipleExternalBridge(ovsdbNode);
- if (brExt == null) {
- LOG.warn("The provider mapping external network bridge name is null");
- return;
- }
- //get external bridge
- Node extBridgeNode = southbound.readBridgeNode(ovsdbNode, brExt);
- LOG.trace("External bridge details in operational data store:extBridgeNode:{}", extBridgeNode);
- if (extBridgeNode == null) {
- LOG.warn("External bridge is not created:{}", brExt);
- return;
- }
- //get internal bridge
- String brInt = configurationService.getIntegrationBridgeName();
- if (!addBridge(ovsdbNode, brExt, null)) {
- LOG.warn("Multiple External Bridge Creation failed");
- return;
- }
- configurationService.setExternalBridgeName(brExt);
- Node internalOvsdbNode = southbound.readConfigBridge(ovsdbNode, brInt);
- LOG.trace("Internal bridge details in config data store:internalOvsdbNode:{}", internalOvsdbNode);
- if (internalOvsdbNode == null) {
- LOG.warn("Internal Bridge is null in config datastore:{}", brInt);
- return;
- }
- //Processing an external bridge
- String portNameExt = VLANProvider.getPatchPortName(brExt);
- LOG.trace("prepareNode: portNameExt:{}", portNameExt);
- final String portNameInt = Constants.PATCH_PORT_TO_INTEGRATION_BRIDGE_NAME;
- Preconditions.checkNotNull(portNameInt);
- Preconditions.checkNotNull(portNameExt);
- if (!addPatchPort(internalOvsdbNode, brInt, portNameExt, portNameInt)) {
- LOG.error("Add Port {} to Bridge {} failed", portNameInt, brInt);
- return;
- }
- if (!addPatchPort(extBridgeNode, brExt, portNameInt, portNameExt)) {
- LOG.error("Add Port {} to Bridge {} failed", portNameExt, brExt);
- return;
- }
- LOG.info("Multiple external bridge is successfully created:{}", brExt);
- }
- } catch (Exception e) {
- LOG.error("Error creating External Bridge on {}", ovsdbNode, e);
- return;
- }
- // this node is an ovsdb node so it doesn't have a bridge
- // so either look up the bridges or just wait for the bridge update to come in
- // and add the flows there.
- //networkingProviderManager.getProvider(node).initializeFlowRules(node);
- }
-
- /**
- * Check if the full network setup is available. If not, create it.
- */
- @Override
- public boolean createLocalNetwork (Node bridgeNode, NeutronNetwork network) {
- boolean isCreated = false;
- Node ovsdbNode = southbound.readOvsdbNode(bridgeNode);
- if (ovsdbNode == null) {
- //this should never happen
- LOG.error("createLocalNetwork could not find ovsdbNode from bridge node {}", bridgeNode);
- return false;
- }
- if (network.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VLAN)) {
- if (!isNodeVlanReady(bridgeNode, ovsdbNode, network)) {
- try {
- isCreated = createBridges(bridgeNode, ovsdbNode, network);
- } catch (Exception e) {
- LOG.error("Error creating internal vlan net network {}--{}", bridgeNode, network, e);
- }
- } else {
- isCreated = true;
- }
- } else if (network.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VXLAN) ||
- network.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_GRE)) {
- if (!isNodeTunnelReady(bridgeNode, ovsdbNode)) {
- try {
- isCreated = createBridges(bridgeNode, ovsdbNode, network);
- } catch (Exception e) {
- LOG.error("Error creating internal vxlan/gre net network {}--{}", bridgeNode, network, e);
- }
- } else {
- isCreated = true;
- }
- }
- return isCreated;
- }
-
-
-
- @Override
- public String getExternalInterfaceName (Node node, String extNetwork) {
- String phyIf = null;
- String providerMaps = southbound.getOtherConfig(node, OvsdbTables.OPENVSWITCH,
- configurationService.getProviderMappingsKey());
- if (providerMaps != null) {
- for (String map : providerMaps.split(",")) {
- String[] pair = map.split(":");
- if (pair[0].equals(extNetwork)) {
- phyIf = pair[1];
- break;
- }
- }
- }
- if (phyIf == null) {
- LOG.error("External interface not found for Node: {}, Network {}",
- node, extNetwork);
- }
- else {
- LOG.info("External interface found for Node: {}, Network {} is {}",node,extNetwork,phyIf);
- }
- return phyIf;
- }
-
-
-
- @Override
- public String getPhysicalInterfaceName (Node node, String physicalNetwork) {
- String phyIf = null;
- String providerMaps = southbound.getOtherConfig(node, OvsdbTables.OPENVSWITCH,
- configurationService.getProviderMappingsKey());
- if (providerMaps == null) {
- providerMaps = configurationService.getDefaultProviderMapping();
- }
-
- if (providerMaps != null) {
- for (String map : providerMaps.split(",")) {
- String[] pair = map.split(":");
- if (pair[0].equals(physicalNetwork)) {
- phyIf = pair[1];
- break;
- }
- }
- }
-
- if (phyIf == null) {
- LOG.error("Physical interface not found for Node: {}, Network {}",
- node, physicalNetwork);
- }
-
- return phyIf;
- }
-
- @Override
- public List<String> getAllPhysicalInterfaceNames(Node node) {
- List<String> phyIfNames = new ArrayList<>();
- String providerMaps = southbound.getOtherConfig(node, OvsdbTables.OPENVSWITCH,
- configurationService.getProviderMappingsKey());
- if (providerMaps == null) {
- if (configurationService.isL3MultipleExternalNetworkEnabled()) {
- return phyIfNames;
- }
- providerMaps = configurationService.getDefaultProviderMapping();
- }
-
- if (providerMaps != null) {
- for (String map : providerMaps.split(",")) {
- String[] pair = map.split(":");
- phyIfNames.add(pair[1]);
- }
- }
-
- return phyIfNames;
- }
-
- /**
- * Returns true if a patch port exists between the Integration Bridge and Network Bridge
- */
- private boolean isNetworkPatchCreated(Node intBridge, Node netBridge) {
- Preconditions.checkNotNull(configurationService);
-
- boolean isPatchCreated = false;
-
- String portName = configurationService.getPatchPortName(new ImmutablePair<>(intBridge, netBridge));
- if (isPortOnBridge(intBridge, portName)) {
- portName = configurationService.getPatchPortName(new ImmutablePair<>(netBridge, intBridge));
- if (isPortOnBridge(netBridge, portName)) {
- isPatchCreated = true;
- }
- }
-
- return isPatchCreated;
- }
-
- /**
- * Creates the Integration Bridge
- */
- private boolean createIntegrationBridge(Node ovsdbNode) {
- Preconditions.checkNotNull(configurationService);
-
- if (!addBridge(ovsdbNode, configurationService.getIntegrationBridgeName(),
- intBridgeGenMac ? generateRandomMac() : null)) {
- LOG.debug("Integration Bridge Creation failed");
- return false;
- }
- return true;
- }
-
- private String generateRandomMac() {
- byte[] macBytes = new byte[6];
- random.nextBytes(macBytes);
- macBytes[0] &= 0xfc; //the two low bits of the first byte need to be zero
-
- StringBuilder stringBuilder = new StringBuilder();
-
- int i = 0;
- while(true) {
- stringBuilder.append(String.format("%02x", macBytes[i++]));
- if (i >= 6) {
- break;
- }
- stringBuilder.append(':');
- }
-
- return stringBuilder.toString();
- }
-
- private boolean createExternalBridge(Node ovsdbNode) {
- Preconditions.checkNotNull(configurationService);
-
- if (!addBridge(ovsdbNode, configurationService.getExternalBridgeName(), null)) {
- LOG.debug("External Bridge Creation failed");
- return false;
- }
- return true;
- }
-
- /**
- * Create and configure bridges for all network types and OpenFlow versions.
- *
- OF 1.0 vlan:
- Bridge br-int
- Port patch-net
- Interface patch-net
- type: patch
- options: {peer=patch-int}
- Port br-int
- Interface br-int
- type: internal
- Bridge br-net
- Port "eth1"
- Interface "eth1"
- Port patch-int
- Interface patch-int
- type: patch
- options: {peer=patch-net}
- Port br-net
- Interface br-net
- type: internal
-
- OF 1.0 tunnel:
- Bridge br-int
- Port patch-net
- Interface patch-net
- type: patch
- options: {peer=patch-int}
- Port br-int
- Interface br-int
- type: internal
- Bridge "br-net"
- Port patch-int
- Interface patch-int
- type: patch
- options: {peer=patch-net}
- Port br-net
- Interface br-net
- type: internal
-
- OF 1.3 vlan:
- Bridge br-int
- Port "eth1"
- Interface "eth1"
- Port br-int
- Interface br-int
- type: internal
-
- OF 1.3 tunnel:
- Bridge br-int
- Port br-int
- Interface br-int
- type: internal
- */
- private boolean createBridges(Node bridgeNode, Node ovsdbNode, NeutronNetwork network) {
- Preconditions.checkNotNull(configurationService);
- Preconditions.checkNotNull(networkingProviderManager);
-
- LOG.debug("createBridges: node: {}, network type: {}", bridgeNode, network.getProviderNetworkType());
-
- final String brInt = configurationService.getIntegrationBridgeName();
- if (! createIntegrationBridge(ovsdbNode)) {
- LOG.debug("{} Bridge creation failed", brInt);
- return false;
- }
-
- if (configurationService.isL3ForwardingEnabled()) {
- final String brExt = configurationService.getExternalBridgeName();
- if (! createExternalBridge(ovsdbNode)) {
- LOG.error("{} Bridge creation failed", brExt);
- return false;
- }
-
- //get two patch port names
- final String portNameInt = configurationService.getPatchPortName(new ImmutablePair<>(brInt, brExt));
- final String portNameExt = configurationService.getPatchPortName(new ImmutablePair<>(brExt, brInt));
- Preconditions.checkNotNull(portNameInt);
- Preconditions.checkNotNull(portNameExt);
-
- if (!addPatchPort(bridgeNode, brInt, portNameInt, portNameExt)) {
- LOG.error("Add Port {} to Bridge {} failed", portNameInt, brInt);
- return false;
- }
- Node extBridgeNode = southbound.readBridgeNode(ovsdbNode, brExt);
- Preconditions.checkNotNull(extBridgeNode, "br-ex cannot be null or empty!");
- if (!addPatchPort(extBridgeNode, brExt, portNameExt, portNameInt)) {
- LOG.error("Add Port {} to Bridge {} failed", portNameExt, brExt);
- return false;
- }
- String extNetName = getExternalInterfaceName(extBridgeNode, brExt);
- if ( extNetName != null) {
- if (!addPortToBridge(extBridgeNode, brExt, extNetName)) {
- LOG.error("Add External Port {} to Bridge {} failed", extNetName, brExt);
- return false;
- }
- LOG.info("Add External Port {} to Ext Bridge {} success", extNetName, brExt);
- }
- }
- /* For vlan network types add physical port to br-int. */
- if (network.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VLAN)) {
- String phyNetName = this.getPhysicalInterfaceName(bridgeNode, network.getProviderPhysicalNetwork());
- if (!addPortToBridge(bridgeNode, brInt, phyNetName)) {
- LOG.debug("Add Port {} to Bridge {} failed", phyNetName, brInt);
- return false;
- }
- }
-
- LOG.info("createBridges: node: {}, status: success", bridgeNode);
- return true;
- }
-
- /**
- * Add a Port to a Bridge
- */
- private boolean addPortToBridge (Node node, String bridgeName, String portName) {
- boolean rv = true;
-
- if (southbound.extractTerminationPointAugmentation(node, portName) == null) {
- rv = southbound.addTerminationPoint(node, bridgeName, portName, null);
-
- if (rv) {
- LOG.info("addPortToBridge: node: {}, bridge: {}, portname: {} status: success",
- node.getNodeId().getValue(), bridgeName, portName);
- } else {
- LOG.error("addPortToBridge: node: {}, bridge: {}, portname: {} status: FAILED",
- node.getNodeId().getValue(), bridgeName, portName);
- }
- } else {
- LOG.trace("addPortToBridge: node: {}, bridge: {}, portname: {} status: not_needed",
- node.getNodeId().getValue(), bridgeName, portName);
- }
-
- return rv;
- }
-
- /**
- * Add a Patch Port to a Bridge
- */
- private boolean addPatchPort (Node node, String bridgeName, String portName, String peerPortName) {
- boolean rv = true;
- if (configurationService.isL3MultipleExternalNetworkEnabled() ||
- southbound.extractTerminationPointAugmentation(node, portName) == null) {
- rv = southbound.addPatchTerminationPoint(node, bridgeName, portName, peerPortName);
- if (rv) {
- LOG.info("addPatchPort: node: {}, bridge: {}, portname: {} peer: {} status: success",
- node.getNodeId().getValue(), bridgeName, portName, peerPortName);
- } else {
- LOG.error("addPatchPort: node: {}, bridge: {}, portname: {} peer: {} status: FAILED",
- node.getNodeId().getValue(), bridgeName, portName, peerPortName);
- }
- } else {
- LOG.trace("addPatchPort: node: {}, bridge: {}, portname: {} peer: {} status: not_needed",
- node.getNodeId().getValue(), bridgeName, portName, peerPortName);
- }
- return rv;
- }
-
- /**
- * Add Bridge to a Node
- */
- private boolean addBridge(Node ovsdbNode, String bridgeName, String mac) {
- boolean rv = true;
- boolean isBridgeInConfig = (southbound.getBridgeFromConfig(ovsdbNode, bridgeName) != null);
- Node bridgeNode = southbound.readBridgeNode(ovsdbNode, bridgeName);
-
- if (bridgeNode == null || !isBridgeInConfig) {
- Class<? extends DatapathTypeBase> dpType = null;
- if (configurationService.isUserSpaceEnabled()) {
- dpType = DatapathTypeNetdev.class;
- }
-
- // if the bridge is already on the OVS node, use the existing MAC address
- // because changing the MAC causes the dpid to change on the switch, which
- // in turn causes a connection flap (see bugs 6070, 6944)
- rv = southbound.addBridge(ovsdbNode, bridgeName, getControllersFromOvsdbNode(ovsdbNode), dpType,
- bridgeNode == null ? mac : southbound.getOtherConfig(bridgeNode, OvsdbTables.BRIDGE, MdsalHelper.HWADDR));
- }
- return rv;
- }
-
- 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, e);
- }
- }
-
- 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, e);
- }
- }
-
- 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, e);
- }
- }
- return openFlowPort;
- }
-
- public 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 = String.valueOf(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()) {
- LOG.debug("Found {} OpenFlow Controller(s): {}", controllersStr.size(),
- controllersStr.stream().collect(Collectors.joining(" ")));
- }
-
- return controllersStr;
- }
-
- private String getLocalControllerHostIpAddress() {
- String ipaddress = null;
- try{
- 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() && inetAddr.isSiteLocalAddress()) {
- ipaddress = inetAddr.getHostAddress();
- break;
- }
- }
- }
- }catch (Exception e){
- LOG.warn("Exception while fetching local host ip address ", e);
- }
- return ipaddress;
- }
-
- @Override
- public void setDependencies(ServiceReference serviceReference) {
- configurationService =
- (ConfigurationService) ServiceHelper.getGlobalInstance(ConfigurationService.class, this);
- networkingProviderManager =
- (NetworkingProviderManager) ServiceHelper.getGlobalInstance(NetworkingProviderManager.class, this);
- southbound =
- (Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this);
- }
-
- @Override
- public void setDependencies(Object impl) {
- }
-
- @Override
- public String getMultipleExternalBridge(Node ovsdbNode) {
- String brExt = null;
- List<String> phyIfNames = this.getAllPhysicalInterfaceNames(ovsdbNode);
- LOG.debug("getMultipleExternalBridge phyIfName::{}", phyIfNames);
- if (phyIfNames.size() > 0) {
- brExt = phyIfNames.get(0);
- LOG.debug("Provider Mapping: external bridge name:{}", brExt);
- }
- if (brExt == null || brExt.isEmpty()) {
- LOG.warn("The provider mapping external network bridge name is null");
- return null;
- }
- return brExt;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.impl;
-
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.HashMap;
-import java.util.Map;
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.apache.commons.lang3.tuple.Pair;
-import org.opendaylight.netvirt.openstack.netvirt.ConfigInterface;
-import org.opendaylight.netvirt.openstack.netvirt.api.ConfigurationService;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-import org.opendaylight.netvirt.openstack.netvirt.api.OvsdbTables;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.utils.config.ConfigProperties;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ConfigurationServiceImpl implements ConfigurationService, ConfigInterface {
- private static final Logger LOG = LoggerFactory.getLogger(ConfigurationServiceImpl.class);
-
- private String integrationBridgeName;
- private String networkBridgeName;
- private String externalBridgeName;
- private String tunnelEndpointKey;
-
- private Map<Pair<String, String>, String> patchPortNames = new HashMap<>();
- private String providerMappingsKey;
- private String providerMapping;
- private Southbound southbound;
-
- public ConfigurationServiceImpl() {
- tunnelEndpointKey = Constants.TUNNEL_ENDPOINT_KEY;
- integrationBridgeName = Constants.INTEGRATION_BRIDGE;
- networkBridgeName = Constants.NETWORK_BRIDGE;
- externalBridgeName = Constants.EXTERNAL_BRIDGE;
- patchPortNames.put(new ImmutablePair<>(integrationBridgeName, networkBridgeName),
- Constants.PATCH_PORT_TO_NETWORK_BRIDGE_NAME);
- patchPortNames.put(new ImmutablePair<>(networkBridgeName, integrationBridgeName),
- Constants.PATCH_PORT_TO_INTEGRATION_BRIDGE_NAME);
- patchPortNames.put(new ImmutablePair<>(integrationBridgeName, externalBridgeName),
- Constants.PATCH_PORT_TO_EXTERNAL_BRIDGE_NAME);
- patchPortNames.put(new ImmutablePair<>(externalBridgeName, integrationBridgeName),
- Constants.PATCH_PORT_TO_INTEGRATION_BRIDGE_NAME);
- providerMappingsKey = Constants.PROVIDER_MAPPINGS_KEY;
- providerMapping = Constants.PROVIDER_MAPPING;
- }
-
- @Override
- public String getIntegrationBridgeName() {
- return integrationBridgeName;
- }
-
- @Override
- public void setIntegrationBridgeName(String integrationBridgeName) {
- this.integrationBridgeName = integrationBridgeName;
- }
-
- @Override
- public String getNetworkBridgeName() {
- return networkBridgeName;
- }
-
- @Override
- public void setNetworkBridgeName(String networkBridgeName) {
- this.networkBridgeName = networkBridgeName;
- }
-
- @Override
- public String getExternalBridgeName() {
- return externalBridgeName;
- }
-
- @Override
- public void setExternalBridgeName(String externalBridgeName) {
- this.externalBridgeName = externalBridgeName;
- }
-
- @Override
- public String getTunnelEndpointKey() {
- return tunnelEndpointKey;
- }
-
- @Override
- public void setTunnelEndpointKey(String tunnelEndpointKey) {
- this.tunnelEndpointKey = tunnelEndpointKey;
- }
-
- @Override
- public String getProviderMappingsKey() {
- return providerMappingsKey;
- }
-
- @Override
- public void setProviderMappingsKey(String providerMappingsKey) {
- this.providerMappingsKey = providerMappingsKey;
- }
-
- @Override
- public Map<Pair<String, String>, String> getPatchPortNames() {
- return patchPortNames;
- }
-
- @Override
- public void setPatchPortNames(Map<Pair<String, String>, String> patchPortNames) {
- this.patchPortNames = patchPortNames;
- }
-
- @Override
- public String getPatchPortName(Pair portTuple){
- return this.patchPortNames.get(portTuple);
- }
-
- @Override
- public String getDefaultProviderMapping() {
- return providerMapping;
- }
-
- @Override
- public void setDefaultProviderMapping(String providerMapping) {
- this.providerMapping = providerMapping;
- }
-
- @Override
- public InetAddress getTunnelEndPoint(Node node) {
- InetAddress address = null;
- String tunnelEndpoint = southbound.getOtherConfig(node, OvsdbTables.OPENVSWITCH, tunnelEndpointKey);
- if (tunnelEndpoint != null) {
- try {
- address = InetAddress.getByName(tunnelEndpoint);
- LOG.debug("Tunnel Endpoint for Node {} {}", node, address.getHostAddress());
- } catch (UnknownHostException e) {
- LOG.error("Error populating Tunnel Endpoint for Node {} ", node, e);
- }
- }
- return address;
- }
-
- @Override
- public String getOpenflowVersion(Node node) {
- return Constants.OPENFLOW13;
- }
-
- @Override
- public boolean isL3ForwardingEnabled() {
- final String enabledPropertyStr = ConfigProperties.getProperty(this.getClass(), "ovsdb.l3.fwd.enabled");
- return enabledPropertyStr != null && enabledPropertyStr.equalsIgnoreCase("yes");
- }
-
- @Override
- public boolean isDistributedArpDisabled() {
- final String strARPDisabled = ConfigProperties.getProperty(this.getClass(), "ovsdb.l3.arp.responder.disabled");
- return strARPDisabled != null && strARPDisabled.equalsIgnoreCase("yes");
- }
-
- @Override
- public boolean isRemoteMacLearnEnabled() {
- final String enabledPropertyStr = ConfigProperties.getProperty(this.getClass(), "ovsdb.remotemac.learn.enabled");
- return enabledPropertyStr != null && enabledPropertyStr.equalsIgnoreCase("yes");
- }
-
- @Override
- public boolean isL3MultipleExternalNetworkEnabled() {
- final String enabledPropertyStr = ConfigProperties.getProperty(this.getClass(), "ovsdb.l3.multiple.network.enabled");
- return enabledPropertyStr != null && enabledPropertyStr.equalsIgnoreCase("yes");
- }
-
- @Override
- public String getDefaultGatewayMacAddress(Node node) {
- String l3gatewayForNode = null;
- if (node != null) {
- l3gatewayForNode = ConfigProperties.getProperty(this.getClass(),
- "ovsdb.l3gateway.mac." + node.getNodeId().getValue());
- }
- if (l3gatewayForNode == null) {
- l3gatewayForNode = ConfigProperties.getProperty(this.getClass(), "ovsdb.l3gateway.mac");
- }
- return l3gatewayForNode;
- }
-
- @Override
- public boolean isUserSpaceEnabled() {
- final String enabledPropertyStr = ConfigProperties.getProperty(this.getClass(), "ovsdb.userspace.enabled");
- return enabledPropertyStr != null && enabledPropertyStr.equalsIgnoreCase("yes");
- }
-
- @Override
- public void setDependencies(ServiceReference serviceReference) {
- southbound =
- (Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this);
- }
-
- @Override
- public void setDependencies(Object impl) {
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 NEC Corporation 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.netvirt.openstack.netvirt.impl;
-
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.RejectedExecutionException;
-import java.util.concurrent.ThreadFactory;
-
-import com.google.common.base.Preconditions;
-import com.google.common.util.concurrent.ThreadFactoryBuilder;
-
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.ArpProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.ConfigurationService;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.Status;
-import org.opendaylight.netvirt.openstack.netvirt.api.StatusCode;
-import org.opendaylight.netvirt.openstack.netvirt.api.TenantNetworkManager;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronNetworkCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronPortCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.openstack.netvirt.ConfigInterface;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs;
-import org.opendaylight.netvirt.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.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * ARP flows programmed for Neutron port.
- */
-public class DistributedArpService implements ConfigInterface {
-
- private static final Logger LOG = LoggerFactory.getLogger(DistributedArpService.class);
- private static final String DHCP_DEVICE_OWNER = "network:dhcp";
- private static final String ROUTER_INTERFACE_DEVICE_OWNER = "network:router_interface";
- private static final int NUM_THREADS = 5;
- // The implementation for each of these services is resolved by the OSGi Service Manager
- private volatile ConfigurationService configurationService;
- private volatile TenantNetworkManager tenantNetworkManager;
- private volatile NodeCacheManager nodeCacheManager;
- private volatile INeutronNetworkCRUD neutronNetworkCache;
- private volatile INeutronPortCRUD neutronPortCache;
- private volatile ArpProvider arpProvider;
- private volatile NeutronL3Adapter neutronL3Adapter;
-
- private Southbound southbound;
- private Boolean flgDistributedARPEnabled = true;
-
- private HashMap<String, List<Neutron_IPs>> dhcpPortIpCache = new HashMap();
-
- static ThreadFactory threadFactory = new ThreadFactoryBuilder()
- .setNameFormat("DistributedArp-%d").build();
- static ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS, threadFactory);
-
-
- private void initMembers() {
- Preconditions.checkNotNull(configurationService);
- if (configurationService.isDistributedArpDisabled()) {
- this.flgDistributedARPEnabled = false;
- LOG.debug("Distributed ARP responder is disabled");
- } else {
- LOG.debug("Distributed ARP responder is enabled");
- }
- }
-
- /**
- * Process the port event to write Arp rules for neutron ports.
- *
- * @param action the {@link Action} action to be handled.
- * @param isMigratedPort true, if the port is migrated else false.
- * @param bridgeNode the node for the port.
- * @param neutronPort An instance of NeutronPort object.
- */
- public void handlePortEvent(NeutronPort neutronPort, Node bridgeNode, boolean isMigratedPort, Action action) {
- LOG.debug("neutronPort Event {} action event {} ", neutronPort, action);
- this.handleNeutronPortForArp(neutronPort, bridgeNode, isMigratedPort, action);
- }
-
- /**
- * Arp rules are added/removed based on neutron port event
- *
- */
- boolean programStaticRuleStage1(Long dpid, String segOrOfPort,
- String macAddress, String ipStr,
- Action action) {
- if (action == Action.DELETE ) {
- LOG.trace("Deleting Flow : programStaticArpStage1 dpid {} segOrOfPort {} mac {} ip {} action {}",
- dpid, segOrOfPort, macAddress, ipStr, action);
- }
- if (action == Action.ADD) {
- LOG.trace("Adding Flow : programStaticArpStage1 dpid {} segOrOfPort {} mac {} ip {} action {}",
- dpid, segOrOfPort, macAddress, ipStr, action);
- }
-
- Status status = this.programStaticRuleStage2(dpid, segOrOfPort, macAddress, ipStr, action);
- return status.isSuccess();
- }
-
- /**
- * Arp rules are programmed by invoke arpProvider
- *
- */
- private Status programStaticRuleStage2(Long dpid,
- String segOrOfPort,
- String macAddress,
- String address,
- Action action) {
- Status status;
- try {
- InetAddress inetAddress = InetAddress.getByName(address);
- status = arpProvider == null ?
- new Status(StatusCode.SUCCESS) :
- arpProvider.programStaticArpEntry(dpid, segOrOfPort,
- macAddress, inetAddress, action);
- } catch (UnknownHostException e) {
- status = new Status(StatusCode.BADREQUEST);
- }
-
- if (status.isSuccess()) {
- LOG.debug("programStaticRuleStage2 {} for mac:{} addr:{} dpid:{} segOrOfPort:{} action:{}",
- arpProvider == null ? "skipped" : "programmed",
- macAddress, address, dpid, segOrOfPort, action);
- } else {
- LOG.warn("programStaticRuleStage2 failed for mac:{} addr:{} dpid:{} segOrOfPort:{} action:{} status:{}",
- macAddress, address, dpid, segOrOfPort, action, status);
- }
- return status;
- }
-
- /**
- * Write Arp rules based on event for neutron port.
- *
- * @param action the {@link Action} action to be handled.
- * @param isMigratedPort true, if the port is migrated else false.
- * @param bridgeNode the node for the port.
- * @param neutronPort An instance of NeutronPort object.
- */
- private void handleNeutronPortForArp(NeutronPort neutronPort, Node bridgeNode, boolean isMigratedPort, Action action) {
- if (!flgDistributedARPEnabled) {
- return;
- }
-
- //treat UPDATE as ADD
- final Action actionToPerform = action == Action.DELETE ? Action.DELETE : Action.ADD;
- final String providerSegmentationId = getSegmentationId(neutronPort);
- if (providerSegmentationId == null || providerSegmentationId.isEmpty()) {
- return;
- }
- List<Node> nodes = nodeCacheManager.getBridgeNodes();
- if (nodes.isEmpty()) {
- LOG.trace("updateL3ForNeutronPort has no nodes to work with");
- }
- String owner = neutronPort.getDeviceOwner();
- boolean isDhcpPort = owner != null && owner.equals(DHCP_DEVICE_OWNER);
- for (Node node : nodes) {
- if(actionToPerform == Action.DELETE && !isDhcpPort &&
- (isMigratedPort && !bridgeNode.getNodeId().equals(node.getNodeId()))) {
- continue;
- }
- handleArpRule(node, neutronPort, providerSegmentationId, isMigratedPort, actionToPerform);
- }
- }
-
- private void handleArpRule(Node node, NeutronPort neutronPort,
- String providerSegmentationId, boolean isMigratedPort, Action actionToPerform) {
- String owner = neutronPort.getDeviceOwner();
- boolean isRouterInterface = owner != null && owner.equals(ROUTER_INTERFACE_DEVICE_OWNER);
- boolean isDhcpPort = owner != null && owner.equals(DHCP_DEVICE_OWNER);
- List<Neutron_IPs> fixedIps = neutronPort.getFixedIPs();
- if((null == fixedIps || fixedIps.isEmpty())
- && actionToPerform == Action.DELETE && isDhcpPort){
- fixedIps = dhcpPortIpCache.get(neutronPort.getPortUUID());
- if(fixedIps == null) {
- return;
- }
- }
- List <NeutronPort> neutronPortList = new ArrayList();
- // Arp rule is only needed when segmentation exists in the given node (bug 4752)
- // or in case the port is a router interface
- boolean isTenantNetworkPresentInNode = getNeutronPortsForNode(node, neutronPortList, providerSegmentationId);
- boolean arpNeeded = isRouterInterface || isTenantNetworkPresentInNode;
- final Action actionForNode = arpNeeded ? actionToPerform : Action.DELETE;
- NeutronPort existingPort = null;
- if (neutronPortList.size() == 1) {
- existingPort = neutronPortList.get(0);
- }
- final String macAddress = neutronPort.getMacAddress();
- if (macAddress == null || macAddress.isEmpty()) {
- // done: go no further w/out all the info needed...
- return;
- }
- final Long dpid = getDatapathIdIntegrationBridge(node);
- if (dpid == null) {
- return;
- }
- if (arpNeeded) {
- // For a node Arp rule is added for all ports only when the list of NeutronPorts size is 1.
- // If not Arp is added for the current port only (bug 6998)
- if (neutronPortList.size() == 1 && neutronPort.getPortUUID().equalsIgnoreCase(existingPort.getPortUUID())) {
- for (NeutronPort port : neutronPortCache.getAllPorts()) {
- final String portSegmentationId = getSegmentationId(port);
- if (portSegmentationId != null && portSegmentationId.equals(providerSegmentationId)) {
- final String portMacAddress = port.getMacAddress();
- for (Neutron_IPs neutronIPAddr : port.getFixedIPs()) {
- final String portIpAddress = neutronIPAddr.getIpAddress();
- try {
- executor.submit(() ->
- programStaticRuleStage1(dpid, providerSegmentationId, portMacAddress,
- portIpAddress, actionForNode));
- } catch (RejectedExecutionException ex) {
- LOG.error("handleArpRule : unable to accept execution.", ex);
- programStaticRuleStage1(dpid, providerSegmentationId, portMacAddress,
- portIpAddress, actionForNode);
- }
- }
- }
- }
- } else {
- if(!isMigratedPort) {
- for (Neutron_IPs neutronIPAddr : neutronPort.getFixedIPs()) {
- final String ipAddress = neutronIPAddr.getIpAddress();
- try {
- executor.submit(() ->
- programStaticRuleStage1(dpid, providerSegmentationId, macAddress,
- ipAddress, actionForNode));
- } catch (RejectedExecutionException ex) {
- LOG.error("handleArpRule : unable to accept execution.", ex);
- programStaticRuleStage1(dpid, providerSegmentationId, macAddress,
- ipAddress, actionForNode);
- }
- }
- }
- }
- } else {
- if (actionToPerform == Action.DELETE) {
- // Arp flows for DHCP port should remove from control node
- // when network removed (bug 7333).
- if (isDhcpPort) {
- for (Neutron_IPs neutronIP : fixedIps) {
- final String dhcpIpAddress = neutronIP.getIpAddress();
- if (dhcpIpAddress.isEmpty()) {
- continue;
- }
- try {
- executor.submit(() ->
- programStaticRuleStage1(dpid, providerSegmentationId, macAddress,
- dhcpIpAddress, actionToPerform));
- } catch (RejectedExecutionException ex) {
- LOG.error("handleArpRule : unable to accept execution.", ex);
- programStaticRuleStage1(dpid, providerSegmentationId, macAddress,
- dhcpIpAddress, actionToPerform);
- }
- }
- }
- for (NeutronPort delPort : neutronL3Adapter.getPortCleanupCache().values()) {
- if (!delPort.getDeviceOwner().equalsIgnoreCase(ROUTER_INTERFACE_DEVICE_OWNER)) {
- final String delMacAddress = delPort.getMacAddress();
- if (null == delMacAddress || delMacAddress.isEmpty()) {
- continue;
- }
- for (Neutron_IPs neutronIPAddr : delPort.getFixedIPs()) {
- final String delIpAddress = neutronIPAddr.getIpAddress();
- if (null == delIpAddress || delIpAddress.isEmpty()) {
- continue;
- }
- try {
- executor.submit(() ->
- programStaticRuleStage1(dpid, providerSegmentationId, delMacAddress,
- delIpAddress, actionToPerform));
- } catch (RejectedExecutionException ex) {
- LOG.error("handleArpRule : unable to accept execution.", ex);
- programStaticRuleStage1(dpid, providerSegmentationId, delMacAddress,
- delIpAddress, actionToPerform);
- }
- }
- }
- }
- }
- }
- if(isDhcpPort && actionToPerform == Action.ADD){
- dhcpPortIpCache.put(neutronPort.getPortUUID(), fixedIps);
- } else if (isDhcpPort && actionToPerform == Action.DELETE) {
- dhcpPortIpCache.remove(neutronPort.getPortUUID());
- }
- }
-
- /**
- * Check if node is integration bridge, then return its datapathID.
- * @param node An instance of Node object.
- */
- private Long getDatapathIdIntegrationBridge(Node node) {
- if (southbound.getBridge(node, configurationService.getIntegrationBridgeName()) != null) {
- return southbound.getDataPathId(node);
- }
- return null;
- }
-
- /**
- * Process the event.
- *
- * @param bridgeNode An instance of Node object.
- * @param intf An {@link org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105
- * .OvsdbTerminationPointAugmentation} instance of OvsdbTerminationPointAugmentation object.
- * @param neutronNetwork An {@link NeutronNetwork} instance of NeutronNetwork
- * object.
- * @param isMigratedPort true, if the port is migrated else false.
- * @param action the {@link Action} action to be handled.
- */
- public void processInterfaceEvent(final Node bridgeNode, final OvsdbTerminationPointAugmentation intf,
- final NeutronNetwork neutronNetwork, boolean isMigratedPort, Action action) {
- LOG.debug("southbound interface {} node:{} interface:{}, neutronNetwork:{}",
- action, bridgeNode.getNodeId().getValue(), intf.getName(), neutronNetwork);
- final NeutronPort neutronPort = tenantNetworkManager.getTenantPort(intf);
- if (neutronPort != null) {
- this.handlePortEvent(neutronPort, bridgeNode, isMigratedPort, action);
- }
- }
-
- @Override
- public void setDependencies(ServiceReference serviceReference) {
- tenantNetworkManager =
- (TenantNetworkManager) ServiceHelper.getGlobalInstance(TenantNetworkManager.class, this);
- configurationService =
- (ConfigurationService) ServiceHelper.getGlobalInstance(ConfigurationService.class, this);
- arpProvider =
- (ArpProvider) ServiceHelper.getGlobalInstance(ArpProvider.class, this);
- nodeCacheManager =
- (NodeCacheManager) ServiceHelper.getGlobalInstance(NodeCacheManager.class, this);
- southbound =
- (Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this);
- neutronL3Adapter =
- (NeutronL3Adapter) ServiceHelper.getGlobalInstance(NeutronL3Adapter.class, this);
- initMembers();
- }
-
- @Override
- public void setDependencies(Object impl) {
- if (impl instanceof INeutronNetworkCRUD) {
- neutronNetworkCache = (INeutronNetworkCRUD)impl;
- } else if (impl instanceof INeutronPortCRUD) {
- neutronPortCache = (INeutronPortCRUD)impl;
- } else if (impl instanceof ArpProvider) {
- arpProvider = (ArpProvider)impl;
- }
- }
-
- private boolean isInterfacePresentInTenantNetwork (String portId, String networkId) {
- NeutronPort neutronPort = neutronPortCache.getPort(portId);
- return neutronPort != null && neutronPort.getNetworkUUID().equalsIgnoreCase(networkId);
- }
-
- /**
- * Populates the list of neutron ports for node and
- * check whether the segId is available on node or not.
- *
- * @param Node An instance of Node object.
- * @param List<neutronPort> An instances list of NeutronPort object.
- * @param String value for segmentationId.
- */
- private boolean getNeutronPortsForNode(Node node, List<NeutronPort> neutronPortList, String segmentationId) {
- List<OvsdbTerminationPointAugmentation> ports = southbound.readTerminationPointAugmentations(node);
- boolean isTenantNetworkPresentInNode = false;
- String networkId = tenantNetworkManager.getNetworkId(segmentationId);
- for (OvsdbTerminationPointAugmentation port : ports) {
- if (networkId != null) {
- String ifaceId = southbound.getInterfaceExternalIdsValue(port, "iface-id");
- if (ifaceId != null && isInterfacePresentInTenantNetwork(ifaceId, networkId)) {
- LOG.debug("Tenant Network {} with Segmentation-id {} is present in Node {} / Interface {}",
- networkId, segmentationId, node, port);
- isTenantNetworkPresentInNode = true;
- }
- }
- NeutronPort neutronPort = tenantNetworkManager.getTenantPort(port);
- if (neutronPort != null) {
- final String portSegmentationId = getSegmentationId(neutronPort);
- if (portSegmentationId != null && portSegmentationId.equals(segmentationId)) {
- neutronPortList.add(neutronPort);
- }
- }
- }
- return isTenantNetworkPresentInNode;
- }
-
- /**
- * To get segmentationId.
- *
- * @param neutronPort An instance of NeutronPort object
- */
- private String getSegmentationId(NeutronPort neutronPort) {
- final String networkUUID = neutronPort.getNetworkUUID();
- NeutronNetwork neutronNetwork = neutronNetworkCache.getNetwork(networkUUID);
- if (null == neutronNetwork) {
- neutronNetwork = neutronL3Adapter.getNetworkFromCleanupCache(networkUUID);
- }
- final String portSegmentationId = neutronNetwork != null ?
- neutronNetwork.getProviderSegmentationID() : null;
- return portSegmentationId;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.impl;
-
-import com.google.common.util.concurrent.ThreadFactoryBuilder;
-import org.opendaylight.netvirt.openstack.netvirt.AbstractEvent;
-import org.opendaylight.netvirt.openstack.netvirt.AbstractHandler;
-import org.opendaylight.netvirt.openstack.netvirt.ConfigInterface;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-import org.opendaylight.netvirt.openstack.netvirt.api.EventDispatcher;
-
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.ThreadFactory;
-
-public class EventDispatcherImpl implements EventDispatcher, ConfigInterface {
- private static final Logger LOG = LoggerFactory.getLogger(EventDispatcher.class);
- private ExecutorService eventHandler;
- private volatile BlockingQueue<AbstractEvent> events;
- private AbstractHandler[] handlers;
-
- public EventDispatcherImpl() {
- events = new LinkedBlockingQueue<>();
- handlers = new AbstractHandler[AbstractEvent.HandlerType.size];
- ThreadFactory threadFactory = new ThreadFactoryBuilder()
- .setNameFormat("NV-EvtDsptchr-%d").build();
- eventHandler = Executors.newSingleThreadExecutor(threadFactory);
- start();
- }
-
- void start() {
- eventHandler.submit(() -> {
- Thread t = Thread.currentThread();
- t.setName("EventDispatcherImpl");
- LOG.info("EventDispatcherImpl: started {}", t.getName());
- while (true) {
- AbstractEvent ev;
- try {
- ev = events.take();
- } catch (InterruptedException e) {
- LOG.info("The event handler thread was interrupted, shutting down", e);
- return;
- }
- try {
- dispatchEvent(ev);
- } catch (Exception e) {
- LOG.error("Exception in dispatching event {}", ev.toString(), e);
- }
- }
- });
- LOG.debug("event dispatcher is started");
- }
-
- void stop() {
- // stop accepting new tasks
- eventHandler.shutdown();
- try {
- // Wait a while for existing tasks to terminate
- if (!eventHandler.awaitTermination(10, TimeUnit.SECONDS)) {
- eventHandler.shutdownNow();
- // Wait a while for tasks to respond to being cancelled
- if (!eventHandler.awaitTermination(10, TimeUnit.SECONDS)) {
- LOG.error("Dispatcher's event handler did not terminate");
- }
- }
- } catch (InterruptedException e) {
- // (Re-)Cancel if current thread also interrupted
- eventHandler.shutdownNow();
- // Preserve interrupt status
- Thread.currentThread().interrupt();
- }
- LOG.debug("event dispatcher is stopped");
- }
-
- private void dispatchEvent(AbstractEvent ev) {
- LOG.trace("dispatchEvent: Processing (id={}): Event : {}", ev.getTransactionId(), ev);
- AbstractHandler handler = handlers[ev.getHandlerType().ordinal()];
- if (handler == null) {
- LOG.warn("event dispatcher found no handler for : {}", ev);
- return;
- }
-
- handler.processEvent(ev);
- LOG.trace("dispatchEvent: Done processing (id={}): Event : {}", ev.getTransactionId(), ev);
- }
-
- public void eventHandlerAdded(final ServiceReference ref, AbstractHandler handler){
- Long pid = (Long) ref.getProperty(org.osgi.framework.Constants.SERVICE_ID);
- Object handlerTypeObject = ref.getProperty(Constants.EVENT_HANDLER_TYPE_PROPERTY);
- if (!(handlerTypeObject instanceof AbstractEvent.HandlerType)){
- // The exception should give us a stacktrace
- LOG.error("Abstract handler reg failed to provide a valid handler type: {} ref: {} handler: {}",
- handlerTypeObject, ref.getClass().getName(), handler.getClass().getName(),
- new IllegalArgumentException("Missing handler type"));
- return;
- }
- AbstractEvent.HandlerType handlerType = (AbstractEvent.HandlerType) handlerTypeObject;
- handlers[handlerType.ordinal()] = handler;
- LOG.debug("eventHandlerAdded: handler: {}, pid: {}, type: {}",
- handler.getClass().getName(), pid, handlerType);
- }
-
- public void eventHandlerRemoved(final ServiceReference ref){
- Long pid = (Long) ref.getProperty(org.osgi.framework.Constants.SERVICE_ID);
- Object handlerTypeObject = ref.getProperty(Constants.EVENT_HANDLER_TYPE_PROPERTY);
- if (!(handlerTypeObject instanceof AbstractEvent.HandlerType)){
- LOG.error("Abstract handler unreg failed to provide a valid handler type {}", handlerTypeObject);
- return;
- }
- AbstractEvent.HandlerType handlerType = (AbstractEvent.HandlerType) handlerTypeObject;
- handlers[handlerType.ordinal()] = null;
- LOG.debug("Event handler for type {} unregistered pid {}", handlerType, pid);
- }
-
- /**
- * Enqueue the event.
- *
- * @param event the {@link AbstractEvent} event to be handled.
- */
- @Override
- public void enqueueEvent(AbstractEvent event) {
- if (event == null) {
- LOG.warn("enqueueEvent: event is null");
- return;
- }
-
- try {
- events.put(event);
- } catch (InterruptedException e) {
- LOG.error("Thread was interrupted while trying to enqueue event ", e);
- }
- }
-
- @Override
- public void setDependencies(ServiceReference serviceReference) {}
-
- @Override
- public void setDependencies(Object impl) {}
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Intel Corporation. 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.netvirt.openstack.netvirt.impl;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.netvirt.openstack.netvirt.ClusterAwareMdsalUtils;
-import org.opendaylight.netvirt.openstack.netvirt.ConfigInterface;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.OvsdbInventoryListener;
-import org.opendaylight.netvirt.openstack.netvirt.api.OvsdbInventoryService;
-import org.opendaylight.netvirt.openstack.netvirt.api.OvsdbTables;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.hostconfig.rev150712.hostconfig.attributes.Hostconfigs;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.hostconfig.rev150712.hostconfig.attributes.hostconfigs.Hostconfig;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.hostconfig.rev150712.hostconfig.attributes.hostconfigs.HostconfigBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.OpenvswitchExternalIds;
-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.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-
-public class HostConfigService implements OvsdbInventoryListener, ConfigInterface {
- private static final Logger LOG = LoggerFactory.getLogger(HostConfigService.class);
-
- private static final String OS_HOST_CONFIG_HOST_ID_KEY = "odl_os_hostconfig_hostid";
- private static final String OS_HOST_CONFIG_CONFIG_KEY_PREFIX = "odl_os_hostconfig_config_odl_";
- private static int HOST_TYPE_STR_LEN = 8;
-
- private final DataBroker databroker;
- private final ClusterAwareMdsalUtils mdsalUtils;
- private volatile OvsdbInventoryService ovsdbInventoryService;
- private volatile Southbound southbound;
-
- public HostConfigService(DataBroker dataBroker) {
- this.databroker = dataBroker;
- mdsalUtils = new ClusterAwareMdsalUtils(dataBroker);
- }
-
- @Override
- public void ovsdbUpdate(Node node, DataObject resourceAugmentationData, OvsdbType ovsdbType, Action action) {
- if (ovsdbType != OvsdbType.NODE) {
- return;
- }
- LOG.trace("ovsdbUpdate: {} - {} - <<{}>> <<{}>>", ovsdbType, action, node, resourceAugmentationData);
- String hostId = southbound.getExternalId(node, OvsdbTables.OPENVSWITCH, OS_HOST_CONFIG_HOST_ID_KEY);
- if (hostId == null){
- return;
- }
- for(Map.Entry<String,String> entry : extractHostConfig(node).entrySet()) {
- ovsdbUpdateConfig(buildHostConfigInfo(hostId, entry.getKey(), entry.getValue()), action);
- }
- }
-
- @Override
- public void triggerUpdates() {
- List<Node> ovsdbNodes = southbound.readOvsdbTopologyNodes();
- for (Node node : ovsdbNodes) {
- ovsdbUpdate(node, node.getAugmentation(OvsdbNodeAugmentation.class),
- OvsdbInventoryListener.OvsdbType.NODE, Action.ADD);
- }
- }
-
- private Map<String, String> extractHostConfig(Node node) {
- OvsdbNodeAugmentation ovsdbNode = southbound.extractNodeAugmentation(node);
- Map<String, String> config = new HashMap<>();
- if (ovsdbNode == null) {
- Node nodeFromReadOvsdbNode = southbound.readOvsdbNode(node);
- if (nodeFromReadOvsdbNode != null) {
- ovsdbNode = southbound.extractNodeAugmentation(nodeFromReadOvsdbNode);
- }
- }
- if (ovsdbNode != null && ovsdbNode.getOpenvswitchExternalIds() != null) {
- for (OpenvswitchExternalIds openvswitchExternalIds : ovsdbNode.getOpenvswitchExternalIds()) {
- if (openvswitchExternalIds.getExternalIdKey().startsWith(OS_HOST_CONFIG_CONFIG_KEY_PREFIX)) {
- // Extract the host type. Max 8 characters after suffix OS_HOST_CONFIG_CONFIG_KEY_PREFIX.length()
- String hostType = openvswitchExternalIds.getExternalIdKey().substring(
- OS_HOST_CONFIG_CONFIG_KEY_PREFIX.length());
- if (null != hostType && hostType.length() > 0) {
- if (hostType.length() > HOST_TYPE_STR_LEN) {
- hostType = hostType.substring(0, HOST_TYPE_STR_LEN);
- }
- hostType = "ODL " + hostType.toUpperCase();
- if (null != openvswitchExternalIds.getExternalIdValue())
- config.put(hostType, openvswitchExternalIds.getExternalIdValue());
- }
- }
- }
- }
- return config;
- }
-
- private void ovsdbUpdateConfig(Hostconfig hostConfig, Action action) {
- boolean result;
- InstanceIdentifier<Hostconfig> hostConfigId;
- if (hostConfig == null) {
- return;
- }
- switch (action) {
- case ADD:
- case UPDATE:
- hostConfigId = createInstanceIdentifier(hostConfig);
- result = mdsalUtils.put(LogicalDatastoreType.OPERATIONAL, hostConfigId, hostConfig);
- LOG.trace("Add Node: result: {}", result);
- break;
- case DELETE:
- hostConfigId = createInstanceIdentifier(hostConfig);
- result = mdsalUtils.delete(LogicalDatastoreType.OPERATIONAL, hostConfigId);
- LOG.trace("Delete Node: result: {}", result);
- break;
- }
- }
-
- private Hostconfig buildHostConfigInfo(String hostId, String hostType, String hostConfig) {
- HostconfigBuilder hostconfigBuilder = new HostconfigBuilder();
- hostconfigBuilder.setHostId(hostId);
- hostconfigBuilder.setHostType(hostType);
- hostconfigBuilder.setConfig(hostConfig);
- return hostconfigBuilder.build();
- }
-
- private InstanceIdentifier<Hostconfig> createInstanceIdentifier() {
- return InstanceIdentifier.create(Neutron.class)
- .child(Hostconfigs.class)
- .child(Hostconfig.class);
- }
-
- private InstanceIdentifier<Hostconfig> createInstanceIdentifier(Hostconfig hostconfig) {
- return InstanceIdentifier.create(Neutron.class)
- .child(Hostconfigs.class)
- .child(Hostconfig.class, hostconfig.getKey());
- }
-
- @Override
- public void setDependencies(ServiceReference serviceReference) {
- southbound =
- (Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this);
- ovsdbInventoryService =
- (OvsdbInventoryService) ServiceHelper.getGlobalInstance(OvsdbInventoryService.class, this);
- ovsdbInventoryService.listenerAdded(this);
- }
-
- @Override
- public void setDependencies(Object impl) {
- }
-}
+++ /dev/null
-/*
- * Copyright © 2014, 2017 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.impl;
-
-import static org.opendaylight.netvirt.openstack.netvirt.api.Action.ADD;
-import static org.opendaylight.netvirt.openstack.netvirt.api.Action.DELETE;
-import static org.opendaylight.netvirt.openstack.netvirt.api.Action.UPDATE;
-
-import com.google.common.base.Preconditions;
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.apache.commons.lang3.tuple.Pair;
-import org.opendaylight.netvirt.openstack.netvirt.AbstractEvent;
-import org.opendaylight.netvirt.openstack.netvirt.AbstractHandler;
-import org.opendaylight.netvirt.openstack.netvirt.ConfigInterface;
-import org.opendaylight.netvirt.openstack.netvirt.NeutronL3AdapterEvent;
-import org.opendaylight.netvirt.openstack.netvirt.NeutronModelsDataStoreHelper;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.ArpProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.ConfigurationService;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-import org.opendaylight.netvirt.openstack.netvirt.api.EventDispatcher;
-import org.opendaylight.netvirt.openstack.netvirt.api.GatewayMacResolver;
-import org.opendaylight.netvirt.openstack.netvirt.api.GatewayMacResolverListener;
-import org.opendaylight.netvirt.openstack.netvirt.api.IcmpEchoProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.InboundNatProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.L3ForwardingProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.OutboundNatProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.RoutingProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.SecurityServicesManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.openstack.netvirt.api.Status;
-import org.opendaylight.netvirt.openstack.netvirt.api.StatusCode;
-import org.opendaylight.netvirt.openstack.netvirt.api.TenantNetworkManager;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronFloatingIP;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronRouter;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronRouter_Interface;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityGroup;
-import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronFloatingIPCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronNetworkCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronPortCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSubnet;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSubnetCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.impl.NeutronIAwareUtil;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.Routers;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.routers.Router;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.FixedIps;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.Ports;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.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.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.net.Inet4Address;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-
-/**
- * Neutron L3 Adapter implements a hub-like adapter for the various Neutron events. Based on
- * these events, the abstract router callbacks can be generated to the multi-tenant aware router,
- * as well as the multi-tenant router forwarding provider.
- */
-public class NeutronL3Adapter extends AbstractHandler implements GatewayMacResolverListener, ConfigInterface {
- private static final Logger LOG = LoggerFactory.getLogger(NeutronL3Adapter.class);
-
- // The implementation for each of these services is resolved by the OSGi Service Manager
- private volatile ConfigurationService configurationService;
- private volatile TenantNetworkManager tenantNetworkManager;
- private volatile NodeCacheManager nodeCacheManager;
- private volatile INeutronNetworkCRUD neutronNetworkCache;
- private volatile INeutronSubnetCRUD neutronSubnetCache;
- private volatile INeutronPortCRUD neutronPortCache;
- private volatile INeutronFloatingIPCRUD neutronFloatingIpCache;
- private volatile L3ForwardingProvider l3ForwardingProvider;
- private volatile InboundNatProvider inboundNatProvider;
- private volatile OutboundNatProvider outboundNatProvider;
- private volatile ArpProvider arpProvider;
- private volatile RoutingProvider routingProvider;
- private volatile GatewayMacResolver gatewayMacResolver;
- private volatile SecurityServicesManager securityServicesManager;
- private volatile IcmpEchoProvider icmpEchoProvider;
-
- private class FloatIpData {
- // br-int of node where floating ip is associated with tenant port
- private final Long dpid;
- // patch port in br-int used to reach br-ex
- private final Long ofPort;
- // segmentation id of the net where fixed ip is instantiated
- private final String segId;
- // mac address assigned to neutron port of floating ip
- private final String macAddress;
- private final String floatingIpAddress;
- // ip address given to tenant vm
- private final String fixedIpAddress;
- private final String neutronRouterMac;
-
- FloatIpData(final Long dpid, final Long ofPort, final String segId, final String macAddress,
- final String floatingIpAddress, final String fixedIpAddress, final String neutronRouterMac) {
- this.dpid = dpid;
- this.ofPort = ofPort;
- this.segId = segId;
- this.macAddress = macAddress;
- this.floatingIpAddress = floatingIpAddress;
- this.fixedIpAddress = fixedIpAddress;
- this.neutronRouterMac = neutronRouterMac;
- }
- }
-
- private Map<String, String> networkIdToRouterMacCache;
- private Map<String, List<Neutron_IPs>> networkIdToRouterIpListCache;
- private Map<String, NeutronRouter_Interface> subnetIdToRouterInterfaceCache;
-
- private Map<String, Pair<Long, Uuid>> neutronPortToDpIdCache;
- private Map<String, FloatIpData> floatIpDataMapCache;
-
- private String externalRouterMac;
- private Boolean enabled = false;
- private Boolean isCachePopulationDone = false;
- private ConcurrentMap<String, NeutronPort> portCleanupCache;
- private ConcurrentMap<String, NeutronNetwork> networkCleanupCache;
-
- private Southbound southbound;
- private DistributedArpService distributedArpService;
- private NeutronModelsDataStoreHelper neutronModelsDataStoreHelper;
-
- private static final String OWNER_ROUTER_INTERFACE = "network:router_interface";
- private static final String OWNER_ROUTER_INTERFACE_DISTRIBUTED = "network:router_interface_distributed";
- private static final String OWNER_ROUTER_GATEWAY = "network:router_gateway";
- private static final String OWNER_FLOATING_IP = "network:floatingip";
- private static final String DEFAULT_EXT_RTR_MAC = "00:00:5E:00:01:01";
-
- public NeutronL3Adapter(NeutronModelsDataStoreHelper neutronHelper) {
- LOG.info(">>>>>> NeutronL3Adapter constructor {}", this.getClass());
- this.neutronModelsDataStoreHelper = neutronHelper;
- }
-
- private void initL3AdapterMembers() {
- Preconditions.checkNotNull(configurationService);
-
- if (configurationService.isL3ForwardingEnabled()) {
- this.networkIdToRouterMacCache = new HashMap<>();
- this.networkIdToRouterIpListCache = new HashMap<>();
- this.subnetIdToRouterInterfaceCache = new HashMap<>();
- this.floatIpDataMapCache = new HashMap<>();
-
- this.externalRouterMac = configurationService.getDefaultGatewayMacAddress(null);
- if (this.externalRouterMac == null) {
- this.externalRouterMac = DEFAULT_EXT_RTR_MAC;
- }
- this.enabled = true;
- LOG.info("OVSDB L3 forwarding is enabled");
- } else {
- LOG.debug("OVSDB L3 forwarding is disabled");
- }
- this.neutronPortToDpIdCache = new HashMap<>();
- this.portCleanupCache = new ConcurrentHashMap<>();
- this.networkCleanupCache = new ConcurrentHashMap<>();
- }
-
- //
- // Callbacks from AbstractHandler
- //
- @Override
- public void processEvent(AbstractEvent abstractEvent) {
- if (!(abstractEvent instanceof NeutronL3AdapterEvent)) {
- LOG.error("Unable to process abstract event " + abstractEvent);
- return;
- }
- if (!this.enabled) {
- return;
- }
-
- NeutronL3AdapterEvent ev = (NeutronL3AdapterEvent) abstractEvent;
- switch (ev.getAction()) {
- case UPDATE:
- if (ev.getSubType() == NeutronL3AdapterEvent.SubType.SUBTYPE_EXTERNAL_MAC_UPDATE) {
- updateExternalRouterMac( ev.getMacAddress().getValue() );
- } else {
- LOG.warn("Received update for an unexpected event " + ev);
- }
- break;
- case ADD:
- // fall through...
- // break;
- case DELETE:
- // fall through...
- // break;
- default:
- LOG.warn("Unable to process event " + ev);
- break;
- }
- }
-
- //
- // Callbacks from GatewayMacResolverListener
- //
-
- @Override
- public void gatewayMacResolved(Long externalNetworkBridgeDpid, IpAddress gatewayIpAddress, MacAddress macAddress) {
- LOG.info("got gatewayMacResolved callback for ip {} on dpid {} to mac {}",
- gatewayIpAddress, externalNetworkBridgeDpid, macAddress);
- if (!this.enabled) {
- return;
- }
-
- if (macAddress == null || macAddress.getValue() == null) {
- // TODO: handle cases when mac is null
- return;
- }
-
- //
- // Enqueue event so update is handled by adapter's thread
- //
- enqueueEvent( new NeutronL3AdapterEvent(externalNetworkBridgeDpid, gatewayIpAddress, macAddress) );
- }
-
- private void populateL3ForwardingCaches() {
- if (!this.enabled) {
- return;
- }
- if(this.isCachePopulationDone || this.neutronFloatingIpCache == null
- || this.neutronPortCache == null ||this.neutronNetworkCache == null) {
- return;
- }
- this.isCachePopulationDone = true;
- LOG.debug("Populating NetVirt L3 caches from data store configuration");
- Routers routers = this.neutronModelsDataStoreHelper.readAllNeutronRouters();
- Ports ports = this.neutronModelsDataStoreHelper.readAllNeutronPorts();
- if(routers != null && routers.getRouter() != null && ports != null) {
- LOG.debug("L3 Cache Population : {} Neutron router present in data store",routers.getRouter().size());
- for( Router router : routers.getRouter()) {
- LOG.debug("L3 Cache Population : Populate caches for router {}",router);
- if(!ports.getPort().isEmpty()) {
- for( Port port : ports.getPort()) {
- if (port.getDeviceId().equals(router.getUuid().getValue()) &&
- port.getDeviceOwner().equals(OWNER_ROUTER_INTERFACE)) {
- LOG.debug("L3 Cache Population : Router interface {} found.",port);
- for (final FixedIps fixedIps : port.getFixedIps()) {
- if (fixedIps.getIpAddress().getIpv4Address() != null) {
- networkIdToRouterMacCache.put(port.getNetworkId().getValue(),
- port.getMacAddress().getValue());
- networkIdToRouterIpListCache.put(port.getNetworkId().getValue(),
- NeutronIAwareUtil.convertMDSalIpToNeutronIp(port.getFixedIps()));
- subnetIdToRouterInterfaceCache.put(port.getFixedIps().get(0).getSubnetId().getValue(),
- NeutronIAwareUtil.convertMDSalInterfaceToNeutronRouterInterface(port));
- break;
- }
- }
- }
- }
- }else {
- LOG.warn("L3 Cache Population :Did not find any port information " +
- "in config Data Store for router {}",router);
- }
- }
- }
- LOG.debug("NetVirt L3 caches population is done");
- }
-
- public Pair<Long, Uuid> getDpIdOfNeutronPort(String neutronTenantPortUuid) {
- if(neutronPortToDpIdCache.get(neutronTenantPortUuid) == null) {
- List<Node> bridges = this.southbound.readOvsdbTopologyBridgeNodes();
- LOG.debug("getDpIdOfNeutronPort : {} bridges present in ovsdb topology",bridges.size());
- for(Node bridge : bridges) {
- List<OvsdbTerminationPointAugmentation> interfaces
- = southbound.extractTerminationPointAugmentations(bridge);
- if(interfaces != null && !interfaces.isEmpty()) {
- LOG.debug("getDpIdOfNeutronPort : {} termination point present on bridge {}",
- interfaces.size(), bridge.getNodeId());
- for (OvsdbTerminationPointAugmentation intf : interfaces) {
- NeutronPort neutronPort = tenantNetworkManager.getTenantPort(intf);
- if(neutronPort != null && neutronPort.getID().equals(neutronTenantPortUuid)) {
- Long dpId = getDpidForIntegrationBridge(bridge);
- Uuid interfaceUuid = intf.getInterfaceUuid();
- LOG.debug("getDpIdOfNeutronPort : Found bridge {} and interface {} for the tenant neutron" +
- " port {}",dpId,interfaceUuid,neutronTenantPortUuid);
- handleInterfaceEventAdd(neutronPort.getPortUUID(), dpId, interfaceUuid);
- break;
- }
- }
- }
- }
- }
- return neutronPortToDpIdCache.get(neutronTenantPortUuid);
- }
-
- private Collection<FloatIpData> getAllFloatingIPsWithMetadata() {
- LOG.debug("getAllFloatingIPsWithMetadata : Fechting all floating Ips and it's metadata");
- List<NeutronFloatingIP> neutronFloatingIps = neutronFloatingIpCache.getAllFloatingIPs();
- if(neutronFloatingIps != null && !neutronFloatingIps.isEmpty()) {
- for (NeutronFloatingIP neutronFloatingIP : neutronFloatingIps) {
- if(!floatIpDataMapCache.containsKey(neutronFloatingIP.getID())){
- LOG.debug("Metadata for floating ip {} is not present in the cache. " +
- "Fetching from data store.",neutronFloatingIP.getID());
- this.getFloatingIPWithMetadata(neutronFloatingIP.getID());
- }
- }
- }
- LOG.debug("getAllFloatingIPsWithMetadata : {} floating points found in data store",floatIpDataMapCache.size());
- return floatIpDataMapCache.values();
- }
- private FloatIpData getFloatingIPWithMetadata(String neutronFloatingId) {
- LOG.debug("getFloatingIPWithMetadata : Get Floating ip and it's meta data for neutron " +
- "floating id {} ",neutronFloatingId);
- if(floatIpDataMapCache.get(neutronFloatingId) == null) {
- NeutronFloatingIP neutronFloatingIP = neutronFloatingIpCache.getFloatingIP(neutronFloatingId);
- if (neutronFloatingIP == null) {
- LOG.error("getFloatingIPWithMetadata : Floating ip {} is missing from data store, that should not happen",neutronFloatingId);
- return null;
- }
- List<NeutronPort> neutronPorts = neutronPortCache.getAllPorts();
- NeutronPort neutronPortForFloatIp = null;
- for (NeutronPort neutronPort : neutronPorts) {
- if (neutronPort.getDeviceOwner().equals(OWNER_FLOATING_IP) &&
- neutronPort.getDeviceID().equals(neutronFloatingIP.getID())) {
- neutronPortForFloatIp = neutronPort;
- break;
- }
- }
-
- String neutronTenantPortUuid = neutronFloatingIP.getPortUUID();
- if(neutronTenantPortUuid == null) {
- return null;
- }
- Pair<Long, Uuid> nodeIfPair = this.getDpIdOfNeutronPort(neutronTenantPortUuid);
- String floatingIpMac = neutronPortForFloatIp == null ? null : neutronPortForFloatIp.getMacAddress();
- String fixedIpAddress = neutronFloatingIP.getFixedIPAddress();
- String floatingIpAddress = neutronFloatingIP.getFloatingIPAddress();
-
- NeutronPort tenantNeutronPort = neutronPortCache.getPort(neutronTenantPortUuid);
- NeutronNetwork tenantNeutronNetwork = tenantNeutronPort != null ?
- neutronNetworkCache.getNetwork(tenantNeutronPort.getNetworkUUID()) : null;
- String providerSegmentationId = tenantNeutronNetwork != null ?
- tenantNeutronNetwork.getProviderSegmentationID() : null;
- String neutronRouterMac = tenantNeutronNetwork != null ?
- networkIdToRouterMacCache.get(tenantNeutronNetwork.getID()) : null;
-
- if (nodeIfPair == null || neutronTenantPortUuid == null ||
- providerSegmentationId == null || providerSegmentationId.isEmpty() ||
- floatingIpMac == null || floatingIpMac.isEmpty() ||
- neutronRouterMac == null || neutronRouterMac.isEmpty()) {
- LOG.debug("getFloatingIPWithMetadata :Floating IP {}<->{}, incomplete floatPort {} tenantPortUuid {} " +
- "seg {} mac {} rtrMac {}",
- fixedIpAddress,
- floatingIpAddress,
- neutronPortForFloatIp,
- neutronTenantPortUuid,
- providerSegmentationId,
- floatingIpMac,
- neutronRouterMac);
-
- return null;
- }
-
- // get ofport for patch port in br-int
- final Long dpId = nodeIfPair.getLeft();
- final Long ofPort = findOFPortForExtPatch(dpId);
- if (ofPort == null) {
- LOG.warn("getFloatingIPWithMetadata : Unable to locate OF port of patch port " +
- "to connect floating ip to external bridge. dpid {}",
- dpId);
- return null;
- }
-
- final FloatIpData floatIpData = new FloatIpData(dpId, ofPort, providerSegmentationId, floatingIpMac,
- floatingIpAddress, fixedIpAddress, neutronRouterMac);
- floatIpDataMapCache.put(neutronFloatingIP.getID(), floatIpData);
-
- }
- return floatIpDataMapCache.get(neutronFloatingId);
- }
- /**
- * Invoked to configure the mac address for the external gateway in br-ex. ovsdb netvirt needs help in getting
- * mac for given ip in br-ex (bug 3378). For example, since ovsdb has no real arp, it needs a service in can
- * subscribe so that the mac address associated to the gateway ip address is available.
- *
- * @param externalRouterMacUpdate The mac address to be associated to the gateway.
- */
- public void updateExternalRouterMac(final String externalRouterMacUpdate) {
- Preconditions.checkNotNull(externalRouterMacUpdate);
-
- flushExistingIpRewrite();
- this.externalRouterMac = externalRouterMacUpdate;
- rebuildExistingIpRewrite();
- }
-
- /**
- * Process the event.
- *
- * @param action the {@link Action} action to be handled.
- * @param subnet An instance of NeutronSubnet object.
- */
- public void handleNeutronSubnetEvent(final NeutronSubnet subnet, Action action) {
- LOG.debug("Neutron subnet {} event : {}", action, subnet.toString());
- if (action == ADD) {
- this.storeNetworkInCleanupCache(neutronNetworkCache.getNetwork(subnet.getNetworkUUID()));
- }
- }
-
- /**
- * Process the port event as a router interface event.
- * For a not delete action, since a port is only create when the tennat uses the subnet, it is required to
- * verify if all routers across all nodes have the interface for the port's subnet(s) configured.
- *
- * @param action the {@link Action} action to be handled.
- * @param neutronPort An instance of NeutronPort object.
- */
- public void handleNeutronPortEvent(final NeutronPort neutronPort, Action action) {
- LOG.debug("Neutron port {} event : {}", action, neutronPort.toString());
-
- if (action == UPDATE) {
- // FIXME: Bug 4971 Move cleanup cache to SG Impl
- this.updatePortInCleanupCache(neutronPort, neutronPort.getOriginalPort());
- if (neutronPort.getPortSecurityEnabled()) {
- this.processSecurityGroupUpdate(neutronPort);
- }
- if (isPortSecurityEnableUpdated(neutronPort)) {
- this.processPortSecurityEnableUpdated(neutronPort);
- }
- }
-
- if (!this.enabled) {
- return;
- }
-
- final boolean isDelete = action == DELETE;
-
- if (action == DELETE) {
- // Bug 5164: Cleanup Floating IP OpenFlow Rules when port is deleted.
- this.cleanupFloatingIPRules(neutronPort);
- }
- else if (action == UPDATE){
- // Bug 5353: VM restart cause floatingIp flows to be removed
- this.updateFloatingIPRules(neutronPort);
- }
-
- if (neutronPort.getDeviceOwner().equalsIgnoreCase(OWNER_ROUTER_GATEWAY)){
- if (!isDelete) {
- LOG.info("Port {} is network router gateway interface, "
- + "triggering gateway resolution for the attached external network", neutronPort);
- this.triggerGatewayMacResolver(neutronPort);
- }else{
- NeutronNetwork externalNetwork = neutronNetworkCache.getNetwork(neutronPort.getNetworkUUID());
- if (null == externalNetwork) {
- externalNetwork = this.getNetworkFromCleanupCache(neutronPort.getNetworkUUID());
- }
-
- if (externalNetwork != null && externalNetwork.isRouterExternal()) {
- final NeutronSubnet externalSubnet = getExternalNetworkSubnet(neutronPort);
- // TODO support IPv6
- if (externalSubnet != null &&
- externalSubnet.getIpVersion() == 4) {
- gatewayMacResolver.stopPeriodicRefresh(new Ipv4Address(externalSubnet.getGatewayIP()));
- }
- }
- }
- }
-
- // Treat the port event as a router interface event if the port belongs to router. This is a
- // helper for handling cases when handleNeutronRouterInterfaceEvent is not available
- //
- if (neutronPort.getDeviceOwner().equalsIgnoreCase(OWNER_ROUTER_INTERFACE) ||
- neutronPort.getDeviceOwner().equalsIgnoreCase(OWNER_ROUTER_INTERFACE_DISTRIBUTED)) {
-
- if (neutronPort.getFixedIPs() != null) {
- for (Neutron_IPs neutronIP : neutronPort.getFixedIPs()) {
- NeutronRouter_Interface neutronRouterInterface =
- new NeutronRouter_Interface(neutronIP.getSubnetUUID(), neutronPort.getPortUUID());
- // id of router interface to be same as subnet
- neutronRouterInterface.setID(neutronIP.getSubnetUUID());
- neutronRouterInterface.setTenantID(neutronPort.getTenantID());
-
- this.handleNeutronRouterInterfaceEvent(null /*neutronRouter*/, neutronRouterInterface, action);
- }
- }
- } else {
- // We made it here, port is not used as a router interface. If this is not a delete action, make sure that
- // all nodes that are supposed to have a router interface for the port's subnet(s), have it configured. We
- // need to do this check here because a router interface is not added to a node until tenant becomes needed
- // there.
- //
- if (!isDelete && neutronPort.getFixedIPs() != null) {
- for (Neutron_IPs neutronIP : neutronPort.getFixedIPs()) {
- NeutronRouter_Interface neutronRouterInterface =
- subnetIdToRouterInterfaceCache.get(neutronIP.getSubnetUUID());
- if (neutronRouterInterface != null) {
- this.handleNeutronRouterInterfaceEvent(null /*neutronRouter*/, neutronRouterInterface, action);
- }
- }
- }
- this.updateL3ForNeutronPort(neutronPort, isDelete);
- }
- }
-
- /**
- * Process the event.
- *
- * @param action the {@link Action} action to be handled.
- * @param neutronRouter An instance of NeutronRouter object.
- */
- public void handleNeutronRouterEvent(final NeutronRouter neutronRouter, Action action) {
- LOG.debug("Neutron router {} event : {}", action, neutronRouter.toString());
- }
-
- /**
- * Process the event enforcing actions and verifying dependencies between all router's interface. For example,
- * delete the ports on the same subnet.
- *
- * @param action the {@link Action} action to be handled.
- * @param neutronRouter An instance of NeutronRouter object.
- * @param neutronRouterInterface An instance of NeutronRouter_Interface object.
- */
- public void handleNeutronRouterInterfaceEvent(final NeutronRouter neutronRouter,
- final NeutronRouter_Interface neutronRouterInterface,
- Action action) {
- LOG.debug("Router interface {} got event {}. Subnet {}",
- neutronRouterInterface.getPortUUID(),
- action,
- neutronRouterInterface.getSubnetUUID());
- if (!this.enabled) {
- return;
- }
-
- final boolean isDelete = action == DELETE;
-
- this.programFlowsForNeutronRouterInterface(neutronRouterInterface, isDelete);
-
- // As neutron router interface is added/removed, we need to iterate through all the neutron ports and
- // see if they are affected by l3
- //
- for (NeutronPort neutronPort : neutronPortCache.getAllPorts()) {
- boolean currPortShouldBeDeleted = false;
- // Note: delete in this case only applies to 1)router interface delete and 2)ports on the same subnet
- if (isDelete) {
- if (neutronPort.getFixedIPs() != null) {
- for (Neutron_IPs neutronIP : neutronPort.getFixedIPs()) {
- if (neutronRouterInterface.getSubnetUUID().equalsIgnoreCase(neutronIP.getSubnetUUID())) {
- currPortShouldBeDeleted = true;
- break;
- }
- }
- }
- }
- this.updateL3ForNeutronPort(neutronPort, currPortShouldBeDeleted);
- }
-
- }
-
- /**
- * Invoked when a neutron message regarding the floating ip association is sent to odl via ml2. If the action is
- * a creation, it will first add ARP rules for the given floating ip and then configure the DNAT (rewrite the
- * packets from the floating IP address to the internal fixed ip) rules on OpenFlow Table 30 and SNAT rules (other
- * way around) on OpenFlow Table 100.
- *
- * @param actionIn the {@link Action} action to be handled.
- * @param neutronFloatingIP An {@link NeutronFloatingIP} instance of NeutronFloatingIP object.
- */
- public void handleNeutronFloatingIPEvent(final NeutronFloatingIP neutronFloatingIP,
- Action actionIn) {
- Preconditions.checkNotNull(neutronFloatingIP);
-
- LOG.debug(" Floating IP {} {}<->{}, network uuid {}", actionIn,
- neutronFloatingIP.getFixedIPAddress(),
- neutronFloatingIP.getFloatingIPAddress(),
- neutronFloatingIP.getFloatingNetworkUUID());
- if (!this.enabled) {
- return;
- }
-
- Action action;
-
- // Consider action to be delete if getFixedIPAddress is null
- //
- if (neutronFloatingIP.getFixedIPAddress() == null) {
- action = DELETE;
- } else {
- action = actionIn;
- }
-
- // this.programFlowsForFloatingIP(neutronFloatingIP, action == Action.DELETE);
-
- if (action != DELETE) {
- // must be first, as it updates floatIpDataMapCache
- programFlowsForFloatingIPArpAdd(neutronFloatingIP);
-
- programFlowsForFloatingIPInbound(neutronFloatingIP, ADD);
- programFlowsForFloatingIPOutbound(neutronFloatingIP, ADD);
- } else {
- programFlowsForFloatingIPOutbound(neutronFloatingIP, DELETE);
- programFlowsForFloatingIPInbound(neutronFloatingIP, DELETE);
-
- // must be last, as it updates floatIpDataMapCache
- programFlowsForFloatingIPArpDelete(neutronFloatingIP.getID());
- }
- }
-
- /**
- * This method performs creation or deletion of in-bound rules into Table 30 for a existing available floating
- * ip, otherwise for newer one.
- */
- private void programFlowsForFloatingIPInbound(final NeutronFloatingIP neutronFloatingIP, final Action action) {
- Preconditions.checkNotNull(neutronFloatingIP);
-
- final FloatIpData fid = getFloatingIPWithMetadata(neutronFloatingIP.getID());
- if (fid == null) {
- LOG.trace("programFlowsForFloatingIPInboundAdd {} for {} uuid {} not in local cache",
- action, neutronFloatingIP.getFloatingIPAddress(), neutronFloatingIP.getID());
- return;
- }
- programInboundIpRewriteStage1(fid.dpid, fid.ofPort, fid.segId, fid.floatingIpAddress, fid.fixedIpAddress,
- action);
- }
-
- /**
- * This method performs creation or deletion of out-bound rules into Table 100 for a existing available floating
- * ip, otherwise for newer one.
- */
- private void programFlowsForFloatingIPOutbound(final NeutronFloatingIP neutronFloatingIP, final Action action) {
- Preconditions.checkNotNull(neutronFloatingIP);
-
- final FloatIpData fid = getFloatingIPWithMetadata(neutronFloatingIP.getID());
- if (fid == null) {
- LOG.trace("programFlowsForFloatingIPOutbound {} for {} uuid {} not in local cache",
- action, neutronFloatingIP.getFloatingIPAddress(), neutronFloatingIP.getID());
- return;
- }
- programOutboundIpRewriteStage1(fid, action);
- }
-
- private void flushExistingIpRewrite() {
- for (FloatIpData fid : getAllFloatingIPsWithMetadata()) {
- programOutboundIpRewriteStage1(fid, DELETE);
- }
- }
-
- private void rebuildExistingIpRewrite() {
- for (FloatIpData fid : getAllFloatingIPsWithMetadata()) {
- programOutboundIpRewriteStage1(fid, ADD);
- }
- }
-
- /**
- * This method creates ARP response rules into OpenFlow Table 30 for a given floating ip. In order to connect
- * to br-ex from br-int, a patch-port is used. Thus, the patch-port will be responsible to respond the ARP
- * requests.
- */
- private void programFlowsForFloatingIPArpAdd(final NeutronFloatingIP neutronFloatingIP) {
- Preconditions.checkNotNull(neutronFloatingIP);
- Preconditions.checkNotNull(neutronFloatingIP.getFixedIPAddress());
- Preconditions.checkNotNull(neutronFloatingIP.getFloatingIPAddress());
-
- // find bridge Node where floating ip is configured by looking up cache for its port
- final NeutronPort neutronPortForFloatIp = findNeutronPortForFloatingIp(neutronFloatingIP.getID());
- final String neutronTenantPortUuid = neutronFloatingIP.getPortUUID();
- final Pair<Long, Uuid> nodeIfPair = this.getDpIdOfNeutronPort(neutronTenantPortUuid);
- final String floatingIpMac = neutronPortForFloatIp == null ? null : neutronPortForFloatIp.getMacAddress();
- final String fixedIpAddress = neutronFloatingIP.getFixedIPAddress();
- final String floatingIpAddress = neutronFloatingIP.getFloatingIPAddress();
-
- final NeutronPort tenantNeutronPort = neutronPortCache.getPort(neutronTenantPortUuid);
- final NeutronNetwork tenantNeutronNetwork = tenantNeutronPort != null ?
- neutronNetworkCache.getNetwork(tenantNeutronPort.getNetworkUUID()) : null;
- final String providerSegmentationId = tenantNeutronNetwork != null ?
- tenantNeutronNetwork.getProviderSegmentationID() : null;
- final String neutronRouterMac = tenantNeutronNetwork != null ?
- networkIdToRouterMacCache.get(tenantNeutronNetwork.getID()) : null;
-
- if (nodeIfPair == null || neutronTenantPortUuid == null ||
- providerSegmentationId == null || providerSegmentationId.isEmpty() ||
- floatingIpMac == null || floatingIpMac.isEmpty() ||
- neutronRouterMac == null || neutronRouterMac.isEmpty()) {
- LOG.trace("Floating IP {}<->{}, incomplete floatPort {} tenantPortUuid {} seg {} mac {} rtrMac {}",
- fixedIpAddress,
- floatingIpAddress,
- neutronPortForFloatIp,
- neutronTenantPortUuid,
- providerSegmentationId,
- floatingIpMac,
- neutronRouterMac);
- return;
- }
-
- // get ofport for patch port in br-int
- final Long dpId = nodeIfPair.getLeft();
- final Long ofPort = findOFPortForExtPatch(dpId);
- if (ofPort == null) {
- LOG.warn("Unable to locate OF port of patch port to connect floating ip to external bridge. dpid {}",
- dpId);
- return;
- }
-
- // Respond to ARPs for the floating ip address by default, via the patch port that connects br-int to br-ex
- //
- if (distributedArpService.programStaticRuleStage1(dpId, encodeExcplicitOFPort(ofPort), floatingIpMac, floatingIpAddress,
- ADD)) {
- final FloatIpData floatIpData = new FloatIpData(dpId, ofPort, providerSegmentationId, floatingIpMac,
- floatingIpAddress, fixedIpAddress, neutronRouterMac);
- floatIpDataMapCache.put(neutronFloatingIP.getID(), floatIpData);
- LOG.info("Floating IP {}<->{} programmed ARP mac {} on OFport {} seg {} dpid {}",
- neutronFloatingIP.getFixedIPAddress(), neutronFloatingIP.getFloatingIPAddress(),
- floatingIpMac, ofPort, providerSegmentationId, dpId);
- }
- }
-
- private void programFlowsForFloatingIPArpDelete(final String neutronFloatingIPUuid) {
- final FloatIpData floatIpData = getFloatingIPWithMetadata(neutronFloatingIPUuid);
- if (floatIpData == null) {
- LOG.trace("programFlowsForFloatingIPArpDelete for uuid {} is not needed", neutronFloatingIPUuid);
- return;
- }
-
- if (distributedArpService.programStaticRuleStage1(floatIpData.dpid, encodeExcplicitOFPort(floatIpData.ofPort), floatIpData.macAddress,
- floatIpData.floatingIpAddress, DELETE)) {
- floatIpDataMapCache.remove(neutronFloatingIPUuid);
- LOG.info("Floating IP {} un-programmed ARP mac {} on {} dpid {}",
- floatIpData.floatingIpAddress, floatIpData.macAddress, floatIpData.ofPort, floatIpData.dpid);
- }
- }
-
- private NeutronPort findNeutronPortForFloatingIp(final String floatingIpUuid) {
- for (NeutronPort neutronPort : neutronPortCache.getAllPorts()) {
- if (neutronPort.getDeviceOwner().equals(OWNER_FLOATING_IP) &&
- neutronPort.getDeviceID().equals(floatingIpUuid)) {
- return neutronPort;
- }
- }
- return null;
- }
-
- private Long findOFPortForExtPatch(Long dpId) {
- final String brInt = configurationService.getIntegrationBridgeName();
- final String brExt = configurationService.getExternalBridgeName();
- final String portNameInt = configurationService.getPatchPortName(new ImmutablePair<>(brInt, brExt));
-
- Preconditions.checkNotNull(dpId);
- Preconditions.checkNotNull(portNameInt);
-
- final long dpidPrimitive = dpId;
- for (Node node : nodeCacheManager.getBridgeNodes()) {
- if (dpidPrimitive == southbound.getDataPathId(node)) {
- final OvsdbTerminationPointAugmentation terminationPointOfBridge =
- southbound.getTerminationPointOfBridge(node, portNameInt);
- return terminationPointOfBridge == null ? null : terminationPointOfBridge.getOfport();
- }
- }
- return null;
- }
-
- /**
- * Process the event.
- *
- * @param action the {@link Action} action to be handled.
- * @param neutronNetwork An {@link NeutronNetwork} instance of NeutronFloatingIP object.
- */
- public void handleNeutronNetworkEvent(final NeutronNetwork neutronNetwork, Action action) {
- LOG.debug("neutronNetwork {}: network: {}", action, neutronNetwork);
- if (action == UPDATE) {
- this.updateNetworkInCleanupCache(neutronNetwork);
- }
- }
-
- //
- // Callbacks from OVSDB's southbound handler
- //
- /**
- * Process the event.
- *
- * @param bridgeNode An instance of Node object.
- * @param intf An {@link org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105
- * .OvsdbTerminationPointAugmentation} instance of OvsdbTerminationPointAugmentation object.
- * @param neutronNetwork An {@link NeutronNetwork} instance of NeutronNetwork
- * object.
- * @param action the {@link Action} action to be handled.
- */
- public void handleInterfaceEvent(final Node bridgeNode, final OvsdbTerminationPointAugmentation intf,
- final NeutronNetwork neutronNetwork, Action action) {
- LOG.debug("southbound interface {} node:{} interface:{}, neutronNetwork:{}",
- action, bridgeNode.getNodeId().getValue(), intf.getName(), neutronNetwork);
-
- final NeutronPort neutronPort = tenantNetworkManager.getTenantPort(intf);
- if (action != DELETE && neutronPort != null) {
- // FIXME: Bug 4971 Move cleanup cache to SG Impl
- storePortInCleanupCache(neutronPort);
- }
-
- final Long dpId = getDpidForIntegrationBridge(bridgeNode);
- final Uuid interfaceUuid = intf.getInterfaceUuid();
-
- LOG.trace("southbound interface {} node:{} interface:{}, neutronNetwork:{} port:{} dpid:{} intfUuid:{}",
- action, bridgeNode.getNodeId().getValue(), intf.getName(), neutronNetwork, neutronPort, dpId, interfaceUuid);
-
- if (neutronPort != null) {
- final String neutronPortUuid = neutronPort.getPortUUID();
-
- if (action == ADD && dpId != null && interfaceUuid != null) {
- handleInterfaceEventAdd(neutronPortUuid, dpId, interfaceUuid);
- }
-
- if (this.enabled) {
- handleNeutronPortEvent(neutronPort, action == DELETE ? Action.DELETE : Action.UPDATE);
- }
- }
-
- if (action == DELETE && interfaceUuid != null) {
- handleInterfaceEventDelete(intf, dpId);
- }
- }
-
- private void handleInterfaceEventAdd(final String neutronPortUuid, Long dpId, final Uuid interfaceUuid) {
- neutronPortToDpIdCache.put(neutronPortUuid, new ImmutablePair<>(dpId, interfaceUuid));
- LOG.debug("handleInterfaceEvent add cache entry NeutronPortUuid {} : dpid {}, ifUuid {}",
- neutronPortUuid, dpId, interfaceUuid.getValue());
- }
-
- private void handleInterfaceEventDelete(final OvsdbTerminationPointAugmentation intf, final Long dpId) {
- // Remove entry from neutronPortToDpIdCache based on interface uuid
- for (Map.Entry<String, Pair<Long, Uuid>> entry : neutronPortToDpIdCache.entrySet()) {
- final String currPortUuid = entry.getKey();
- if (intf.getInterfaceUuid().equals(entry.getValue().getRight())) {
- LOG.debug("handleInterfaceEventDelete remove cache entry NeutronPortUuid {} : dpid {}, ifUuid {}",
- currPortUuid, dpId, intf.getInterfaceUuid().getValue());
- neutronPortToDpIdCache.remove(currPortUuid);
- break;
- }
- }
- }
-
- //
- // Internal helpers
- //
- private void updateL3ForNeutronPort(final NeutronPort neutronPort, final boolean isDelete) {
-
- final String networkUUID = neutronPort.getNetworkUUID();
- final String routerMacAddress = networkIdToRouterMacCache.get(networkUUID);
-
- if(!isDelete) {
- // If there is no router interface handling the networkUUID, we are done
- if (routerMacAddress == null || routerMacAddress.isEmpty()) {
- return;
- }
-
- // If this is the neutron port for the router interface itself, ignore it as well. Ports that represent the
- // router interface are handled via handleNeutronRouterInterfaceEvent.
- if (routerMacAddress.equalsIgnoreCase(neutronPort.getMacAddress())) {
- return;
- }
- }
-
- final NeutronNetwork neutronNetwork = neutronNetworkCache.getNetwork(networkUUID);
- final String providerSegmentationId = neutronNetwork != null ?
- neutronNetwork.getProviderSegmentationID() : null;
- final String tenantMac = neutronPort.getMacAddress();
-
- if (providerSegmentationId == null || providerSegmentationId.isEmpty() ||
- tenantMac == null || tenantMac.isEmpty()) {
- // done: go no further w/out all the info needed...
- return;
- }
-
- final Action action = isDelete ? DELETE : ADD;
- List<Node> nodes = nodeCacheManager.getBridgeNodes();
- if (nodes.isEmpty()) {
- LOG.trace("updateL3ForNeutronPort has no nodes to work with");
- }
- for (Node node : nodes) {
- final Long dpid = getDpidForIntegrationBridge(node);
- if (dpid == null) {
- continue;
- }
- if (neutronPort.getFixedIPs() == null) {
- continue;
- }
- for (Neutron_IPs neutronIP : neutronPort.getFixedIPs()) {
- final String tenantIpStr = neutronIP.getIpAddress();
- if (tenantIpStr.isEmpty()) {
- continue;
- }
-
- // Configure L3 fwd. We do that regardless of tenant network present, because these rules are
- // still needed when routing to subnets non-local to node (bug 2076).
- programL3ForwardingStage1(node, dpid, providerSegmentationId, tenantMac, tenantIpStr, action);
- }
- }
- }
-
- private void processSecurityGroupUpdate(NeutronPort neutronPort) {
- LOG.trace("processSecurityGroupUpdate:" + neutronPort);
- /**
- * Get updated data and original data for the the changed. Identify the security groups that got
- * added and removed and call the appropriate providers for updating the flows.
- */
- try {
- List<NeutronSecurityGroup> addedGroup = getsecurityGroupChanged(neutronPort,
- neutronPort.getOriginalPort());
- List<NeutronSecurityGroup> deletedGroup = getsecurityGroupChanged(neutronPort.getOriginalPort(),
- neutronPort);
-
- if (null != deletedGroup && !deletedGroup.isEmpty()) {
- securityServicesManager.syncSecurityGroup(neutronPort,deletedGroup,false);
- }
- if (null != addedGroup && !addedGroup.isEmpty()) {
- securityServicesManager.syncSecurityGroup(neutronPort,addedGroup,true);
- }
-
- } catch (Exception e) {
- LOG.error("Exception in processSecurityGroupUpdate", e);
- }
- }
-
- private void processPortSecurityEnableUpdated(NeutronPort neutronPort) {
- LOG.trace("processPortSecurityEnableUpdated:" + neutronPort);
- securityServicesManager.syncFixedSecurityGroup(neutronPort,
- neutronPort.getPortSecurityEnabled());
- }
-
- private boolean isPortSecurityEnableUpdated(NeutronPort neutronPort) {
- LOG.trace("isPortSecurityEnableUpdated: {}", neutronPort);
- if (neutronPort == null) {
- return false;
- }
-
- NeutronPort originalPort = neutronPort.getOriginalPort();
- if (originalPort == null) {
- return false;
- }
-
- Boolean originalPortSecurityEnabled = originalPort.getPortSecurityEnabled();
- if (originalPortSecurityEnabled == null) {
- return false;
- }
-
- return !originalPortSecurityEnabled.equals(neutronPort.getPortSecurityEnabled());
- }
-
- private List<NeutronSecurityGroup> getsecurityGroupChanged(NeutronPort port1, NeutronPort port2) {
- LOG.trace("getsecurityGroupChanged:" + "Port1:" + port1 + "Port2" + port2);
- if (port1 == null) {
- return null;
- }
- List<NeutronSecurityGroup> list1 = new ArrayList<>(port1.getSecurityGroups());
- if (port2 == null) {
- return list1;
- }
- List<NeutronSecurityGroup> list2 = new ArrayList<>(port2.getSecurityGroups());
- for (Iterator<NeutronSecurityGroup> iterator = list1.iterator(); iterator.hasNext();) {
- NeutronSecurityGroup securityGroup1 = iterator.next();
- for (NeutronSecurityGroup securityGroup2 :list2) {
- if (securityGroup1.getID().equals(securityGroup2.getID())) {
- iterator.remove();
- }
- }
- }
- return list1;
- }
-
- private void programL3ForwardingStage1(Node node, Long dpid, String providerSegmentationId,
- String macAddress, String ipStr,
- Action actionForNode) {
- if (actionForNode == DELETE) {
- LOG.trace("Deleting Flow : programL3ForwardingStage1 for node {} providerId {} mac {} ip {} action {}",
- node.getNodeId().getValue(), providerSegmentationId, macAddress, ipStr, actionForNode);
- }
- if (actionForNode == ADD) {
- LOG.trace("Adding Flow : programL3ForwardingStage1 for node {} providerId {} mac {} ip {} action {}",
- node.getNodeId().getValue(), providerSegmentationId, macAddress, ipStr, actionForNode);
- }
-
- this.programL3ForwardingStage2(node, dpid, providerSegmentationId,
- macAddress, ipStr, actionForNode);
- }
-
- private Status programL3ForwardingStage2(Node node, Long dpid, String providerSegmentationId,
- String macAddress,
- String address,
- Action actionForNode) {
- Status status;
- try {
- InetAddress inetAddress = InetAddress.getByName(address);
- status = l3ForwardingProvider == null ?
- new Status(StatusCode.SUCCESS) :
- l3ForwardingProvider.programForwardingTableEntry(dpid, providerSegmentationId,
- inetAddress, macAddress, actionForNode);
- } catch (UnknownHostException e) {
- status = new Status(StatusCode.BADREQUEST);
- }
-
- if (status.isSuccess()) {
- LOG.debug("ProgramL3Forwarding {} for mac:{} addr:{} node:{} action:{}",
- l3ForwardingProvider == null ? "skipped" : "programmed",
- macAddress, address, node.getNodeId().getValue(), actionForNode);
- } else {
- LOG.error("ProgramL3Forwarding failed for mac:{} addr:{} node:{} action:{} status:{}",
- macAddress, address, node.getNodeId().getValue(), actionForNode, status);
- }
- return status;
- }
-
- // --
-
- private void programFlowsForNeutronRouterInterface(final NeutronRouter_Interface destNeutronRouterInterface,
- Boolean isDelete) {
- Preconditions.checkNotNull(destNeutronRouterInterface);
-
- final NeutronPort neutronPort = neutronPortCache.getPort(destNeutronRouterInterface.getPortUUID());
- String macAddress = neutronPort != null ? neutronPort.getMacAddress() : null;
- List<Neutron_IPs> ipList = neutronPort != null ? neutronPort.getFixedIPs() : null;
- final NeutronSubnet subnet = neutronSubnetCache.getSubnet(destNeutronRouterInterface.getSubnetUUID());
- final NeutronNetwork neutronNetwork = subnet != null ?
- neutronNetworkCache.getNetwork(subnet.getNetworkUUID()) : null;
- final String destinationSegmentationId = neutronNetwork != null ?
- neutronNetwork.getProviderSegmentationID() : null;
- final Boolean isExternal = neutronNetwork != null ? neutronNetwork.getRouterExternal() : Boolean.TRUE;
- final String cidr = subnet != null ? subnet.getCidr() : null;
- final int mask = getMaskLenFromCidr(cidr);
-
- LOG.trace("programFlowsForNeutronRouterInterface called for interface {} isDelete {}",
- destNeutronRouterInterface, isDelete);
-
- if (subnet != null && subnet.getIpVersion() == 6) {
- LOG.trace("programFlowsForNeutronRouterInterface doesn't support IPv6 router interface");
- return;
- }
- // in delete path, mac address as well as ip address are not provided. Being so, let's find them from
- // the local cache
- if (neutronNetwork != null) {
- if (macAddress == null || macAddress.isEmpty()) {
- macAddress = networkIdToRouterMacCache.get(neutronNetwork.getNetworkUUID());
- }
- if (ipList == null || ipList.isEmpty()) {
- ipList = networkIdToRouterIpListCache.get(neutronNetwork.getNetworkUUID());
- }
- }
-
- if (destinationSegmentationId == null || destinationSegmentationId.isEmpty() ||
- cidr == null || cidr.isEmpty() ||
- macAddress == null || macAddress.isEmpty() ||
- ipList == null || ipList.isEmpty()) {
- LOG.debug("programFlowsForNeutronRouterInterface is bailing seg:{} cidr:{} mac:{} ip:{}",
- destinationSegmentationId, cidr, macAddress, ipList);
- // done: go no further w/out all the info needed...
- return;
- }
-
- final Action actionForNode = isDelete ? DELETE : ADD;
-
- // Keep cache for finding router's mac from network uuid -- add
- //
- if (! isDelete) {
- networkIdToRouterMacCache.put(neutronNetwork.getNetworkUUID(), macAddress);
- networkIdToRouterIpListCache.put(neutronNetwork.getNetworkUUID(), new ArrayList<>(ipList));
- subnetIdToRouterInterfaceCache.put(subnet.getSubnetUUID(), destNeutronRouterInterface);
- }
-
- List<Node> nodes = nodeCacheManager.getBridgeNodes();
- if (nodes.isEmpty()) {
- LOG.trace("programFlowsForNeutronRouterInterface has no nodes to work with");
- }
- for (Node node : nodes) {
- final Long dpid = getDpidForIntegrationBridge(node);
- if (dpid == null) {
- continue;
- }
-
- for (Neutron_IPs neutronIP : ipList) {
- final String ipStr = neutronIP.getIpAddress();
- if (ipStr.isEmpty()) {
- LOG.debug("programFlowsForNeutronRouterInterface is skipping node {} ip {}",
- node.getNodeId().getValue(), ipStr);
- continue;
- }
- final IpAddress ipAddress = new IpAddress(ipStr.toCharArray());
- if (ipAddress.getIpv4Address() == null) {
- LOG.debug("programFlowsForNeutronRouterInterface is skipping node {} ipv6 {}",
- node.getNodeId().getValue(), ipStr);
- continue;
- }
-
- // Iterate through all other interfaces and add/remove reflexive flows to this interface
- //
- for (NeutronRouter_Interface srcNeutronRouterInterface : subnetIdToRouterInterfaceCache.values()) {
- programFlowsForNeutronRouterInterfacePair(node, dpid,
- srcNeutronRouterInterface, destNeutronRouterInterface,
- neutronNetwork, destinationSegmentationId,
- macAddress, ipStr, mask, actionForNode,
- true /*isReflexsive*/);
- }
-
- if (! isExternal) {
- programFlowForNetworkFromExternal(node, dpid, destinationSegmentationId, macAddress, ipStr, mask,
- actionForNode);
- }
- // Enable ARP responder by default, because router interface needs to be responded always.
- distributedArpService.programStaticRuleStage1(dpid, destinationSegmentationId, macAddress, ipStr, actionForNode);
- programIcmpEcho(dpid, destinationSegmentationId, macAddress, ipStr, actionForNode);
- }
-
- // Compute action to be programmed. In the case of rewrite exclusions, we must never program rules
- // for the external neutron networks.
- //
- {
- final Action actionForRewriteExclusion = isExternal ? DELETE : actionForNode;
- programIpRewriteExclusionStage1(node, dpid, destinationSegmentationId, cidr, actionForRewriteExclusion);
- }
- }
-
- if (isDelete) {
- networkIdToRouterMacCache.remove(neutronNetwork.getNetworkUUID());
- networkIdToRouterIpListCache.remove(neutronNetwork.getNetworkUUID());
- subnetIdToRouterInterfaceCache.remove(subnet.getSubnetUUID());
- }
- }
-
- private void programFlowForNetworkFromExternal(final Node node,
- final Long dpid,
- final String destinationSegmentationId,
- final String dstMacAddress,
- final String destIpStr,
- final int destMask,
- final Action actionForNode) {
- programRouterInterfaceStage1(node, dpid, Constants.EXTERNAL_NETWORK, destinationSegmentationId,
- dstMacAddress, destIpStr, destMask, actionForNode);
- }
-
- private void programFlowsForNeutronRouterInterfacePair(final Node node,
- final Long dpid,
- final NeutronRouter_Interface srcNeutronRouterInterface,
- final NeutronRouter_Interface dstNeutronRouterInterface,
- final NeutronNetwork dstNeutronNetwork,
- final String destinationSegmentationId,
- final String dstMacAddress,
- final String destIpStr,
- final int destMask,
- final Action actionForNode,
- Boolean isReflexsive) {
- Preconditions.checkNotNull(srcNeutronRouterInterface);
- Preconditions.checkNotNull(dstNeutronRouterInterface);
-
- final String sourceSubnetId = srcNeutronRouterInterface.getSubnetUUID();
- if (sourceSubnetId == null) {
- LOG.error("Could not get provider Subnet ID from router interface {}",
- srcNeutronRouterInterface.getID());
- return;
- }
-
- final NeutronSubnet sourceSubnet = neutronSubnetCache.getSubnet(sourceSubnetId);
- final String sourceNetworkId = sourceSubnet == null ? null : sourceSubnet.getNetworkUUID();
- if (sourceNetworkId == null) {
- LOG.error("Could not get provider Network ID from subnet {}", sourceSubnetId);
- return;
- }
-
- final NeutronNetwork sourceNetwork = neutronNetworkCache.getNetwork(sourceNetworkId);
- if (sourceNetwork == null) {
- LOG.error("Could not get provider Network for Network ID {}", sourceNetworkId);
- return;
- }
-
- if (! sourceNetwork.getTenantID().equals(dstNeutronNetwork.getTenantID())) {
- // Isolate subnets from different tenants within the same router
- return;
- }
- final String sourceSegmentationId = sourceNetwork.getProviderSegmentationID();
- if (sourceSegmentationId == null) {
- LOG.error("Could not get provider Segmentation ID for Subnet {}", sourceSubnetId);
- return;
- }
- if (sourceSegmentationId.equals(destinationSegmentationId)) {
- // Skip 'self'
- return;
- }
-
- programRouterInterfaceStage1(node, dpid, sourceSegmentationId, destinationSegmentationId,
- dstMacAddress, destIpStr, destMask, actionForNode);
-
- // Flip roles src->dst; dst->src
- if (isReflexsive) {
- final NeutronPort sourceNeutronPort = neutronPortCache.getPort(srcNeutronRouterInterface.getPortUUID());
- final String macAddress2 = sourceNeutronPort != null ? sourceNeutronPort.getMacAddress() : null;
- final List<Neutron_IPs> ipList2 = sourceNeutronPort != null ? sourceNeutronPort.getFixedIPs() : null;
- final String cidr2 = sourceSubnet.getCidr();
- final int mask2 = getMaskLenFromCidr(cidr2);
-
- if (cidr2 == null || cidr2.isEmpty() ||
- macAddress2 == null || macAddress2.isEmpty() ||
- ipList2 == null || ipList2.isEmpty()) {
- LOG.trace("programFlowsForNeutronRouterInterfacePair reflexive is bailing seg:{} cidr:{} mac:{} ip:{}",
- sourceSegmentationId, cidr2, macAddress2, ipList2);
- // done: go no further w/out all the info needed...
- return;
- }
-
- for (Neutron_IPs neutronIP2 : ipList2) {
- final String ipStr2 = neutronIP2.getIpAddress();
- if (ipStr2.isEmpty()) {
- continue;
- }
- programFlowsForNeutronRouterInterfacePair(node, dpid, dstNeutronRouterInterface,
- srcNeutronRouterInterface,
- sourceNetwork, sourceSegmentationId,
- macAddress2, ipStr2, mask2, actionForNode,
- false /*isReflexsive*/);
- }
- }
- }
-
- private void programRouterInterfaceStage1(Node node, Long dpid, String sourceSegmentationId,
- String destinationSegmentationId,
- String macAddress, String ipStr, int mask,
- Action actionForNode) {
- if (actionForNode == DELETE) {
- LOG.trace("Deleting Flow : programRouterInterfaceStage1 for node {} sourceSegId {} destSegId {} mac {} ip {} mask {}" +
- " action {}",
- node.getNodeId().getValue(), sourceSegmentationId, destinationSegmentationId,
- macAddress, ipStr, mask, actionForNode);
- }
- if (actionForNode == ADD) {
- LOG.trace("Adding Flow : programRouterInterfaceStage1 for node {} sourceSegId {} destSegId {} mac {} ip {} mask {}" +
- " action {}",
- node.getNodeId().getValue(), sourceSegmentationId, destinationSegmentationId,
- macAddress, ipStr, mask, actionForNode);
- }
-
- this.programRouterInterfaceStage2(node, dpid, sourceSegmentationId, destinationSegmentationId,
- macAddress, ipStr, mask, actionForNode);
- }
-
- private Status programRouterInterfaceStage2(Node node, Long dpid, String sourceSegmentationId,
- String destinationSegmentationId,
- String macAddress,
- String address, int mask,
- Action actionForNode) {
- Status status;
- try {
- InetAddress inetAddress = InetAddress.getByName(address);
- status = routingProvider == null ?
- new Status(StatusCode.SUCCESS) :
- routingProvider.programRouterInterface(dpid, sourceSegmentationId, destinationSegmentationId,
- macAddress, inetAddress, mask, actionForNode);
- } catch (UnknownHostException e) {
- status = new Status(StatusCode.BADREQUEST);
- }
-
- if (status.isSuccess()) {
- LOG.debug("programRouterInterfaceStage2 {} for mac:{} addr:{}/{} node:{} srcTunId:{} destTunId:{} action:{}",
- routingProvider == null ? "skipped" : "programmed",
- macAddress, address, mask, node.getNodeId().getValue(), sourceSegmentationId, destinationSegmentationId,
- actionForNode);
- } else {
- LOG.error("programRouterInterfaceStage2 failed for mac:{} addr:{}/{} node:{} srcTunId:{} destTunId:{} action:{} status:{}",
- macAddress, address, mask, node.getNodeId().getValue(), sourceSegmentationId, destinationSegmentationId,
- actionForNode, status);
- }
- return status;
- }
-
- private boolean programIcmpEcho(Long dpid, String segOrOfPort,
- String macAddress, String ipStr,
- Action action) {
- if (action == DELETE ) {
- LOG.trace("Deleting Flow : programIcmpEcho dpid {} segOrOfPort {} mac {} ip {} action {}",
- dpid, segOrOfPort, macAddress, ipStr, action);
- }
- if (action == ADD) {
- LOG.trace("Adding Flow : programIcmpEcho dpid {} segOrOfPort {} mac {} ip {} action {}",
- dpid, segOrOfPort, macAddress, ipStr, action);
- }
-
- Status status = new Status(StatusCode.UNSUPPORTED);
- if (icmpEchoProvider != null){
- try {
- InetAddress inetAddress = InetAddress.getByName(ipStr);
- status = icmpEchoProvider.programIcmpEchoEntry(dpid, segOrOfPort,
- macAddress, inetAddress, action);
- } catch (UnknownHostException e) {
- status = new Status(StatusCode.BADREQUEST);
- }
- }
-
- if (status.isSuccess()) {
- LOG.debug("programIcmpEcho {} for mac:{} addr:{} dpid:{} segOrOfPort:{} action:{}",
- icmpEchoProvider == null ? "skipped" : "programmed",
- macAddress, ipStr, dpid, segOrOfPort, action);
- } else {
- LOG.error("programIcmpEcho failed for mac:{} addr:{} dpid:{} segOrOfPort:{} action:{} status:{}",
- macAddress, ipStr, dpid, segOrOfPort, action, status);
- }
-
- return status.isSuccess();
- }
-
- private boolean programInboundIpRewriteStage1(Long dpid, Long inboundOFPort, String providerSegmentationId,
- String matchAddress, String rewriteAddress,
- Action action) {
- if (action == DELETE ) {
- LOG.trace("Deleting Flow : programInboundIpRewriteStage1 dpid {} OFPort {} seg {} matchAddress {} rewriteAddress {}" +
- " action {}",
- dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action);
- }
- if (action == ADD ) {
- LOG.trace("Adding Flow : programInboundIpRewriteStage1 dpid {} OFPort {} seg {} matchAddress {} rewriteAddress {}" +
- " action {}",
- dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action);
- }
-
- Status status = programInboundIpRewriteStage2(dpid, inboundOFPort, providerSegmentationId, matchAddress,
- rewriteAddress, action);
- return status.isSuccess();
- }
-
- private Status programInboundIpRewriteStage2(Long dpid, Long inboundOFPort, String providerSegmentationId,
- String matchAddress, String rewriteAddress,
- Action action) {
- Status status;
- try {
- InetAddress inetMatchAddress = InetAddress.getByName(matchAddress);
- InetAddress inetRewriteAddress = InetAddress.getByName(rewriteAddress);
- status = inboundNatProvider == null ?
- new Status(StatusCode.SUCCESS) :
- inboundNatProvider.programIpRewriteRule(dpid, inboundOFPort, providerSegmentationId,
- inetMatchAddress, inetRewriteAddress,
- action);
- } catch (UnknownHostException e) {
- status = new Status(StatusCode.BADREQUEST);
- }
-
- if (status.isSuccess()) {
- final boolean isSkipped = inboundNatProvider == null;
- LOG.debug("programInboundIpRewriteStage2 {} for dpid:{} ofPort:{} seg:{} match:{} rewrite:{} action:{}",
- isSkipped ? "skipped" : "programmed",
- dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action);
- } else {
- LOG.error("programInboundIpRewriteStage2 failed for dpid:{} ofPort:{} seg:{} match:{} rewrite:{} action:{}" +
- " status:{}",
- dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action,
- status);
- }
- return status;
- }
-
- private void programIpRewriteExclusionStage1(Node node, Long dpid, String providerSegmentationId, String cidr,
- Action actionForRewriteExclusion) {
- if (actionForRewriteExclusion == DELETE ) {
- LOG.trace("Deleting Flow : programIpRewriteExclusionStage1 node {} providerId {} cidr {} action {}",
- node.getNodeId().getValue(), providerSegmentationId, cidr, actionForRewriteExclusion);
- }
- if (actionForRewriteExclusion == ADD) {
- LOG.trace("Adding Flow : programIpRewriteExclusionStage1 node {} providerId {} cidr {} action {}",
- node.getNodeId().getValue(), providerSegmentationId, cidr, actionForRewriteExclusion);
- }
-
- this.programIpRewriteExclusionStage2(node, dpid, providerSegmentationId, cidr,actionForRewriteExclusion);
- }
-
- private Status programIpRewriteExclusionStage2(Node node, Long dpid, String providerSegmentationId, String cidr,
- Action actionForNode) {
- final Status status = outboundNatProvider == null ? new Status(StatusCode.SUCCESS) :
- outboundNatProvider.programIpRewriteExclusion(dpid, providerSegmentationId, cidr, actionForNode);
-
- if (status.isSuccess()) {
- final boolean isSkipped = outboundNatProvider == null;
- LOG.debug("IpRewriteExclusion {} for cidr:{} node:{} action:{}",
- isSkipped ? "skipped" : "programmed",
- cidr, node.getNodeId().getValue(), actionForNode);
- } else {
- LOG.error("IpRewriteExclusion failed for cidr:{} node:{} action:{} status:{}",
- cidr, node.getNodeId().getValue(), actionForNode, status);
- }
- return status;
- }
-
- private void programOutboundIpRewriteStage1(FloatIpData fid, Action action) {
-
- if (action == DELETE) {
- LOG.trace("Deleting Flow : programOutboundIpRewriteStage1 dpid {} seg {} fixedIpAddress {} floatIp {} action {} ",
- fid.dpid, fid.segId, fid.fixedIpAddress, fid.floatingIpAddress, action);
- }
- if (action == ADD) {
- LOG.trace("Adding Flow : programOutboundIpRewriteStage1 dpid {} seg {} fixedIpAddress {} floatIp {} action {} " ,
- fid.dpid, fid.segId, fid.fixedIpAddress, fid.floatingIpAddress, action);
- }
-
- this.programOutboundIpRewriteStage2(fid, action);
- }
-
- private Status programOutboundIpRewriteStage2(FloatIpData fid, Action action) {
- Status status;
- try {
- InetAddress matchSrcAddress = InetAddress.getByName(fid.fixedIpAddress);
- InetAddress rewriteSrcAddress = InetAddress.getByName(fid.floatingIpAddress);
- status = outboundNatProvider == null ?
- new Status(StatusCode.SUCCESS) :
- outboundNatProvider.programIpRewriteRule(
- fid.dpid, fid.segId, fid.neutronRouterMac, matchSrcAddress, fid.macAddress,
- this.externalRouterMac, rewriteSrcAddress, fid.ofPort, action);
- } catch (UnknownHostException e) {
- status = new Status(StatusCode.BADREQUEST);
- }
-
- if (status.isSuccess()) {
- final boolean isSkipped = outboundNatProvider == null;
- LOG.debug("programOutboundIpRewriteStage2 {} for dpid {} seg {} fixedIpAddress {} floatIp {}" +
- " action {}",
- isSkipped ? "skipped" : "programmed",
- fid.dpid, fid.segId, fid.fixedIpAddress, fid.floatingIpAddress, action);
- } else {
- LOG.error("programOutboundIpRewriteStage2 failed for dpid {} seg {} fixedIpAddress {} floatIp {}" +
- " action {} status:{}",
- fid.dpid, fid.segId, fid.fixedIpAddress, fid.floatingIpAddress, action, status);
- }
- return status;
- }
-
- private int getMaskLenFromCidr(String cidr) {
- if (cidr == null) {
- return 0;
- }
- String[] splits = cidr.split("/");
- if (splits.length != 2) {
- return 0;
- }
-
- int result;
- try {
- result = Integer.parseInt(splits[1].trim());
- } catch (NumberFormatException nfe) {
- result = 0;
- }
- return result;
- }
-
- private Long getDpidForIntegrationBridge(Node node) {
- // Check if node is integration bridge; and only then return its dpid
- if (southbound.getBridge(node, configurationService.getIntegrationBridgeName()) != null) {
- return southbound.getDataPathId(node);
- }
- return null;
- }
-
- private Long getDpidForExternalBridge(Node node) {
- // Check if node is external bridge; and only then return its dpid
- if (southbound.getBridge(node, configurationService.getExternalBridgeName()) != null) {
- return southbound.getDataPathId(node);
- }
- return null;
- }
-
- private Node getExternalBridgeNode(){
- //Pickup the first node that has external bridge (br-ex).
- //NOTE: We are assuming that all the br-ex are serving one external network and gateway ip of
- //the external network is reachable from every br-ex
- // TODO: Consider other deployment scenario, and thing of better solution.
- List<Node> allBridges = nodeCacheManager.getBridgeNodes();
- for(Node node : allBridges){
- if (southbound.getBridge(node, configurationService.getExternalBridgeName()) != null) {
- return node;
- }
- }
- return null;
- }
-
- private NeutronSubnet getExternalNetworkSubnet(NeutronPort gatewayPort){
- if (gatewayPort.getFixedIPs() == null) {
- return null;
- }
- for (Neutron_IPs neutronIPs : gatewayPort.getFixedIPs()) {
- String subnetUUID = neutronIPs.getSubnetUUID();
- NeutronSubnet extSubnet = neutronSubnetCache.getSubnet(subnetUUID);
- if (extSubnet != null && extSubnet.getGatewayIP() != null) {
- return extSubnet;
- }
- if (extSubnet == null) {
- // TODO: when subnet is created, try again.
- LOG.debug("subnet {} in not found", subnetUUID);
- }
- }
- return null;
- }
-
- private void cleanupFloatingIPRules(final NeutronPort neutronPort) {
- List<NeutronFloatingIP> neutronFloatingIps = neutronFloatingIpCache.getAllFloatingIPs();
- if (neutronFloatingIps != null && !neutronFloatingIps.isEmpty()) {
- for (NeutronFloatingIP neutronFloatingIP : neutronFloatingIps) {
- // Neutron floating Ip's port uuid cannot be null (Bug#5894)
- if (neutronFloatingIP.getPortUUID() != null &&
- (neutronFloatingIP.getPortUUID().equals(neutronPort.getPortUUID()))) {
- handleNeutronFloatingIPEvent(neutronFloatingIP, DELETE);
- }
- }
- }
- }
-
- private void updateFloatingIPRules(final NeutronPort neutronPort) {
- List<NeutronFloatingIP> neutronFloatingIps = neutronFloatingIpCache.getAllFloatingIPs();
- if (neutronFloatingIps != null) {
- for (NeutronFloatingIP neutronFloatingIP : neutronFloatingIps) {
- if (neutronFloatingIP.getPortUUID() != null
- && neutronFloatingIP.getPortUUID().equals(
- neutronPort.getPortUUID())) {
- handleNeutronFloatingIPEvent(neutronFloatingIP, UPDATE);
- }
- }
- }
- }
-
-
- private void triggerGatewayMacResolver(final NeutronPort gatewayPort){
-
- Preconditions.checkNotNull(gatewayPort);
- NeutronNetwork externalNetwork = neutronNetworkCache.getNetwork(gatewayPort.getNetworkUUID());
-
- if(externalNetwork != null){
- if(externalNetwork.isRouterExternal()){
- final NeutronSubnet externalSubnet = getExternalNetworkSubnet(gatewayPort);
-
- // TODO: address IPv6 case.
- if (externalSubnet != null &&
- externalSubnet.getIpVersion() == 4 &&
- gatewayPort.getFixedIPs() != null) {
- LOG.info("Trigger MAC resolution for gateway ip {}", externalSubnet.getGatewayIP());
- Neutron_IPs neutronIP = null;
- for (Neutron_IPs nIP : gatewayPort.getFixedIPs()) {
- InetAddress ipAddress;
- try {
- ipAddress = InetAddress.getByName(nIP.getIpAddress());
- } catch (UnknownHostException e) {
- LOG.warn("unknown host exception {}", e);
- continue;
- }
- if (ipAddress instanceof Inet4Address) {
- neutronIP = nIP;
- break;
- }
- }
- if (neutronIP == null) {
- // TODO IPv6 neighbor discovery
- LOG.debug("Ignoring gateway ports with IPv6 only fixed ip {}",
- gatewayPort.getFixedIPs());
- } else {
- gatewayMacResolver.resolveMacAddress(
- this, /* gatewayMacResolverListener */
- null, /* externalNetworkBridgeDpid */
- true, /* refreshExternalNetworkBridgeDpidIfNeeded */
- new Ipv4Address(externalSubnet.getGatewayIP()),
- new Ipv4Address(neutronIP.getIpAddress()),
- new MacAddress(gatewayPort.getMacAddress()),
- true /* periodicRefresh */);
- }
- } else {
- LOG.warn("No gateway IP address found for external network {}", externalNetwork);
- }
- }
- }else{
- LOG.warn("Neutron network not found for router interface {}", gatewayPort);
- }
- }
-
-
- private void storePortInCleanupCache(NeutronPort port) {
- this.portCleanupCache.put(port.getPortUUID(),port);
- }
-
-
- private void updatePortInCleanupCache(NeutronPort updatedPort,NeutronPort originalPort) {
- removePortFromCleanupCache(originalPort);
- storePortInCleanupCache(updatedPort);
- }
-
- public void removePortFromCleanupCache(NeutronPort port) {
- if(port != null) {
- this.portCleanupCache.remove(port.getPortUUID());
- }
- }
-
- public Map<String, NeutronPort> getPortCleanupCache() {
- return this.portCleanupCache;
- }
-
- public NeutronPort getPortFromCleanupCache(String portid) {
- NeutronPort ret = this.portCleanupCache.get(portid);
- if (ret != null) {
- LOG.info("getPortFromCleanupCache: Matching NeutronPort found {}", portid);
- }
- return ret;
- }
-
- private void storeNetworkInCleanupCache(NeutronNetwork network) {
- if (network != null) {
- this.networkCleanupCache.put(network.getNetworkUUID(), network);
- }
- }
-
-
- private void updateNetworkInCleanupCache(NeutronNetwork network) {
- this.networkCleanupCache.put(network.getNetworkUUID(), network);
- }
-
- public void removeNetworkFromCleanupCache(String networkid) {
- NeutronNetwork network = networkCleanupCache.get(networkid);
- if (network != null) {
- for (NeutronPort port : this.portCleanupCache.values()) {
- if (port.getNetworkUUID().equals(networkid)) {
- LOG.info("This network is used by another port", network);
- return;
- }
- }
- this.networkCleanupCache.remove(network.getNetworkUUID());
- }
- }
-
- public NeutronPort getPortPreferablyFromCleanupCache(String portUuid) {
- NeutronPort port = getPortFromCleanupCache(portUuid);
- if (port == null) {
- port = neutronPortCache.getPort(portUuid);
- if (port == null) {
- LOG.warn("In getPortPreferablyFromCleanupCache no neutron port found: portUuid: {}", portUuid);
- }
- }
- return port;
- }
-
- public Map<String, NeutronNetwork> getNetworkCleanupCache() {
- return this.networkCleanupCache;
- }
-
- public NeutronNetwork getNetworkFromCleanupCache(String networkid) {
- NeutronNetwork ret = networkCleanupCache.get(networkid);
- if (ret != null) {
- LOG.info("getNetworkFromCleanupCache: Matching NeutronNetwork found {}", networkid);
- }
- return ret;
- }
- /**
- * Return String that represents OF port with marker explicitly provided (reverse of MatchUtils:parseExplicitOFPort)
- *
- * @param ofPort the OF port number
- * @return the string with encoded OF port (example format "OFPort|999")
- */
- public static String encodeExcplicitOFPort(Long ofPort) {
- return "OFPort|" + ofPort.toString();
- }
- private void initNetworkCleanUpCache() {
- if (this.neutronNetworkCache != null) {
- for (NeutronNetwork neutronNetwork : neutronNetworkCache.getAllNetworks()) {
- networkCleanupCache.put(neutronNetwork.getNetworkUUID(), neutronNetwork);
- }
- }
- }
- private void initPortCleanUpCache() {
- if (this.neutronPortCache != null) {
- for (NeutronPort neutronPort : neutronPortCache.getAllPorts()) {
- portCleanupCache.put(neutronPort.getPortUUID(), neutronPort);
- }
- }
- }
- @Override
- public void setDependencies(ServiceReference serviceReference) {
- eventDispatcher =
- (EventDispatcher) ServiceHelper.getGlobalInstance(EventDispatcher.class, this);
- eventDispatcher.eventHandlerAdded(serviceReference, this);
- tenantNetworkManager =
- (TenantNetworkManager) ServiceHelper.getGlobalInstance(TenantNetworkManager.class, this);
- configurationService =
- (ConfigurationService) ServiceHelper.getGlobalInstance(ConfigurationService.class, this);
- arpProvider =
- (ArpProvider) ServiceHelper.getGlobalInstance(ArpProvider.class, this);
- inboundNatProvider =
- (InboundNatProvider) ServiceHelper.getGlobalInstance(InboundNatProvider.class, this);
- outboundNatProvider =
- (OutboundNatProvider) ServiceHelper.getGlobalInstance(OutboundNatProvider.class, this);
- routingProvider =
- (RoutingProvider) ServiceHelper.getGlobalInstance(RoutingProvider.class, this);
- l3ForwardingProvider =
- (L3ForwardingProvider) ServiceHelper.getGlobalInstance(L3ForwardingProvider.class, this);
- distributedArpService =
- (DistributedArpService) ServiceHelper.getGlobalInstance(DistributedArpService.class, this);
- nodeCacheManager =
- (NodeCacheManager) ServiceHelper.getGlobalInstance(NodeCacheManager.class, this);
- southbound =
- (Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this);
- gatewayMacResolver =
- (GatewayMacResolver) ServiceHelper.getGlobalInstance(GatewayMacResolver.class, this);
- securityServicesManager =
- (SecurityServicesManager) ServiceHelper.getGlobalInstance(SecurityServicesManager.class, this);
-
- initL3AdapterMembers();
- }
-
- @Override
- public void setDependencies(Object impl) {
- if (impl instanceof INeutronNetworkCRUD) {
- neutronNetworkCache = (INeutronNetworkCRUD)impl;
- initNetworkCleanUpCache();
- } else if (impl instanceof INeutronPortCRUD) {
- neutronPortCache = (INeutronPortCRUD)impl;
- initPortCleanUpCache();
- } else if (impl instanceof INeutronSubnetCRUD) {
- neutronSubnetCache = (INeutronSubnetCRUD)impl;
- } else if (impl instanceof INeutronFloatingIPCRUD) {
- neutronFloatingIpCache = (INeutronFloatingIPCRUD)impl;
- } else if (impl instanceof ArpProvider) {
- arpProvider = (ArpProvider)impl;
- } else if (impl instanceof InboundNatProvider) {
- inboundNatProvider = (InboundNatProvider)impl;
- } else if (impl instanceof OutboundNatProvider) {
- outboundNatProvider = (OutboundNatProvider)impl;
- } else if (impl instanceof RoutingProvider) {
- routingProvider = (RoutingProvider)impl;
- } else if (impl instanceof L3ForwardingProvider) {
- l3ForwardingProvider = (L3ForwardingProvider)impl;
- }else if (impl instanceof GatewayMacResolver) {
- gatewayMacResolver = (GatewayMacResolver)impl;
- }else if (impl instanceof IcmpEchoProvider) {
- icmpEchoProvider = (IcmpEchoProvider)impl;
- }
-
- populateL3ForwardingCaches();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt.impl;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import org.opendaylight.netvirt.openstack.netvirt.AbstractEvent;
-import org.opendaylight.netvirt.openstack.netvirt.AbstractHandler;
-import org.opendaylight.netvirt.openstack.netvirt.ConfigInterface;
-import org.opendaylight.netvirt.openstack.netvirt.NodeCacheManagerEvent;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.EventDispatcher;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheListener;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-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.network.topology.topology.Node;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * @author Flavio Fernandes (ffernand@redhat.com)
- * @author Sam Hague (shague@redhat.com)
- */
-public class NodeCacheManagerImpl extends AbstractHandler implements NodeCacheManager, ConfigInterface {
- private static final Logger LOG = LoggerFactory.getLogger(NodeCacheManagerImpl.class);
- private Map<NodeId, Node> nodeCache = new ConcurrentHashMap<>();
- private Map<Long, NodeCacheListener> handlers = new HashMap<>();
- private volatile Southbound southbound;
-
- @Override
- public void nodeAdded(Node node) {
- LOG.trace("nodeAdded: {}", node);
- enqueueEvent(new NodeCacheManagerEvent(node, Action.UPDATE));
- }
-
- @Override
- public void nodeRemoved(Node node) {
- LOG.trace("nodeRemoved: {}", node);
- enqueueEvent(new NodeCacheManagerEvent(node, Action.DELETE));
- }
-
-
- @Override
- public Node getNode(NodeId nodeId) {
- Node node = nodeCache.get(nodeId);
- return node;
- }
-
- // TODO SB_MIGRATION
- // might need to break this into two different events
- // notifyOvsdbNode, notifyBridgeNode or just make sure the
- // classes implementing the interface check for ovsdbNode or bridgeNode
- private void processNodeUpdate(Node node) {
- Action action = Action.UPDATE;
-
- NodeId nodeId = node.getNodeId();
- if (nodeCache.get(nodeId) == null) {
- action = Action.ADD;
- } else {
- long oldDpid = southbound.getDataPathId(nodeCache.get(nodeId));
- long newDpid = southbound.getDataPathId(node);
- LOG.trace("oldDpid == {}, newDpid == {}", oldDpid, newDpid);
- if (oldDpid != newDpid) {
- action = Action.ADD;
- }
- }
- nodeCache.put(nodeId, node);
-
- LOG.debug("processNodeUpdate: size= {}, Node type= {}, action= {}, node= {}",
- nodeCache.size(),
- southbound.getBridge(node) != null ? "BridgeNode" : "OvsdbNode",
- action == Action.ADD ? "ADD" : "UPDATE",
- node);
-
- for (NodeCacheListener handler : handlers.values()) {
- try {
- handler.notifyNode(node, action);
- } catch (Exception e) {
- LOG.error("Failed notifying node add event", e);
- }
- }
- LOG.trace("processNodeUpdate: Done processing");
- }
-
- private void processNodeRemoved(Node node) {
- nodeCache.remove(node.getNodeId());
- for (NodeCacheListener handler : handlers.values()) {
- try {
- handler.notifyNode(node, Action.DELETE);
- } catch (Exception e) {
- LOG.error("Failed notifying node remove event", e);
- }
- }
- LOG.trace("processNodeRemoved: Done processing");
- }
-
- /**
- * Process the event.
- *
- * @param abstractEvent the {@link AbstractEvent} event to be handled.
- * @see EventDispatcher
- */
- @Override
- public void processEvent(AbstractEvent abstractEvent) {
- if (!(abstractEvent instanceof NodeCacheManagerEvent)) {
- LOG.error("Unable to process abstract event {}", abstractEvent);
- return;
- }
- NodeCacheManagerEvent ev = (NodeCacheManagerEvent) abstractEvent;
- LOG.trace("NodeCacheManagerImpl: dequeue Event: {}", ev.getAction());
- switch (ev.getAction()) {
- case DELETE:
- processNodeRemoved(ev.getNode());
- break;
- case UPDATE:
- processNodeUpdate(ev.getNode());
- break;
- default:
- LOG.warn("Unable to process event action {}", ev.getAction());
- break;
- }
- }
-
- public void cacheListenerAdded(final ServiceReference ref, NodeCacheListener handler){
- Long pid = (Long) ref.getProperty(org.osgi.framework.Constants.SERVICE_ID);
- handlers.put(pid, handler);
- LOG.info("Node cache listener registered, pid : {} handler : {}", pid,
- handler.getClass().getName());
- }
-
- public void cacheListenerRemoved(final ServiceReference ref){
- Long pid = (Long) ref.getProperty(org.osgi.framework.Constants.SERVICE_ID);
- handlers.remove(pid);
- LOG.debug("Node cache listener unregistered, pid {}", pid);
- }
-
- @Override
- public Map<NodeId,Node> getOvsdbNodes() {
- Map<NodeId,Node> ovsdbNodesMap = new ConcurrentHashMap<>();
- for (Map.Entry<NodeId, Node> ovsdbNodeEntry : nodeCache.entrySet()) {
- if (southbound.extractOvsdbNode(ovsdbNodeEntry.getValue()) != null) {
- ovsdbNodesMap.put(ovsdbNodeEntry.getKey(), ovsdbNodeEntry.getValue());
- }
- }
- return ovsdbNodesMap;
- }
-
- @Override
- public List<Node> getBridgeNodes() {
- List<Node> nodes = new ArrayList<>();
- for (Node node : nodeCache.values()) {
- if (southbound.getBridge(node) != null) {
- nodes.add(node);
- }
- }
- return nodes;
- }
-
- @Override
- public List <Long> getBridgeDpids(final String bridgeName) {
- List<Long> dpids = new ArrayList<>();
- for (Node node : nodeCache.values()) {
- if (bridgeName == null || southbound.getBridge(node, bridgeName) != null) {
- long dpid = southbound.getDataPathId(node);
- if (dpid != 0L) {
- dpids.add(dpid);
- }
- }
- }
- return dpids;
- }
-
- @Override
- public List<Node> getNodes() {
- return new ArrayList<>(nodeCache.values());
- }
-
- private void populateNodeCache() {
- LOG.debug("populateNodeCache : Populating the node cache");
- List<Node> nodes = southbound.readOvsdbTopologyNodes();
- for(Node ovsdbNode : nodes) {
- this.nodeCache.put(ovsdbNode.getNodeId(), ovsdbNode);
- }
- nodes = southbound.readOvsdbTopologyBridgeNodes();
- for(Node bridgeNode : nodes) {
- this.nodeCache.put(bridgeNode.getNodeId(), bridgeNode);
- }
- LOG.debug("populateNodeCache : Node cache population is done. Total nodes : {}",this.nodeCache.size());
- }
-
- @Override
- public void setDependencies(ServiceReference serviceReference) {
- southbound =
- (Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this);
- eventDispatcher =
- (EventDispatcher) ServiceHelper.getGlobalInstance(EventDispatcher.class, this);
- eventDispatcher.eventHandlerAdded(serviceReference, this);
- populateNodeCache();
- }
-
- @Override
- public void setDependencies(Object impl) {}
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.impl;
-
-import org.opendaylight.netvirt.openstack.netvirt.ConfigInterface;
-import org.opendaylight.netvirt.openstack.netvirt.api.MultiTenantAwareRouter;
-
-import java.net.InetAddress;
-import java.util.UUID;
-
-import org.osgi.framework.ServiceReference;
-
-/**
- * OpenStack router implements the MultiTenantAwareRouter interfaces It provides routing functionality for multiple
- * tenants in an OpenStack cloud
- */
-public class OpenstackRouter implements MultiTenantAwareRouter, ConfigInterface {
-
- @Override
- public void addInterface(UUID tenantId, String interfaceName, InetAddress address, int mask) {
-
- }
-
- @Override
- public void addInterface(UUID tenantId, String interfaceName, String macAddress, InetAddress address, int mask) {
-
- }
-
- @Override
- public void updateInterface(UUID tenantId, String interfaceName, InetAddress address, int mask) {
-
- }
-
- @Override
- public void updateInterface(UUID tenantId, String interfaceName, String macAddress, InetAddress address, int mask) {
-
- }
-
- @Override
- public void removeInterface(UUID tenantId, String interfaceName) {
-
- }
-
- @Override
- public void addRoute(UUID tenantId, String destinationCidr, InetAddress nextHop) {
-
- }
-
- @Override
- public void addRoute(UUID tenantId, String destinationCidr, InetAddress nextHop, Integer priority) {
-
- }
-
- @Override
- public void removeRoute(UUID tenantId, String destinationCidr, InetAddress nextHop) {
-
- }
-
- @Override
- public void removeRoute(UUID tenantId, String destinationCidr, InetAddress nextHop, Integer priority) {
-
- }
-
- @Override
- public void addDefaultRoute(UUID tenantId, InetAddress nextHop) {
-
- }
-
- @Override
- public void addDefaultRoute(UUID tenantId, InetAddress nextHop, Integer priority) {
-
- }
-
- @Override
- public void addNatRule(UUID tenantId, InetAddress matchAddress, InetAddress rewriteAddress) {
-
- }
-
- @Override
- public void setDependencies(ServiceReference serviceReference) {
-
- }
-
- @Override
- public void setDependencies(Object impl) {
-
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt.impl;
-
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ThreadFactory;
-
-import com.google.common.util.concurrent.ThreadFactoryBuilder;
-import org.opendaylight.controller.md.sal.binding.api.ClusteredDataChangeListener;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.netvirt.openstack.netvirt.MdsalHelper;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.OvsdbInventoryListener;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation;
-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.NetworkTopology;
-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.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * MDSAL dataChangeListener for the OVSDB Southbound
- *
- * @author Sam Hague (shague@redhat.com)
- */
-public class OvsdbDataChangeListener implements ClusteredDataChangeListener, AutoCloseable {
- private static final Logger LOG = LoggerFactory.getLogger(OvsdbDataChangeListener.class);
- private DataBroker dataBroker = null;
- private ListenerRegistration<DataChangeListener> registration;
- private static final ThreadFactory threadFactory = new ThreadFactoryBuilder()
- .setNameFormat("NV-OvsdbDCL-%d").build();
- private final ExecutorService executorService = Executors.newFixedThreadPool(1, threadFactory);
-
- public OvsdbDataChangeListener (DataBroker dataBroker) {
- this.dataBroker = dataBroker;
- }
-
- public void start() {
- InstanceIdentifier<Node> path = InstanceIdentifier
- .create(NetworkTopology.class)
- .child(Topology.class, new TopologyKey(MdsalHelper.OVSDB_TOPOLOGY_ID))
- .child(Node.class);
- registration = dataBroker.registerDataChangeListener(LogicalDatastoreType.OPERATIONAL, path, this,
- DataChangeScope.SUBTREE);
- LOG.info("OVSDB topology listener has been registered.");
- triggerUpdates();
- }
-
- @Override
- public void close () throws Exception {
- registration.close();
- LOG.info("OVSDB topology listener has been closed.");
- executorService.shutdown();
- }
-
- @Override
- public void onDataChanged(final AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes) {
-
- executorService.submit(() -> {
- LOG.trace("onDataChanged : {}", changes);
- processOvsdbConnections(changes);
- processOvsdbConnectionAttributeUpdates(changes);
- processBridgeCreation(changes);
- processBridgeUpdate(changes);
- processPortCreation(changes);
- processPortUpdate(changes);
- processPortDeletion(changes);
- processBridgeDeletion(changes);
- processOvsdbDisconnect(changes);
- });
- }
-
- private void processOvsdbConnections(AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes) {
- for (Map.Entry<InstanceIdentifier<?>, DataObject> created : changes.getCreatedData().entrySet()) {
- if (created.getValue() instanceof OvsdbNodeAugmentation) {
- Node ovsdbNode = getNode(changes.getCreatedData(), created);
- LOG.trace("processOvsdbConnections: <{}>, ovsdbNode: <{}>", created, ovsdbNode);
- ovsdbUpdate(ovsdbNode, created.getValue(), OvsdbInventoryListener.OvsdbType.NODE, Action.ADD);
- }
- }
- }
-
- private void processOvsdbDisconnect(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes) {
-
- for(InstanceIdentifier<?> removedOvsdbNode : changes.getRemovedPaths()) {
- if(removedOvsdbNode.getTargetType().equals(OvsdbNodeAugmentation.class)){
- //Get top node to get details of all the bridge/termination point augmentation
- // in case we want to do any cleanup task while processing node disconnection
- Node parentNode = getNode(changes.getOriginalData(), removedOvsdbNode);
- if(parentNode == null){
- //Throwing this warning in case behavior of southbound plugin changes.
- LOG.warn("OvsdbNode's {} parent node details are not present in original data,"
- + " it should not happen", parentNode);
- continue;
- }
- //Fetch data of removed connection info from original data
- @SuppressWarnings("unchecked")
- OvsdbNodeAugmentation removedOvsdbNodeAugmentationData = getDataChanges(changes.getOriginalData(),
- (InstanceIdentifier<OvsdbNodeAugmentation>) removedOvsdbNode);
-
- LOG.trace("processOvsdbDisconnect: {} ", removedOvsdbNode);
- ////Assuming Openvswitch type represent the ovsdb node connection and not OvsdbType.NODE
-
- ovsdbUpdate(parentNode, removedOvsdbNodeAugmentationData,
- OvsdbInventoryListener.OvsdbType.NODE, Action.DELETE);
- }
- }
- }
-
- private void processOvsdbConnectionAttributeUpdates(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes) {
-
- for(Map.Entry<InstanceIdentifier<?>, DataObject> updatedOvsdbNode : changes.getUpdatedData().entrySet()){
- if(updatedOvsdbNode.getKey().getTargetType().equals(OvsdbNodeAugmentation.class)){
- LOG.trace("processOvsdbConnectionAttributeUpdates: {}", updatedOvsdbNode);
- /* XXX (NOTE): Till now we don't really need the old ovsdb connection attributes data before update.
- * I am passing the updated data of both Node and resource augmentation data (connection attributes).
- * If in future we need old OvsdbNodeAugmentation attributes data, we will extract it from
- * original data and pass it as a resourceAugmentationData.
- */
- Node parentNode = getNode(changes.getUpdatedData(), updatedOvsdbNode);
- if (parentNode == null) {
- // Logging this warning, to catch any change in southbound plugin's behavior.
- LOG.warn("Parent Node for OvsdbNodeAugmentation is not found. On OvsdbNodeAugmentation update "
- + "data store must provide the parent node update. This condition should not occur "
- + "with the existing models defined in southbound plugin." );
- continue;
- }
- LOG.trace("processOvsdbConnectionAttributeUpdates <{}> related update on Node: <{}>",
- updatedOvsdbNode.getValue(), parentNode);
-
- ovsdbUpdate(parentNode, updatedOvsdbNode.getValue(),
- OvsdbInventoryListener.OvsdbType.NODE, Action.UPDATE);
- }
- }
- }
-
- private void processPortCreation(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes) {
- for(Map.Entry<InstanceIdentifier<?>, DataObject> newPort : changes.getCreatedData().entrySet()){
- if(newPort.getKey().getTargetType().equals(OvsdbTerminationPointAugmentation.class)){
- //LOG.trace("processPortCreation: {}", newPort);
- //If user created termination point only, Node will get updated
- Node tpParentNode = getNode(changes.getUpdatedData(), newPort);
- if(tpParentNode == null){
- //If user created port with the bridge itself, Node will be in created data
- tpParentNode = getNode(changes.getCreatedData(),newPort);
- }
- if(tpParentNode == null){
- // Logging this warning, to make sure we didn't change anything
- // in southbound plugin that changes this behavior.
- LOG.warn("Parent Node for port is not found. Port creation must create or "
- + "update the Node. This condition should not occur." );
- continue;
- }
-
- LOG.trace("processPortCreation <{}> creation on Node <{}>", newPort.getValue(), tpParentNode);
- ovsdbUpdate(tpParentNode, newPort.getValue(),OvsdbInventoryListener.OvsdbType.PORT, Action.ADD);
- }
- }
- }
-
- private void processPortDeletion(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes) {
-
- for(InstanceIdentifier<?> removedPort : changes.getRemovedPaths()) {
- if(removedPort.getTargetType().equals(OvsdbTerminationPointAugmentation.class)){
- Node tpParentNode = getNode(changes.getOriginalData(), removedPort);
- if(tpParentNode == null){
- //Throwing this warning in case behavior of southbound plugin changes.
- LOG.warn("Port's {} parent node details are not present in original data, "
- + "it should not happen", removedPort);
- continue;
- }
- //Fetch data of removed port from original data
- @SuppressWarnings("unchecked")
- OvsdbTerminationPointAugmentation removedTPAugmentationData = getDataChanges(changes.getOriginalData(),
- (InstanceIdentifier<OvsdbTerminationPointAugmentation>)removedPort);
-
- LOG.trace("processPortDeletion <{}> deletion on Node <{}>", removedPort, tpParentNode);
- ovsdbUpdate(tpParentNode, removedTPAugmentationData,
- OvsdbInventoryListener.OvsdbType.PORT, Action.DELETE);
- }
- }
- }
-
- private void processPortUpdate(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes) {
-
- for (Map.Entry<InstanceIdentifier<?>, DataObject> updatedPort : changes.getUpdatedData().entrySet()){
- if (updatedPort.getKey().getTargetType().equals(OvsdbTerminationPointAugmentation.class)){
- //LOG.trace("processPortUpdate: <{}>", updatedPort);
- /* XXX (NOTE): Till now we don't really need the old termination point data before update.
- * I am passing the updated data of both Node and resource augmentation data (termination-point).
- * If in future we need old TerminationPointAugmentation data, we will extract it from
- * original data and pass it as a resourceAugmentationData.
- */
- Node tpParentNode = getNode(changes.getUpdatedData(),updatedPort);
- if (tpParentNode == null){
- // Logging this warning, to catch any change in southbound plugin's behavior.
- LOG.warn("Parent Node for port is not found. On Port/Interface update data store"
- + " must provide the parent node update. This condition should not occure "
- + "with the existing models define in southbound plugin." );
- continue;
- }
-
- LOG.trace("processPortUpdate <{}> update on Node <{}>", updatedPort.getValue(), tpParentNode);
- ovsdbUpdate(tpParentNode, updatedPort.getValue(),
- OvsdbInventoryListener.OvsdbType.PORT, Action.UPDATE);
- }
- }
- }
-
- private void processBridgeCreation(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes) {
-
- for(Map.Entry<InstanceIdentifier<?>, DataObject> newBridge : changes.getCreatedData().entrySet()){
- if(newBridge.getKey().getTargetType().equals(OvsdbBridgeAugmentation.class)){
- //LOG.trace("processBridgeCreation <{}>", newBridge);
- //Bridge augmentation happens directly on the Node so Node details should also exist in created data.
- Node bridgeParentNode = getNode(changes.getCreatedData(),newBridge);
- if(bridgeParentNode == null){
- // Logging this warning, to catch any change in southbound plugin behavior
- LOG.warn("Parent Node for bridge is not found. Bridge creation must provide the Node "
- + "details in create Data Changes. This condition should not occur." );
- continue;
- }
- LOG.trace("processBridgeCreation <{}> creation on Node <{}>", newBridge.getValue(), bridgeParentNode);
- ovsdbUpdate(bridgeParentNode, newBridge.getValue(),
- OvsdbInventoryListener.OvsdbType.BRIDGE, Action.ADD);
- }
- }
- }
-
- private void processBridgeUpdate(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes) {
-
- for (Map.Entry<InstanceIdentifier<?>, DataObject> updatedBridge : changes.getUpdatedData().entrySet()) {
- if(updatedBridge.getKey().getTargetType().equals(OvsdbBridgeAugmentation.class)){
- //LOG.trace("processBridgeUpdate <{}>", updatedBridge);
- /* XXX (NOTE): Till now we don't really need the old bridge data before update.
- * I am passing the updated data of both Node and resource augmentation data.
- * If in future we need old bridgeAugmentationData, we will extract it from
- * original data and pass it as a resourceAugmentationData.
- */
-
- Node bridgeParentNode = getNode(changes.getUpdatedData(), updatedBridge);
- if(bridgeParentNode == null){
- // Logging this warning, to catch any change in southbound plugin behavior
- LOG.warn("Parent Node for bridge is not found. Bridge update must provide the Node "
- + "details in updated Data Changes. This condition should not occure" );
- continue;
- }
- LOG.trace("processBridgeUpdate <{}> update on Node <{}>", updatedBridge.getValue(), bridgeParentNode);
- ovsdbUpdate(bridgeParentNode, updatedBridge.getValue(),
- OvsdbInventoryListener.OvsdbType.BRIDGE, Action.UPDATE);
- }
- }
- }
-
- private void processBridgeDeletion(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes) {
-
- for(InstanceIdentifier<?> removedBridge : changes.getRemovedPaths()) {
- if(removedBridge.getTargetType().equals(OvsdbBridgeAugmentation.class)){
- Node bridgeParentNode = getNode(changes.getOriginalData(), removedBridge);
- if(bridgeParentNode == null){
- //Throwing this warning to catch the behavior change of southbound plugin.
- LOG.warn("Bridge's {} parent node details are not present in original data"
- + ", it should not happen", removedBridge);
- continue;
- }
- //Fetch data of removed bridge from original data
- @SuppressWarnings("unchecked")
- OvsdbBridgeAugmentation removedBridgeAugmentationData = getDataChanges(changes.getOriginalData(),
- (InstanceIdentifier<OvsdbBridgeAugmentation>) removedBridge);
-
- LOG.debug("processBridgeDeletion <{}> deletion on Node <{}>", removedBridge,bridgeParentNode);
- ovsdbUpdate(bridgeParentNode, removedBridgeAugmentationData,
- OvsdbInventoryListener.OvsdbType.BRIDGE, Action.DELETE);
- }
- }
- }
-
- private Node getNode(Map<InstanceIdentifier<?>, DataObject> changes,
- Map.Entry<InstanceIdentifier<?>, DataObject> change) {
- InstanceIdentifier<Node> nodeInstanceIdentifier = change.getKey().firstIdentifierOf(Node.class);
- return (Node)changes.get(nodeInstanceIdentifier);
- }
-
- private Node getNode(Map<InstanceIdentifier<?>, DataObject> changes,InstanceIdentifier<?> path) {
- InstanceIdentifier<Node> nodeInstanceIdentifier = path.firstIdentifierOf(Node.class);
- return (Node)changes.get(nodeInstanceIdentifier);
- }
-
- private <T extends DataObject> T getDataChanges(
- Map<InstanceIdentifier<?>, DataObject> changes,InstanceIdentifier<T> path){
-
- for(Map.Entry<InstanceIdentifier<?>,DataObject> change : changes.entrySet()){
- if(change.getKey().getTargetType().equals(path.getTargetType())){
- @SuppressWarnings("unchecked")
- T dataObject = (T) change.getValue();
- return dataObject;
- }
- }
- return null;
- }
-
- private void ovsdbUpdate(Node node, DataObject resourceAugmentationDataChanges,
- OvsdbInventoryListener.OvsdbType ovsdbType, Action action) {
-
- Set<OvsdbInventoryListener> ovsdbInventoryListeners = OvsdbInventoryServiceImpl.getOvsdbInventoryListeners();
- for (OvsdbInventoryListener ovsdbInventoryListener : ovsdbInventoryListeners) {
- ovsdbInventoryListener.ovsdbUpdate(node, resourceAugmentationDataChanges, ovsdbType, action);
- }
- }
-
- private void triggerUpdates() {
- Set<OvsdbInventoryListener> ovsdbInventoryListeners = OvsdbInventoryServiceImpl.getOvsdbInventoryListeners();
- for (OvsdbInventoryListener ovsdbInventoryListener : ovsdbInventoryListeners) {
- ovsdbInventoryListener.triggerUpdates();
- }
- }
-}
+++ /dev/null
-/*
- * Copyright © 2015, 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt.impl;
-
-import com.google.common.collect.Sets;
-
-import java.util.Set;
-
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.ProviderContext;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.impl.NeutronFloatingIPDataTreeChangeListener;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.impl.NeutronRouterChangeListener;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.impl.NeutronSecurityRuleDataChangeListener;
-import org.opendaylight.netvirt.openstack.netvirt.ClusterAwareMdsalUtils;
-import org.opendaylight.netvirt.openstack.netvirt.ConfigInterface;
-import org.opendaylight.netvirt.openstack.netvirt.NetvirtProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-import org.opendaylight.netvirt.openstack.netvirt.api.OvsdbInventoryService;
-import org.opendaylight.netvirt.openstack.netvirt.api.OvsdbInventoryListener;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.impl.NeutronNetworkChangeListener;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.impl.NeutronPortChangeListener;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.impl.NeutronSubnetChangeListener;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.impl.NeutronLoadBalancerPoolChangeListener;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.impl.NeutronLoadBalancerPoolMemberChangeListener;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
-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.TopologyId;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyBuilder;
-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.yangtools.yang.binding.InstanceIdentifier;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * OvsdbInventoryServiceImpl is the implementation for {@link OvsdbInventoryService}
- *
- * @author Sam Hague (shague@redhat.com)
- */
-public class OvsdbInventoryServiceImpl implements ConfigInterface, OvsdbInventoryService {
- private static final Logger LOG = LoggerFactory.getLogger(OvsdbInventoryServiceImpl.class);
- private final DataBroker dataBroker;
- private static Set<OvsdbInventoryListener> ovsdbInventoryListeners = Sets.newCopyOnWriteArraySet();
- private OvsdbDataChangeListener ovsdbDataChangeListener = null;
- private static ClusterAwareMdsalUtils mdsalUtils = null;
-
- public OvsdbInventoryServiceImpl(final DataBroker dataBroker) {
- this.dataBroker = dataBroker;
- LOG.info("OvsdbInventoryServiceImpl initialized");
- ovsdbDataChangeListener = new OvsdbDataChangeListener(dataBroker);
- mdsalUtils = new ClusterAwareMdsalUtils(dataBroker);
- }
-
- @Override
- public void listenerAdded(OvsdbInventoryListener listener) {
- ovsdbInventoryListeners.add(listener);
- LOG.info("listenerAdded: {}", listener);
- }
-
- @Override
- public void listenerRemoved(OvsdbInventoryListener listener) {
- ovsdbInventoryListeners.remove(listener);
- LOG.info("listenerRemoved: {}", listener);
- }
-
- @Override
- public void providersReady() {
- ovsdbDataChangeListener.start();
- initializeNeutronModelsDataChangeListeners(dataBroker);
- initializeNetvirtTopology();
- }
-
- public static Set<OvsdbInventoryListener> getOvsdbInventoryListeners() {
- return ovsdbInventoryListeners;
- }
-
- @Override
- public void setDependencies(ServiceReference serviceReference) {}
-
- @Override
- public void setDependencies(Object impl) {}
-
- private void initializeNetvirtTopology() {
- while(!NetvirtProvider.isMasterElected()){
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- LOG.warn("Netvirt thread waiting on Netvirt Ownership Election is interrupted");
- }
- }
- final TopologyId topologyId = new TopologyId(new Uri(Constants.NETVIRT_TOPOLOGY_ID));
- InstanceIdentifier<Topology> path =
- InstanceIdentifier.create(NetworkTopology.class).child(Topology.class, new TopologyKey(topologyId));
- TopologyBuilder tpb = new TopologyBuilder();
- tpb.setTopologyId(topologyId);
- if (! mdsalUtils.put(LogicalDatastoreType.OPERATIONAL, path, tpb.build())) {
- LOG.error("Error initializing netvirt topology");
- }
- }
-
- private void initializeNeutronModelsDataChangeListeners(
- DataBroker db) {
- new NeutronNetworkChangeListener(db);
- new NeutronSubnetChangeListener(db);
- new NeutronPortChangeListener(db);
- new NeutronRouterChangeListener(db);
- new NeutronFloatingIPDataTreeChangeListener(db).init();
- new NeutronLoadBalancerPoolChangeListener(db);
- new NeutronLoadBalancerPoolMemberChangeListener(db);
- new NeutronSecurityRuleDataChangeListener(db);
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.impl;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.function.Predicate;
-import java.util.stream.Collectors;
-import org.opendaylight.netvirt.openstack.netvirt.ConfigInterface;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-import org.opendaylight.netvirt.openstack.netvirt.api.NetworkingProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.NetworkingProviderManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.OvsdbInventoryService;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-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.network.topology.topology
- .Node;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ProviderNetworkManagerImpl implements ConfigInterface, NetworkingProviderManager {
- private static final Logger LOG = LoggerFactory.getLogger(ProviderNetworkManagerImpl.class);
- private Map<Long, ProviderEntry> providers = new HashMap<>();
- private Map<NodeId, NetworkingProvider> nodeToProviderMapping = new HashMap<>();
- private volatile OvsdbInventoryService ovsdbInventoryService;
-
- @Override
- public NetworkingProvider getProvider(Node node) {
- NodeId nodeId = node.getNodeId();
- if (nodeToProviderMapping.get(nodeId) != null) {
- return nodeToProviderMapping.get(nodeId);
- }
-
- final String targetVersion = Constants.OPENFLOW13;
- Predicate<ProviderEntry> providerEntryPredicate = providerEntry -> {
- //ToDo: This should match on southboundProtocol and providerType too
- return providerEntry.getProperties().get(Constants.OPENFLOW_VERSION_PROPERTY).equals(targetVersion);
- };
-
- List<ProviderEntry> matchingProviders =
- providers.values().stream().filter(providerEntryPredicate).collect(Collectors.toList());
- if (matchingProviders.isEmpty()) {
- LOG.error("No providers matching {} found", targetVersion);
- }
-
- // Return the first match as only have one matching provider today
- // ToDo: Tie-breaking logic
- NetworkingProvider provider = matchingProviders.get(0).getProvider();
- nodeToProviderMapping.put(nodeId, provider);
- return provider;
- }
-
- public void providerAdded(final ServiceReference ref, final NetworkingProvider provider){
- Map <String, String> properties = new HashMap<>();
- Long pid = (Long) ref.getProperty(org.osgi.framework.Constants.SERVICE_ID);
- properties.put(Constants.SOUTHBOUND_PROTOCOL_PROPERTY,
- (String) ref.getProperty(Constants.SOUTHBOUND_PROTOCOL_PROPERTY));
- properties.put(Constants.OPENFLOW_VERSION_PROPERTY,
- (String) ref.getProperty(Constants.OPENFLOW_VERSION_PROPERTY));
- properties.put(Constants.PROVIDER_TYPE_PROPERTY, (String) ref.getProperty(Constants.PROVIDER_TYPE_PROPERTY));
- providers.put(pid, new ProviderEntry(provider, properties));
- LOG.trace("Neutron Networking Provider Registered: {}, with {} and pid={}",
- provider.getClass().getName(), properties.toString(), pid);
-
- ovsdbInventoryService.providersReady();
- }
-
- public void providerRemoved(final ServiceReference ref){
- Long pid = (Long)ref.getProperty(org.osgi.framework.Constants.SERVICE_ID);
- providers.remove(pid);
- LOG.trace("Neutron Networking Provider Removed: {}", pid);
- }
-
- @Override
- public void setDependencies(ServiceReference serviceReference) {
- ovsdbInventoryService =
- (OvsdbInventoryService) ServiceHelper.getGlobalInstance(OvsdbInventoryService.class, this);
- }
-
- @Override
- public void setDependencies(Object impl) {
-
- }
-
- private class ProviderEntry {
- NetworkingProvider provider;
- Map<String, String> properties;
-
- ProviderEntry(NetworkingProvider provider, Map<String, String> properties) {
- this.provider = provider;
- this.properties = properties;
- }
-
- public NetworkingProvider getProvider() {
- return provider;
- }
-
- public Map<String, String> getProperties() {
- return properties;
- }
- }
-
-}
+++ /dev/null
-/*
- * Copyright © 2014, 2017 HP, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.impl;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronPortCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSecurityGroupCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.ConfigInterface;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-import org.opendaylight.netvirt.openstack.netvirt.api.SecurityGroupCacheManger;
-import org.opendaylight.netvirt.openstack.netvirt.api.SecurityServicesManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityGroup;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityRule;
-import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSecurityRuleCRUD;
-import org.opendaylight.netvirt.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.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-
-
-/**
- * @author Aswin Suryanarayanan.
- */
-
-public class SecurityGroupCacheManagerImpl implements ConfigInterface, SecurityGroupCacheManger {
-
- private final Map<String, Map<String, NodeId>> securityGroupCache = new ConcurrentHashMap<>();
- private static final Logger LOG = LoggerFactory.getLogger(SecurityGroupCacheManagerImpl.class);
- private volatile SecurityServicesManager securityServicesManager;
- private volatile Southbound southbound;
- private volatile INeutronPortCRUD neutronPortCache;
- private volatile NeutronL3Adapter neutronL3Adapter;
- private volatile INeutronSecurityRuleCRUD neutronSecurityRule;
-
- @Override
- public void portAdded(String securityGroupUuid, String portUuid) {
- LOG.debug("In portAdded securityGroupUuid: {} portUuid: {} " , securityGroupUuid, portUuid);
- NeutronPort port = neutronL3Adapter.getPortPreferablyFromCleanupCache(portUuid);
- if(port == null) {
- return;
- }
- processPortAdded(securityGroupUuid, port);
- }
-
- @Override
- public void portRemoved(String securityGroupUuid, String portUuid) {
- LOG.debug("In portRemoved securityGroupUuid: {} portUuid: {} " , securityGroupUuid, portUuid);
- NeutronPort port = neutronL3Adapter.getPortPreferablyFromCleanupCache(portUuid);
- if(port == null) {
- return;
- }
- processPortRemoved(securityGroupUuid, port);
- }
-
- @Override
- public void addToCache(String remoteSgUuid, String portUuid, NodeId nodeId) {
- LOG.debug("In addToCache remoteSgUuid:" + remoteSgUuid + " portUuid:" + portUuid);
- Map<String, NodeId> remoteSgPorts = securityGroupCache.computeIfAbsent(remoteSgUuid, k -> new HashMap<>());
- remoteSgPorts.put(portUuid, nodeId);
- }
-
- @Override
- public void removeFromCache(String remoteSgUuid, String portUuid, NodeId nodeId) {
- LOG.debug("In removeFromCache remoteSgUuid:" + remoteSgUuid + " portUuid:" + portUuid);
- Map<String, NodeId> remoteSgPorts = securityGroupCache.get(remoteSgUuid);
- if (null == remoteSgPorts) {
- LOG.debug("The port list is empty for security group:" + remoteSgUuid);
- return;
- }
- Set<String> portSet = remoteSgPorts.keySet();
- for (Iterator<String> iterator = portSet.iterator(); iterator.hasNext();) {
- String cachedPort = iterator.next();
- if (cachedPort.equals(portUuid)) {
- NodeId cachedNodeId = remoteSgPorts.get(cachedPort);
- if(cachedNodeId.equals(nodeId)) {
- iterator.remove();
- break;
- }
- }
- }
- if (portSet.isEmpty()) {
- securityGroupCache.remove(remoteSgUuid);
- }
- }
-
- private void processPortAdded(String securityGroupUuid, NeutronPort port) {
- processSyncRule(securityGroupUuid, port, true);
- }
-
- private void processSyncRule(String securityGroupUuid, NeutronPort port, boolean write) {
- /*
- * Itreate through the cache maintained for the security group added. For each port in the cache
- * add the rule to allow traffic to/from the new port added.
- */
- LOG.debug("In processPortAdded securityGroupUuid: {}, NeutronPort: {}", securityGroupUuid, port);
- Map<String, NodeId> portMap = securityGroupCache.get(securityGroupUuid);
- if (null == portMap) {
- LOG.debug("The port list is empty for security group: {}", securityGroupUuid);
- return;
- }
- Set portSet = portMap.entrySet();
- Iterator itr = portSet.iterator();
- Map<String, List<NeutronSecurityRule>> secGrpRulesMap = new HashMap<String, List<NeutronSecurityRule>>();
- while(itr.hasNext()) {
- Map.Entry<String, NodeId> portEntry = (Map.Entry)itr.next();
- String cachedportUuid = portEntry.getKey();
- NodeId nodeId = portEntry.getValue();
- if (cachedportUuid.equals(port.getID())) {
- continue;
- }
- NeutronPort cachedport = neutronL3Adapter.getPortPreferablyFromCleanupCache(cachedportUuid);
- if(cachedport == null) {
- continue;
- }
- retrieveAndSyncSecurityRules(securityGroupUuid, cachedport, nodeId, secGrpRulesMap, port, write);
- }
- }
-
- private void processPortRemoved(String securityGroupUuid, NeutronPort port) {
- processSyncRule(securityGroupUuid, port, false);
- }
-
- private void retrieveAndSyncSecurityRules(String securityGroupUuid, NeutronPort cachedport, NodeId nodeId,
- Map<String, List<NeutronSecurityRule> > secGrpRulesMap, NeutronPort currentPort, boolean write) {
- /*
- * Get the list of security rules in the port with portUuid that has securityGroupUuid as a remote
- * security group.
- */
- List<NeutronSecurityRule> securityRules = new ArrayList<NeutronSecurityRule>();
- List<NeutronSecurityGroup> securityGroups = cachedport.getSecurityGroups();
- for (NeutronSecurityGroup securityGroup : securityGroups) {
- securityRules = secGrpRulesMap.get(securityGroup.getSecurityGroupUUID());
- if (securityRules == null) {
- securityRules = getSecurityRulesforGroup(securityGroup);
- secGrpRulesMap.put(securityGroup.getSecurityGroupUUID(), securityRules);
- }
- for (NeutronSecurityRule securityRule : securityRules) {
- if (securityGroupUuid.equals(securityRule.getSecurityRemoteGroupID())) {
- if (currentPort.getFixedIPs() == null) {
- continue;
- }
- for (Neutron_IPs vmIp : currentPort.getFixedIPs()) {
- if (write) {
- securityServicesManager.syncSecurityRule(cachedport, securityRule, vmIp, nodeId, true);
- } else {
- securityServicesManager.syncSecurityRule(cachedport, securityRule, vmIp, nodeId, false);
- }
- }
- }
- }
- }
- }
-
- private void init() {
- /*
- * Rebuild the cache in case of a restart.
- */
- Map<String, NodeId> portNodeCache = getPortNodeCache();
- List<NeutronPort> portList = neutronPortCache.getAllPorts();
- for (NeutronPort port:portList) {
- List<NeutronSecurityGroup> securityGroupList = port.getSecurityGroups();
- if ( null != securityGroupList) {
- for (NeutronSecurityGroup securityGroup : securityGroupList) {
- List<NeutronSecurityRule> securityRuleList = getSecurityRulesforGroup(securityGroup);
- if ( null != securityRuleList) {
- for (NeutronSecurityRule securityRule : securityRuleList) {
- if (null != securityRule.getSecurityRemoteGroupID()) {
- this.addToCache(securityRule.getSecurityRemoteGroupID(), port.getID(), portNodeCache.get(port.getID()));
- }
- }
- }
- }
- }
- }
- }
-
- private Map<String, NodeId> getPortNodeCache() {
- Map<String, NodeId> portNodeCache = new HashMap();
- List<Node> toplogyNodes = southbound.readOvsdbTopologyNodes();
-
- for (Node topologyNode : toplogyNodes) {
- try {
- Node node = southbound.getBridgeNode(topologyNode,Constants.INTEGRATION_BRIDGE);
- if (node == null) {
- LOG.error("getNode: br-int interface is not found for node:{}", topologyNode.getNodeId().getValue());
- }
- List<OvsdbTerminationPointAugmentation> ovsdbPorts = southbound.getTerminationPointsOfBridge(node);
- for (OvsdbTerminationPointAugmentation ovsdbPort : ovsdbPorts) {
- String uuid = southbound.getInterfaceExternalIdsValue(ovsdbPort,
- Constants.EXTERNAL_ID_INTERFACE_ID);
- NodeId nodeId = node.getNodeId();
- if (null != uuid && null != nodeId) {
- portNodeCache.put(uuid, nodeId);
- }
- }
- } catch (Exception e) {
- LOG.error("Exception during handlingNeutron network delete", e);
- }
- }
- return portNodeCache;
- }
-
- private List<NeutronSecurityRule> getSecurityRulesforGroup(NeutronSecurityGroup securityGroup) {
- List<NeutronSecurityRule> securityRules = new ArrayList<>();
- List<NeutronSecurityRule> rules = neutronSecurityRule.getAllNeutronSecurityRules();
- for (NeutronSecurityRule securityRule : rules) {
- if (securityGroup.getID().equals(securityRule.getSecurityRuleGroupID())) {
- securityRules.add(securityRule);
- }
- }
- return securityRules;
- }
-
- @Override
- public void setDependencies(ServiceReference serviceReference) {
- neutronL3Adapter =
- (NeutronL3Adapter) ServiceHelper.getGlobalInstance(NeutronL3Adapter.class, this);
- securityServicesManager =
- (SecurityServicesManager) ServiceHelper.getGlobalInstance(SecurityServicesManager.class, this);
- southbound =
- (Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this);
- neutronPortCache = (INeutronPortCRUD) ServiceHelper.getGlobalInstance(INeutronPortCRUD.class, this);
- neutronSecurityRule = (INeutronSecurityRuleCRUD) ServiceHelper.getGlobalInstance(INeutronSecurityRuleCRUD.class, this);
- init();
- }
-
- @Override
- public void setDependencies(Object impl) {
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.impl;
-
-import org.opendaylight.netvirt.openstack.netvirt.ConfigInterface;
-import org.opendaylight.netvirt.openstack.netvirt.api.ConfigurationService;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-import org.opendaylight.netvirt.openstack.netvirt.api.EgressAclProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.IngressAclProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.SecurityGroupCacheManger;
-import org.opendaylight.netvirt.openstack.netvirt.api.SecurityServicesManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityGroup;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityRule;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSubnet;
-import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronNetworkCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronPortCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSubnetCRUD;
-import org.opendaylight.netvirt.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.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.network.topology.topology.node.TerminationPoint;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.HashMap;
-import java.util.Map;
-
-public class SecurityServicesImpl implements ConfigInterface, SecurityServicesManager {
-
- private static final Logger LOG = LoggerFactory.getLogger(TenantNetworkManagerImpl.class);
- private volatile INeutronPortCRUD neutronPortCache;
- private volatile INeutronSubnetCRUD neutronSubnetCache;
- private volatile Southbound southbound;
- private volatile NodeCacheManager nodeCacheManager;
- private volatile INeutronNetworkCRUD neutronNetworkCache;
- private volatile ConfigurationService configurationService;
- private volatile IngressAclProvider ingressAclProvider;
- private volatile EgressAclProvider egressAclProvider;
- private volatile NeutronL3Adapter neutronL3Adapter;
- private volatile SecurityGroupCacheManger securityGroupCacheManger;
- private volatile Map<NodeId, Long> nodeIdToDpIdCache = new HashMap<NodeId, Long>();
- private boolean isConntrackEnabled = false;
-
- public SecurityServicesImpl() {
- super();
- }
-
- public SecurityServicesImpl(boolean isConntrack) {
- super();
- this.isConntrackEnabled = isConntrack;
- }
-
- @Override
- public boolean isPortSecurityReady(OvsdbTerminationPointAugmentation terminationPointAugmentation) {
- if (neutronPortCache == null) {
- LOG.error("neutron port is null");
- return false;
- }
- LOG.trace("isPortSecurityReady for {}", terminationPointAugmentation.getName());
- String neutronPortId = southbound.getInterfaceExternalIdsValue(terminationPointAugmentation,
- Constants.EXTERNAL_ID_INTERFACE_ID);
- if (neutronPortId == null) {
- return false;
- }
- NeutronPort neutronPort = neutronL3Adapter.getPortPreferablyFromCleanupCache(neutronPortId);
- if (neutronPort == null) {
- return false;
- }
- String deviceOwner = neutronPort.getDeviceOwner();
- if (!deviceOwner.contains("compute")) {
- LOG.debug("Port {} is not a compute host, it is a: {}", neutronPortId, deviceOwner);
- }
- LOG.debug("isPortSecurityReady() is a {} ", deviceOwner);
- List<NeutronSecurityGroup> securityGroups = neutronPort.getSecurityGroups();
- if (securityGroups.isEmpty()) {
- LOG.debug("Check for device: {} does not contain a Security Group for port: {}", deviceOwner,
- neutronPortId);
- return false;
- }
- LOG.debug("Security Group Check {} does contain a Neutron Security Group", neutronPortId);
- return true;
- }
-
- @Override
- public List<NeutronSecurityGroup> getSecurityGroupInPortList(OvsdbTerminationPointAugmentation
- terminationPointAugmentation) {
- List<NeutronSecurityGroup> neutronSecurityGroups = new ArrayList<>();
- if (neutronPortCache == null) {
- LOG.error("neutron port is null");
- return neutronSecurityGroups;
- }
- LOG.trace("getSecurityGroupInPortList for {}", terminationPointAugmentation.getName());
- String neutronPortId = southbound.getInterfaceExternalIdsValue(terminationPointAugmentation,
- Constants.EXTERNAL_ID_INTERFACE_ID);
- if (neutronPortId == null) {
- return neutronSecurityGroups;
- }
- NeutronPort neutronPort = neutronL3Adapter.getPortPreferablyFromCleanupCache(neutronPortId);
- if (neutronPort == null) {
- return neutronSecurityGroups;
- }
- neutronSecurityGroups = neutronPort.getSecurityGroups();
- return neutronSecurityGroups;
-
- }
-
- @Override
- public NeutronPort getDhcpServerPort(OvsdbTerminationPointAugmentation terminationPointAugmentation) {
- if (neutronPortCache == null) {
- LOG.warn("getDHCPServerPort: neutron port cache is null");
- }
- LOG.trace("getDHCPServerPort for {}",
- terminationPointAugmentation.getName());
- NeutronPort neutronPort = null;
- try {
- String neutronPortId = southbound.getInterfaceExternalIdsValue(terminationPointAugmentation,
- Constants.EXTERNAL_ID_INTERFACE_ID);
- if (neutronPortId == null) {
- return null;
- }
- if (null != neutronPortCache) {
- neutronPort = neutronL3Adapter.getPortPreferablyFromCleanupCache(neutronPortId);
- if (neutronPort == null) {
- return null;
- }
- }
- /* if the current port is a DHCP port, return the same*/
- if (neutronPort.getDeviceOwner().contains("dhcp")) {
- return neutronPort;
- }
- /*Since all the fixed ip assigned to a port should be
- *from the same network, first port is sufficient.*/
- List<Neutron_IPs> fixedIps = neutronPort.getFixedIPs();
- if (null == fixedIps || 0 == fixedIps.size() ) {
- LOG.error("getDHCPServerPort: No fixed ip is assigned");
- return null;
- }
- /* Get all the ports in the subnet and identify the dhcp port*/
- String subnetUuid = fixedIps.iterator().next().getSubnetUUID();
- NeutronSubnet neutronSubnet = neutronSubnetCache.getSubnet(subnetUuid);
- if (neutronSubnet == null) {
- LOG.error("getDHCPServerPort: No subnet is found for " + subnetUuid);
- return null;
- }
- List<NeutronPort> ports = neutronSubnet.getPortsInSubnet();
- for (NeutronPort port : ports) {
- if (port.getDeviceOwner().contains("dhcp")) {
- return port;
- }
- }
- } catch (Exception e) {
- LOG.error("getDHCPServerPort:getDHCPServerPort failed due to ", e);
- return null;
- }
- return null;
- }
-
- @Override
- public NeutronPort getNeutronPortFromDhcpIntf(
- OvsdbTerminationPointAugmentation terminationPointAugmentation) {
- if (neutronPortCache == null) {
- LOG.error("getNeutronPortFromDhcpIntf: neutron port is null");
- return null;
- }
- String neutronPortId = southbound.getInterfaceExternalIdsValue(
- terminationPointAugmentation,
- Constants.EXTERNAL_ID_INTERFACE_ID);
- if (neutronPortId == null) {
- return null;
- }
- NeutronPort neutronPort = neutronL3Adapter.getPortPreferablyFromCleanupCache(neutronPortId);
- if (neutronPort == null) {
- return null;
- }
- /* if the current port is a DHCP port, return true*/
- if (neutronPort.getDeviceOwner().contains("dhcp")) {
- LOG.trace("getNeutronPortFromDhcpIntf: neutronPort is a dhcp port", neutronPort );
- return neutronPort;
- }
- return null;
- }
-
-
- @Override
- public NeutronPort getNeutronPortFromCache(OvsdbTerminationPointAugmentation terminationPointAugmentation) {
- NeutronPort neutronPort = null;
- LOG.trace("getNeutronPortFromCache for {}",
- terminationPointAugmentation.getName());
- try {
- String neutronPortId = southbound.getInterfaceExternalIdsValue(terminationPointAugmentation,
- Constants.EXTERNAL_ID_INTERFACE_ID);
- if (neutronPortId == null) {
- return null;
- }
- if (null != neutronPortCache) {
- neutronPort = neutronL3Adapter.getPortPreferablyFromCleanupCache(neutronPortId);
- if (neutronPort == null) {
- return null;
- }
- }
- LOG.trace("getNeutronPortFromCache: neutron port of {} got from cleanupcache", neutronPortId);
- } catch (Exception e) {
- LOG.warn("getNeutronPortFromCache:getNeutronPortFromCache failed due to ", e);
- return null;
- }
- return neutronPort;
- }
-
-
-
- @Override
- public boolean isComputePort(OvsdbTerminationPointAugmentation terminationPointAugmentation) {
- if (neutronPortCache == null) {
- LOG.warn("isComputePort : neutronPortCache is null");
- }
- NeutronPort neutronPort = null;
- LOG.trace("isComputePort for {}", terminationPointAugmentation.getName());
- String neutronPortId = southbound.getInterfaceExternalIdsValue(terminationPointAugmentation,
- Constants.EXTERNAL_ID_INTERFACE_ID);
- if (neutronPortId == null) {
- return false;
- }
- if (neutronPortCache != null) {
- neutronPort = neutronPortCache.getPort(neutronPortId);
- }
- if (neutronPort == null) {
- neutronPort = getNeutronPortFromCache(terminationPointAugmentation);
- if (neutronPort == null) {
- return false;
- }
- }
- /*Check the device owner and if it contains compute to identify
- * whether it is a compute port.*/
- String deviceOwner = neutronPort.getDeviceOwner();
- if (!deviceOwner.contains("compute")) {
- LOG.debug("isComputePort : Port {} is not a DHCP server port for device owner {}",
- neutronPortId,deviceOwner);
- return false;
- }
- return true;
- }
-
- @Override
- public boolean isLastPortinSubnet(Node node, OvsdbTerminationPointAugmentation terminationPointAugmentation) {
- if (neutronPortCache == null) {
- LOG.error("isLastPortinSubnet: neutronPortCache is null");
- }
- NeutronPort neutronPort = null;
- try {
- LOG.trace("isLastPortinSubnet: for {}", terminationPointAugmentation.getName());
- String neutronPortId = southbound.getInterfaceExternalIdsValue(terminationPointAugmentation,
- Constants.EXTERNAL_ID_INTERFACE_ID);
- if (neutronPortId == null) {
- return false;
- }
- if (neutronPortCache != null) {
- neutronPort = neutronPortCache.getPort(neutronPortId);
- }
- if (neutronPort == null) {
- neutronPort = getNeutronPortFromCache(terminationPointAugmentation);
- if (neutronPort == null) {
- LOG.error("isLastPortinSubnet: neutron port of {} is not found", neutronPortId);
- return false;
- }
- }
- List<Neutron_IPs> neutronPortFixedIp = neutronPort.getFixedIPs();
- if (null == neutronPortFixedIp || neutronPortFixedIp.isEmpty()) {
- return false;
- }
- /*Get all the ports in the current node and check whether there
- * is any port belonging to the same subnet of the input
- */
- List<TerminationPoint> terminationPoints = node.getTerminationPoint();
- if (terminationPoints != null && !terminationPoints.isEmpty()) {
- for (TerminationPoint tp : terminationPoints) {
- OvsdbTerminationPointAugmentation ovsdbTerminationPointAugmentation =
- tp.getAugmentation(OvsdbTerminationPointAugmentation.class);
- if (ovsdbTerminationPointAugmentation != null && !ovsdbTerminationPointAugmentation
- .getName().equals(Constants.INTEGRATION_BRIDGE)) {
- String portId = southbound.getInterfaceExternalIdsValue(ovsdbTerminationPointAugmentation,
- Constants.EXTERNAL_ID_INTERFACE_ID);
- if (null != portId) {
- NeutronPort port = neutronPortCache.getPort(portId);
- if (null != port && !(port.getID().equals(neutronPort.getID()))
- && port.getDeviceOwner().contains("compute")) {
- List<Neutron_IPs> portFixedIp = port.getFixedIPs();
- if (null == portFixedIp || portFixedIp.isEmpty()) {
- return false;
- }
- if (portFixedIp.iterator().next().getSubnetUUID()
- .equals(neutronPort.getFixedIPs().iterator().next().getSubnetUUID())) {
- LOG.trace("isLastPortinSubnet: Port is not the only port.");
- return false;
- }
- }
- }
- }
- }
- }
- } catch (Exception e) {
- LOG.error("isLastPortinSubnet: isLastPortinSubnet failed due to ", e);
- return false;
- }
- return true;
- }
-
- @Override
- public boolean isLastPortinBridge(Node node, OvsdbTerminationPointAugmentation terminationPointAugmentation) {
- LOG.trace("isLastPortinBridge: for {}", terminationPointAugmentation.getName());
- List<TerminationPoint> terminationPoints = node.getTerminationPoint();
- /*Check whether the node has any port other than br-int*/
- if (terminationPoints != null && !terminationPoints.isEmpty()) {
- for (TerminationPoint tp : terminationPoints) {
- OvsdbTerminationPointAugmentation ovsdbTerminationPointAugmentation =
- tp.getAugmentation(OvsdbTerminationPointAugmentation.class);
- if (null != ovsdbTerminationPointAugmentation
- && !(ovsdbTerminationPointAugmentation.getName().equals(Constants.INTEGRATION_BRIDGE))
- && !(terminationPointAugmentation.getInterfaceUuid()
- .equals(ovsdbTerminationPointAugmentation.getInterfaceUuid()))) {
- LOG.debug("isLastPortinBridge: it the last port in bridge {}",
- terminationPointAugmentation.getName());
- return false;
- }
- }
- }
- return true;
- }
-
- @Override
- public List<Neutron_IPs> getIpAddressList(OvsdbTerminationPointAugmentation terminationPointAugmentation) {
- if (neutronPortCache == null) {
- LOG.warn("getIpAddress: neutronPortCache is null");
- }
- NeutronPort neutronPort = null;
- LOG.trace("getIpAddress: for {}", terminationPointAugmentation.getName());
- String neutronPortId = southbound.getInterfaceExternalIdsValue(terminationPointAugmentation,
- Constants.EXTERNAL_ID_INTERFACE_ID);
- if (neutronPortId == null) {
- return null;
- }
- if (neutronPortCache != null) {
- neutronPort = neutronPortCache.getPort(neutronPortId);
- }
- if (neutronPort == null) {
- neutronPort = getNeutronPortFromCache(terminationPointAugmentation);
- }
- if (neutronPort == null) {
- LOG.error("getIpAddress: neutron port of {} is not found", neutronPortId);
- return null;
- }
- return neutronPort.getFixedIPs();
- }
-
- @Override
- public List<Neutron_IPs> getVmListForSecurityGroup(String portUuid, String securityGroupUuid) {
- List<Neutron_IPs> vmListForSecurityGroup = new ArrayList<>();
- /*For every port check whether security grouplist contains the current
- * security group.*/
- try {
- for (String neutronPortUuid:neutronL3Adapter.getPortCleanupCache().keySet()) {
- NeutronPort neutronPort = neutronL3Adapter.getPortCleanupCache().get(neutronPortUuid);
- if (!neutronPort.getDeviceOwner().contains("compute")) {
- LOG.debug("getVMListForSecurityGroup : the port {} is not "
- + "compute port belongs to {}", neutronPort.getID(), neutronPort.getDeviceOwner());
- continue;
- }
- if (portUuid.equals(neutronPort.getID())) {
- continue;
- }
- List<NeutronSecurityGroup> securityGroups = neutronPort.getSecurityGroups();
- if (null != securityGroups) {
- for (NeutronSecurityGroup securityGroup:securityGroups) {
- if (securityGroup.getSecurityGroupUUID().equals(securityGroupUuid)) {
- LOG.debug("getVMListForSecurityGroup : adding ports with ips {} "
- + "compute port", neutronPort.getFixedIPs());
- if (neutronPort.getFixedIPs() != null) {
- vmListForSecurityGroup.addAll(neutronPort.getFixedIPs());
- }
- }
- }
- }
-
- }
- } catch (Exception e) {
- LOG.error("getVMListForSecurityGroup: getVMListForSecurityGroup"
- + " failed due to ", e);
- return null;
- }
- return vmListForSecurityGroup;
-
- }
-
- @Override
- public void syncFixedSecurityGroup(NeutronPort port, boolean write) {
-
- Node node = getNode(port);
- if (node == null) {
- return;
- }
- NeutronNetwork neutronNetwork = neutronNetworkCache.getNetwork(port.getNetworkUUID());
- if (null == neutronNetwork) {
- neutronNetwork = neutronL3Adapter.getNetworkFromCleanupCache(port.getNetworkUUID());
- if (neutronNetwork == null) {
- return;
- }
- }
- OvsdbTerminationPointAugmentation intf = getInterface(node, port);
- if (intf == null) {
- return;
- }
- String attachedMac = southbound.getInterfaceExternalIdsValue(intf, Constants.EXTERNAL_ID_VM_MAC);
- if (attachedMac == null) {
- LOG.debug("syncFixedSecurityGroup: No AttachedMac seen in {}", intf);
- return;
- }
- long dpid = getDpidOfIntegrationBridge(node);
- if (dpid == 0L) {
- return;
- }
- String segmentationId = neutronNetwork.getProviderSegmentationID();
- long localPort = southbound.getOFPort(intf);
- NeutronPort dhcpPort = this.getDhcpServerPort(intf);
- if (dhcpPort != null) {
- ingressAclProvider.programFixedSecurityGroup(dpid, segmentationId,
- dhcpPort.getMacAddress(), localPort, attachedMac, write);
- }
- List<Neutron_IPs> srcAddressList = null;
- srcAddressList = this.getIpAddressList(intf);
- egressAclProvider.programFixedSecurityGroup(dpid, segmentationId,
- attachedMac, localPort, srcAddressList, write);
- }
-
- @Override
- public void syncSecurityGroup(NeutronPort port, List<NeutronSecurityGroup> securityGroupList, boolean write) {
- LOG.trace("syncSecurityGroup:" + securityGroupList + " Write:" + write);
- if (null != port && null != port.getSecurityGroups()) {
- Node node = getNode(port);
- if (node == null) {
- return;
- }
- NodeId nodeId = node.getNodeId();
- NeutronNetwork neutronNetwork = neutronNetworkCache.getNetwork(port.getNetworkUUID());
- if (null == neutronNetwork) {
- neutronNetwork = neutronL3Adapter.getNetworkFromCleanupCache(port.getNetworkUUID());
- if (neutronNetwork == null) {
- return;
- }
- }
- String segmentationId = neutronNetwork.getProviderSegmentationID();
- OvsdbTerminationPointAugmentation intf = getInterface(node, port);
- if (intf == null) {
- return;
- }
- long localPort = southbound.getOFPort(intf);
- String attachedMac = southbound.getInterfaceExternalIdsValue(intf, Constants.EXTERNAL_ID_VM_MAC);
- if (attachedMac == null) {
- LOG.debug("syncSecurityGroup: No AttachedMac seen in {}", intf);
- return;
- }
- long dpid = getDpidOfIntegrationBridge(node);
- if (dpid == 0L) {
- return;
- }
- String neutronPortId = southbound.getInterfaceExternalIdsValue(intf,
- Constants.EXTERNAL_ID_INTERFACE_ID);
- if (neutronPortId == null) {
- LOG.debug("syncSecurityGroup: No neutronPortId seen in {}", intf);
- return;
- }
- for (NeutronSecurityGroup securityGroupInPort:securityGroupList) {
- ingressAclProvider.programPortSecurityGroup(dpid, segmentationId, attachedMac, localPort,
- securityGroupInPort, neutronPortId, nodeId, write);
- egressAclProvider.programPortSecurityGroup(dpid, segmentationId, attachedMac, localPort,
- securityGroupInPort, neutronPortId, nodeId, write);
- if (write) {
- securityGroupCacheManger.portAdded(securityGroupInPort.getSecurityGroupUUID(), neutronPortId);
- } else {
- securityGroupCacheManger.portRemoved(securityGroupInPort.getSecurityGroupUUID(), neutronPortId);
- }
- }
- }
- }
-
- @Override
- public void syncSecurityRule(NeutronPort port, NeutronSecurityRule securityRule, Neutron_IPs vmIp, NodeId nodeId,
- boolean write) {
- LOG.trace("syncSecurityGroup:" + securityRule + " Write:" + write);
- if (null != port && null != port.getSecurityGroups()) {
- if (nodeId != null) {
- syncSecurityRules(port, securityRule, vmIp, nodeId, port.getMacAddress(), write);
- } else {
- return;
- }
- }
- }
-
- private void syncSecurityRules(NeutronPort port, NeutronSecurityRule securityRule, Neutron_IPs vmIp, NodeId nodeId,
- String attachedMac, boolean write) {
- NeutronNetwork neutronNetwork = neutronL3Adapter.getNetworkFromCleanupCache(port.getNetworkUUID());
- if (null == neutronNetwork) {
- neutronNetwork = neutronNetworkCache.getNetwork(port.getNetworkUUID());
- }
- if (neutronNetwork == null) {
- return;
- }
- String segmentationId = neutronNetwork.getProviderSegmentationID();
- Node node = nodeCacheManager.getNode(nodeId);
- Long dpId = this.nodeIdToDpIdCache.get(nodeId);
- if(dpId == null ) {
- dpId = getDpidOfIntegrationBridge(node);
- if (dpId != 0L) {
- this.nodeIdToDpIdCache.put(nodeId , dpId);
- }
- }
- if (dpId == 0L) {
- return;
- }
- if (NeutronSecurityRule.ETHERTYPE_IPV4.equals(securityRule.getSecurityRuleEthertype())) {
- if (NeutronSecurityRule.DIRECTION_INGRESS.equals(securityRule.getSecurityRuleDirection())) {
- ingressAclProvider.programPortSecurityRule(dpId, segmentationId, attachedMac,
- securityRule, vmIp, write);
- } else if (NeutronSecurityRule.DIRECTION_EGRESS.equals(securityRule.getSecurityRuleDirection())) {
- egressAclProvider.programPortSecurityRule(dpId, segmentationId, attachedMac,
- securityRule, vmIp, write);
- }
- }
- }
-
- private long getDpidOfIntegrationBridge(Node node) {
- LOG.trace("getDpidOfIntegrationBridge:" + node);
- long dpid = 0L;
- if (southbound.getBridgeName(node).equals(configurationService.getIntegrationBridgeName())) {
- dpid = getDpid(node);
- }
- if (dpid == 0L) {
- LOG.warn("getDpidOfIntegerationBridge: dpid not found: {}", node);
- }
- return dpid;
- }
-
- private long getDpid(Node node) {
- LOG.trace("getDpid" + node);
- long dpid = southbound.getDataPathId(node);
- if (dpid == 0) {
- LOG.warn("getDpid: dpid not found: {}", node);
- }
- return dpid;
- }
-
- private Node getNode(NeutronPort port) {
- LOG.trace("getNode:Port" + port);
- List<Node> toplogyNodes = southbound.readOvsdbTopologyNodes();
-
- for (Node topologyNode : toplogyNodes) {
- try {
- Node node = southbound.getBridgeNode(topologyNode,Constants.INTEGRATION_BRIDGE);
- if (node == null) {
- LOG.error("getNode: br-int interface is not found for node:{}", topologyNode.getNodeId().getValue());
- }
- List<OvsdbTerminationPointAugmentation> ovsdbPorts = southbound.getTerminationPointsOfBridge(node);
- for (OvsdbTerminationPointAugmentation ovsdbPort : ovsdbPorts) {
- String uuid = southbound.getInterfaceExternalIdsValue(ovsdbPort,
- Constants.EXTERNAL_ID_INTERFACE_ID);
- if (null != uuid && uuid.equals(port.getID())) {
- return node;
- }
- }
- } catch (Exception e) {
- LOG.error("Exception during handlingNeutron network delete", e);
- }
- }
- LOG.info("no node found for port:" + port);
- return null;
- }
-
- private OvsdbTerminationPointAugmentation getInterface(Node node, NeutronPort port) {
- LOG.trace("getInterface:Node:" + node + " Port:" + port);
- try {
- List<OvsdbTerminationPointAugmentation> ovsdbPorts = southbound.getTerminationPointsOfBridge(node);
- for (OvsdbTerminationPointAugmentation ovsdbPort : ovsdbPorts) {
- String uuid = southbound.getInterfaceExternalIdsValue(ovsdbPort,
- Constants.EXTERNAL_ID_INTERFACE_ID);
- if (null != uuid && uuid.equals(port.getID())) {
- return ovsdbPort;
- }
- }
- } catch (Exception e) {
- LOG.error("Exception during handlingNeutron network delete", e);
- }
- LOG.info("no interface found for node: " + node + " port:" + port);
- return null;
- }
-
- @Override
- public boolean isPortSecurityEnabled(OvsdbTerminationPointAugmentation intf) {
- NeutronPort neutronPort = getNeutronPortFromCache(intf);
- if (null == neutronPort) {
- LOG.error("Neutron Port is null: " + intf);
- return false;
- }
- if (neutronPort.getPortSecurityEnabled()) {
- LOG.info("Port Security is enabled for Port: " + neutronPort);
- return true;
- }
- LOG.info("Port Security is not enabled for Port: " + neutronPort);
- return false;
- }
-
- @Override
- public void setDependencies(ServiceReference serviceReference) {
- neutronL3Adapter =
- (NeutronL3Adapter) ServiceHelper.getGlobalInstance(NeutronL3Adapter.class, this);
- southbound =
- (Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this);
- neutronNetworkCache =
- (INeutronNetworkCRUD) ServiceHelper.getGlobalInstance(INeutronNetworkCRUD.class, this);
- nodeCacheManager =
- (NodeCacheManager) ServiceHelper.getGlobalInstance(NodeCacheManager.class, this);
- configurationService =
- (ConfigurationService) ServiceHelper.getGlobalInstance(ConfigurationService.class, this);
- securityGroupCacheManger =
- (SecurityGroupCacheManger) ServiceHelper.getGlobalInstance(SecurityGroupCacheManger.class, this);
- }
-
- @Override
- public void setDependencies(Object impl) {
- if (impl instanceof INeutronPortCRUD) {
- neutronPortCache = (INeutronPortCRUD)impl;
- } else if (impl instanceof INeutronSubnetCRUD) {
- neutronSubnetCache = (INeutronSubnetCRUD) impl;
- } else if (impl instanceof IngressAclProvider) {
- ingressAclProvider = (IngressAclProvider) impl;
- } else if (impl instanceof EgressAclProvider) {
- egressAclProvider = (EgressAclProvider) impl;
- }
- }
-
- @Override
- public boolean isConntrackEnabled() {
- return isConntrackEnabled;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt.impl;
-
-import java.math.BigInteger;
-import java.security.InvalidParameterException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.netvirt.openstack.netvirt.NetworkHandler;
-import org.opendaylight.netvirt.openstack.netvirt.api.OvsdbTables;
-import org.opendaylight.netvirt.openstack.netvirt.ClusterAwareMdsalUtils;
-import org.opendaylight.netvirt.openstack.netvirt.MdsalHelper;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.DatapathTypeBase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.DatapathTypeNetdev;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeDpdk;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentationBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeName;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeProtocolBase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeRef;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbTerminationPointAugmentation;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbTerminationPointAugmentationBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.BridgeExternalIds;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.BridgeOtherConfigs;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.BridgeOtherConfigsBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.ControllerEntry;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.ControllerEntryBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.ProtocolEntry;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.ProtocolEntryBuilder;
-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.InterfaceTypeEntry;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ManagedNodeEntry;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.OpenvswitchExternalIds;
-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.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.InterfaceExternalIds;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.Options;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.OptionsBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.OptionsKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.PortExternalIds;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.PortOtherConfigs;
-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.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.NodeKey;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPoint;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPointBuilder;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.ImmutableBiMap;
-
-/**
- * Utility class to wrap mdsal transactions.
- *
- * @author Sam Hague (shague@redhat.com)
- */
-public class SouthboundImpl implements Southbound {
- private static final Logger LOG = LoggerFactory.getLogger(SouthboundImpl.class);
- private final DataBroker databroker;
- private static final String PATCH_PORT_TYPE = "patch";
- private final ClusterAwareMdsalUtils mdsalUtils;
-
- /**
- * Class constructor setting the data broker.
- *
- * @param dataBroker the {@link org.opendaylight.controller.md.sal.binding.api.DataBroker}
- */
- public SouthboundImpl(DataBroker dataBroker) {
- this.databroker = dataBroker;
- mdsalUtils = new ClusterAwareMdsalUtils(dataBroker);
- }
-
- public DataBroker getDatabroker() {
- return databroker;
- }
-
- public ConnectionInfo getConnectionInfo(Node ovsdbNode) {
- ConnectionInfo connectionInfo = null;
- OvsdbNodeAugmentation ovsdbNodeAugmentation = extractOvsdbNode(ovsdbNode);
- if (ovsdbNodeAugmentation != null) {
- connectionInfo = ovsdbNodeAugmentation.getConnectionInfo();
- }
- return connectionInfo;
- }
-
- public OvsdbNodeAugmentation extractOvsdbNode(Node node) {
- return node.getAugmentation(OvsdbNodeAugmentation.class);
- }
-
- public NodeId extractBridgeOvsdbNodeId(Node bridgeNode) {
- NodeId ovsdbNodeId = null;
- OvsdbBridgeAugmentation bridgeAugmentation = extractBridgeAugmentation(bridgeNode);
- if (bridgeAugmentation != null) {
- @SuppressWarnings("unchecked")
- InstanceIdentifier<Node> ovsdbNodeIid =
- (InstanceIdentifier<Node>) (bridgeAugmentation.getManagedBy().getValue());
- ovsdbNodeId = InstanceIdentifier.keyOf(ovsdbNodeIid).getNodeId();
- }
- return ovsdbNodeId;
- }
-
- public List<Node> readOvsdbTopologyNodes() {
- List<Node> ovsdbNodes = new ArrayList<>();
- InstanceIdentifier<Topology> topologyInstanceIdentifier = MdsalHelper.createInstanceIdentifier();
- Topology topology = mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, topologyInstanceIdentifier);
- if (topology != null && topology.getNode() != null) {
- for (Node node : topology.getNode()) {
- OvsdbNodeAugmentation ovsdbNodeAugmentation = node.getAugmentation(OvsdbNodeAugmentation.class);
- if (ovsdbNodeAugmentation != null) {
- ovsdbNodes.add(node);
- }
- }
- }
- return ovsdbNodes;
- }
-
- public List<Node> readOvsdbTopologyBridgeNodes() {
- List<Node> ovsdbNodes = new ArrayList<>();
- InstanceIdentifier<Topology> topologyInstanceIdentifier = MdsalHelper.createInstanceIdentifier();
- Topology topology = mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, topologyInstanceIdentifier);
- if (topology != null && topology.getNode() != null) {
- for (Node node : topology.getNode()) {
- OvsdbBridgeAugmentation ovsdbBridgeAugmentation = node.getAugmentation(OvsdbBridgeAugmentation.class);
- if (ovsdbBridgeAugmentation != null) {
- ovsdbNodes.add(node);
- }
- }
- }
- return ovsdbNodes;
- }
-
- public Node readOvsdbNode(Node bridgeNode) {
- Node ovsdbNode = null;
- OvsdbBridgeAugmentation bridgeAugmentation = extractBridgeAugmentation(bridgeNode);
- if (bridgeAugmentation != null) {
- InstanceIdentifier<Node> ovsdbNodeIid =
- (InstanceIdentifier<Node>) bridgeAugmentation.getManagedBy().getValue();
- ovsdbNode = mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, ovsdbNodeIid);
- }else{
- LOG.debug("readOvsdbNode: Provided node is not a bridge node : {}",bridgeNode);
- }
- return ovsdbNode;
- }
-
- public String getOvsdbNodeUUID(Node node) {
- String nodeUUID = null;
- OvsdbNodeAugmentation ovsdbNodeAugmentation = node.getAugmentation(OvsdbNodeAugmentation.class);
- if (ovsdbNodeAugmentation != null) {
- // TODO replace with proper uuid and not the system-id
- nodeUUID = getOsdbNodeExternalIdsValue(ovsdbNodeAugmentation, "system-id");
- }
- return nodeUUID;
- }
-
- public String getOsdbNodeExternalIdsValue(OvsdbNodeAugmentation ovsdbNodeAugmentation, String key) {
- String value = null;
- List<OpenvswitchExternalIds> pairs = ovsdbNodeAugmentation.getOpenvswitchExternalIds();
- if (pairs != null && !pairs.isEmpty()) {
- for (OpenvswitchExternalIds pair : pairs) {
- if (pair.getExternalIdKey().equals(key)) {
- value = pair.getExternalIdValue();
- break;
- }
- }
- }
- return value;
- }
-
- public boolean addBridge(Node ovsdbNode, String bridgeName, List<String> controllersStr,
- final Class<? extends DatapathTypeBase> dpType) {
- return addBridge(ovsdbNode, bridgeName, controllersStr, dpType, null);
- }
-
- public boolean addBridge(Node ovsdbNode, String bridgeName, List<String> controllersStr,
- final Class<? extends DatapathTypeBase> dpType, String mac) {
- boolean result;
-
- LOG.info("addBridge: node: {}, bridgeName: {}, controller(s): {}", ovsdbNode, bridgeName, controllersStr);
- ConnectionInfo connectionInfo = getConnectionInfo(ovsdbNode);
- if (connectionInfo != null) {
- NodeBuilder bridgeNodeBuilder = new NodeBuilder();
- InstanceIdentifier<Node> bridgeIid =
- MdsalHelper.createInstanceIdentifier(ovsdbNode.getKey(), bridgeName);
- NodeId bridgeNodeId = MdsalHelper.createManagedNodeId(bridgeIid);
- bridgeNodeBuilder.setNodeId(bridgeNodeId);
- OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder = new OvsdbBridgeAugmentationBuilder();
- ovsdbBridgeAugmentationBuilder.setControllerEntry(createControllerEntries(controllersStr));
- ovsdbBridgeAugmentationBuilder.setBridgeName(new OvsdbBridgeName(bridgeName));
- ovsdbBridgeAugmentationBuilder.setProtocolEntry(createMdsalProtocols());
- ovsdbBridgeAugmentationBuilder.setFailMode(
- MdsalHelper.OVSDB_FAIL_MODE_MAP.inverse().get("secure"));
- BridgeOtherConfigsBuilder bridgeOtherConfigsBuilder = new BridgeOtherConfigsBuilder();
- bridgeOtherConfigsBuilder.setBridgeOtherConfigKey(MdsalHelper.DISABLE_IN_BAND);
- bridgeOtherConfigsBuilder.setBridgeOtherConfigValue("true");
- List<BridgeOtherConfigs> bridgeOtherConfigsList = new ArrayList<>();
- bridgeOtherConfigsList.add(bridgeOtherConfigsBuilder.build());
- if (mac != null) {
- BridgeOtherConfigsBuilder macOtherConfigBuilder = new BridgeOtherConfigsBuilder();
- macOtherConfigBuilder.setBridgeOtherConfigKey(MdsalHelper.HWADDR);
- macOtherConfigBuilder.setBridgeOtherConfigValue(mac);
- bridgeOtherConfigsList.add(macOtherConfigBuilder.build());
- }
- ovsdbBridgeAugmentationBuilder.setBridgeOtherConfigs(bridgeOtherConfigsList);
- setManagedByForBridge(ovsdbBridgeAugmentationBuilder, ovsdbNode.getKey());
- if (dpType != null) {
- ovsdbBridgeAugmentationBuilder.setDatapathType(dpType);
- }
- if (isOvsdbNodeDpdk(ovsdbNode)) {
- ovsdbBridgeAugmentationBuilder.setDatapathType(DatapathTypeNetdev.class);
- }
- bridgeNodeBuilder.addAugmentation(OvsdbBridgeAugmentation.class, ovsdbBridgeAugmentationBuilder.build());
-
- Node node = bridgeNodeBuilder.build();
- result = mdsalUtils.put(LogicalDatastoreType.CONFIGURATION, bridgeIid, node);
- LOG.info("addBridge: result: {}", result);
- } else {
- throw new InvalidParameterException("Could not find ConnectionInfo");
- }
- return result;
- }
-
- public boolean deleteBridge(Node ovsdbNode) {
- InstanceIdentifier<Node> bridgeIid =
- MdsalHelper.createInstanceIdentifier(ovsdbNode.getNodeId());
-
- boolean result = mdsalUtils.delete(LogicalDatastoreType.CONFIGURATION, bridgeIid);
- LOG.info("deleteBridge node: {}, bridgeName: {} result : {}", ovsdbNode, ovsdbNode.getNodeId(),result);
- return result;
- }
-
- public OvsdbBridgeAugmentation readBridge(Node node, String name) {
- OvsdbBridgeAugmentation ovsdbBridgeAugmentation = null;
- ConnectionInfo connectionInfo = getConnectionInfo(node);
- if (connectionInfo != null) {
- InstanceIdentifier<Node> bridgeIid =
- MdsalHelper.createInstanceIdentifier(node.getKey(), name);
- Node bridgeNode = mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, bridgeIid);
- if (bridgeNode != null) {
- ovsdbBridgeAugmentation = bridgeNode.getAugmentation(OvsdbBridgeAugmentation.class);
- }
- }
- return ovsdbBridgeAugmentation;
- }
-
- public Node readBridgeNode(Node node, String name) {
- Node ovsdbNode = node;
- if (extractNodeAugmentation(ovsdbNode) == null) {
- ovsdbNode = readOvsdbNode(node);
- if (ovsdbNode == null) {
- return null;
- }
- }
- Node bridgeNode = null;
- ConnectionInfo connectionInfo = getConnectionInfo(ovsdbNode);
- if (connectionInfo != null) {
- InstanceIdentifier<Node> bridgeIid =
- MdsalHelper.createInstanceIdentifier(node.getKey(), name);
- bridgeNode = mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, bridgeIid);
- }
- return bridgeNode;
- }
-
- public Node getBridgeNode(Node node, String bridgeName) {
- OvsdbBridgeAugmentation bridge = extractBridgeAugmentation(node);
- if (bridge != null && bridge.getBridgeName().getValue().equals(bridgeName)) {
- return node;
- } else {
- return readBridgeNode(node, bridgeName);
- }
- }
-
- public String getBridgeUuid(Node node, String name) {
- String uuid = null;
- OvsdbBridgeAugmentation ovsdbBridgeAugmentation = readBridge(node, name);
- if (ovsdbBridgeAugmentation != null) {
- uuid = ovsdbBridgeAugmentation.getBridgeUuid().getValue();
- }
- return uuid;
- }
-
- private void setManagedByForBridge(OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder,
- NodeKey ovsdbNodeKey) {
- InstanceIdentifier<Node> connectionNodePath = MdsalHelper.createInstanceIdentifier(ovsdbNodeKey.getNodeId());
- ovsdbBridgeAugmentationBuilder.setManagedBy(new OvsdbNodeRef(connectionNodePath));
- }
-
- private List<ControllerEntry> createControllerEntries(List<String> controllersStr) {
- List<ControllerEntry> controllerEntries = new ArrayList<>();
- if (controllersStr != null) {
- for (String controllerStr : controllersStr) {
- ControllerEntryBuilder controllerEntryBuilder = new ControllerEntryBuilder();
- controllerEntryBuilder.setTarget(new Uri(controllerStr));
- controllerEntries.add(controllerEntryBuilder.build());
- }
- }
- return controllerEntries;
- }
-
- private List<ProtocolEntry> createMdsalProtocols() {
- List<ProtocolEntry> protocolList = new ArrayList<>();
- ImmutableBiMap<String, Class<? extends OvsdbBridgeProtocolBase>> mapper =
- MdsalHelper.OVSDB_PROTOCOL_MAP.inverse();
- protocolList.add(new ProtocolEntryBuilder().
- setProtocol(mapper.get("OpenFlow13")).build());
- return protocolList;
- }
-
- public long getDataPathId(Node node) {
- long dpid = 0L;
- String datapathId = getDatapathId(node);
- if (datapathId != null) {
- dpid = new BigInteger(datapathId.replaceAll(":", ""), 16).longValue();
- }
- return dpid;
- }
-
- public String getDatapathId(Node node) {
- OvsdbBridgeAugmentation ovsdbBridgeAugmentation = node.getAugmentation(OvsdbBridgeAugmentation.class);
- return getDatapathId(ovsdbBridgeAugmentation);
- }
-
- public String getDatapathId(OvsdbBridgeAugmentation ovsdbBridgeAugmentation) {
- String datapathId = null;
- if (ovsdbBridgeAugmentation != null && ovsdbBridgeAugmentation.getDatapathId() != null) {
- datapathId = ovsdbBridgeAugmentation.getDatapathId().getValue();
- }
- return datapathId;
- }
-
- public OvsdbBridgeAugmentation getBridge(Node node, String name) {
- OvsdbBridgeAugmentation bridge = node.getAugmentation(OvsdbBridgeAugmentation.class);
- if ((bridge != null) && (!bridge.getBridgeName().getValue().equals(name))) {
- bridge = null;
- }
- return bridge;
- }
-
- public OvsdbBridgeAugmentation getBridge(Node node) {
- return node.getAugmentation(OvsdbBridgeAugmentation.class);
- }
-
- public String getBridgeName(Node node) {
- String bridgeName = null;
- OvsdbBridgeAugmentation bridge = getBridge(node);
- if (bridge != null) {
- bridgeName = bridge.getBridgeName().getValue();
- }
- return bridgeName;
- }
-
- public String extractBridgeName(Node node) {
- return node.getAugmentation(OvsdbBridgeAugmentation.class).getBridgeName().getValue();
- }
-
- public OvsdbBridgeAugmentation extractBridgeAugmentation(Node node) {
- if (node == null) {
- return null;
- }
- return node.getAugmentation(OvsdbBridgeAugmentation.class);
- }
-
- public List<Node> getAllBridgesOnOvsdbNode(Node node) {
- List<Node> nodes = new ArrayList<>();
- List<ManagedNodeEntry> managedNodes = node.getAugmentation(OvsdbNodeAugmentation.class).getManagedNodeEntry();
- for (ManagedNodeEntry managedNode : managedNodes) {
- InstanceIdentifier<?> bridgeIid = managedNode.getBridgeRef().getValue();
- Node bridgeNode = (Node) mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, bridgeIid);
- if (bridgeNode != null) {
- nodes.add(bridgeNode);
- }
- }
- return nodes;
- }
-
- public boolean isBridgeOnOvsdbNode(Node ovsdbNode, String bridgeName) {
- boolean found = false;
- OvsdbNodeAugmentation ovsdbNodeAugmentation = extractNodeAugmentation(ovsdbNode);
- if (ovsdbNodeAugmentation != null) {
- List<ManagedNodeEntry> managedNodes = ovsdbNodeAugmentation.getManagedNodeEntry();
- if (managedNodes != null) {
- for (ManagedNodeEntry managedNode : managedNodes) {
- InstanceIdentifier<?> bridgeIid = managedNode.getBridgeRef().getValue();
- if (bridgeIid.toString().contains(bridgeName)) {
- found = true;
- break;
- }
- }
- }
- }
- return found;
- }
-
- public boolean isOvsdbNodeDpdk(Node ovsdbNode) {
- boolean found = false;
- OvsdbNodeAugmentation ovsdbNodeAugmentation = extractNodeAugmentation(ovsdbNode);
- if (ovsdbNodeAugmentation != null) {
- List<InterfaceTypeEntry> ifTypes = ovsdbNodeAugmentation.getInterfaceTypeEntry();
- if (ifTypes != null) {
- for (InterfaceTypeEntry ifType : ifTypes) {
- if (ifType.getInterfaceType().equals(InterfaceTypeDpdk.class)) {
- found = true;
- break;
- }
- }
- }
- }
- return found;
- }
-
- public OvsdbNodeAugmentation extractNodeAugmentation(Node node) {
- return node.getAugmentation(OvsdbNodeAugmentation.class);
- }
-
- /**
- * Method read ports from bridge node. Method will check if the provided node
- * has the ports details, if not, it will read from Operational data store.
- * @param node Target bridge to getch termination points from.
- * @return List of termination points on the given bridge
- */
- public List<OvsdbTerminationPointAugmentation> getTerminationPointsOfBridge(Node node) {
- List<OvsdbTerminationPointAugmentation> tpAugmentations = extractTerminationPointAugmentations(node);
- if(tpAugmentations.isEmpty()){
- tpAugmentations = readTerminationPointAugmentations(node);
- }
- return tpAugmentations;
- }
-
- public OvsdbTerminationPointAugmentation getTerminationPointOfBridge(Node node, String portName) {
- OvsdbTerminationPointAugmentation tpAugmentation = extractTerminationPointAugmentation(node,portName);
- if(tpAugmentation == null){
- List<OvsdbTerminationPointAugmentation> tpAugmentations = readTerminationPointAugmentations(node);
- if(tpAugmentations != null){
- for(OvsdbTerminationPointAugmentation ovsdbTpAugmentation : tpAugmentations){
- if(ovsdbTpAugmentation.getName().equals(portName)){
- return ovsdbTpAugmentation;
- }
- }
- }
- }
- return tpAugmentation;
- }
-
- public OvsdbTerminationPointAugmentation extractTerminationPointAugmentation(Node bridgeNode, String portName) {
- if (bridgeNode.getAugmentation(OvsdbBridgeAugmentation.class) != null) {
- List<OvsdbTerminationPointAugmentation> tpAugmentations = extractTerminationPointAugmentations(bridgeNode);
- for (OvsdbTerminationPointAugmentation ovsdbTerminationPointAugmentation : tpAugmentations) {
- if (ovsdbTerminationPointAugmentation.getName().equals(portName)) {
- return ovsdbTerminationPointAugmentation;
- }
- }
- }
- return null;
- }
-
- public List<TerminationPoint> extractTerminationPoints(Node node) {
- List<TerminationPoint> terminationPoints = new ArrayList<>();
- OvsdbBridgeAugmentation ovsdbBridgeAugmentation = node.getAugmentation(OvsdbBridgeAugmentation.class);
- if (ovsdbBridgeAugmentation != null) {
- terminationPoints.addAll(node.getTerminationPoint());
- }
- return terminationPoints;
- }
-
- public List<OvsdbTerminationPointAugmentation> extractTerminationPointAugmentations( Node node ) {
- List<OvsdbTerminationPointAugmentation> tpAugmentations = new ArrayList<>();
- if (node == null) {
- LOG.error("extractTerminationPointAugmentations: Node value is null");
- return Collections.emptyList();
- }
- List<TerminationPoint> terminationPoints = node.getTerminationPoint();
- if(terminationPoints != null && !terminationPoints.isEmpty()){
- for(TerminationPoint tp : terminationPoints){
- OvsdbTerminationPointAugmentation ovsdbTerminationPointAugmentation =
- tp.getAugmentation(OvsdbTerminationPointAugmentation.class);
- if (ovsdbTerminationPointAugmentation != null) {
- tpAugmentations.add(ovsdbTerminationPointAugmentation);
- }
- }
- }
- return tpAugmentations;
- }
-
- public List<OvsdbTerminationPointAugmentation> readTerminationPointAugmentations(Node node) {
- if (node == null) {
- LOG.error("readTerminationPointAugmentations: Node value is null");
- return Collections.emptyList();
- }
- InstanceIdentifier<Node> bridgeNodeIid = MdsalHelper.createInstanceIdentifier(node.getNodeId());
- Node operNode = mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, bridgeNodeIid);
- if(operNode != null){
- return extractTerminationPointAugmentations(operNode);
- }
- return new ArrayList<>();
- }
-
- public String getInterfaceExternalIdsValue(
- OvsdbTerminationPointAugmentation terminationPointAugmentation, String key) {
- String value = null;
- List<InterfaceExternalIds> pairs = terminationPointAugmentation.getInterfaceExternalIds();
- if (pairs != null && !pairs.isEmpty()) {
- for (InterfaceExternalIds pair : pairs) {
- if (pair.getExternalIdKey().equals(key)) {
- value = pair.getExternalIdValue();
- break;
- }
- }
- }
- return value;
- }
-
- public Boolean addTerminationPoint(Node bridgeNode, String bridgeName, String portName, String type) {
- InstanceIdentifier<TerminationPoint> tpIid =
- MdsalHelper.createTerminationPointInstanceIdentifier(bridgeNode, portName);
- OvsdbTerminationPointAugmentationBuilder tpAugmentationBuilder =
- new OvsdbTerminationPointAugmentationBuilder();
-
- tpAugmentationBuilder.setName(portName);
- if (type != null) {
- tpAugmentationBuilder.setInterfaceType(MdsalHelper.OVSDB_INTERFACE_TYPE_MAP.get(type));
- }
- TerminationPointBuilder tpBuilder = new TerminationPointBuilder();
- tpBuilder.setKey(InstanceIdentifier.keyOf(tpIid));
- tpBuilder.addAugmentation(OvsdbTerminationPointAugmentation.class, tpAugmentationBuilder.build());
- return mdsalUtils.put(LogicalDatastoreType.CONFIGURATION, tpIid, tpBuilder.build());
- }
-
- public Boolean deleteTerminationPoint(Node bridgeNode, String portName) {
- InstanceIdentifier<TerminationPoint> tpIid =
- MdsalHelper.createTerminationPointInstanceIdentifier(bridgeNode, portName);
- return mdsalUtils.delete(LogicalDatastoreType.CONFIGURATION, tpIid);
- }
-
- public Boolean addTerminationPoint(Node bridgeNode, String bridgeName, String portName,
- String type, Map<String, String> options) {
- InstanceIdentifier<TerminationPoint> tpIid = MdsalHelper.createTerminationPointInstanceIdentifier(
- bridgeNode, portName);
- OvsdbTerminationPointAugmentationBuilder tpAugmentationBuilder = new OvsdbTerminationPointAugmentationBuilder();
-
- tpAugmentationBuilder.setName(portName);
- if (type != null) {
- tpAugmentationBuilder.setInterfaceType(MdsalHelper.OVSDB_INTERFACE_TYPE_MAP.get(type));
- }
-
- List<Options> optionsList = new ArrayList<>();
- for (Map.Entry<String, String> entry : options.entrySet()) {
- OptionsBuilder optionsBuilder = new OptionsBuilder();
- optionsBuilder.setKey(new OptionsKey(entry.getKey()));
- optionsBuilder.setOption(entry.getKey());
- optionsBuilder.setValue(entry.getValue());
- optionsList.add(optionsBuilder.build());
- }
- tpAugmentationBuilder.setOptions(optionsList);
-
- TerminationPointBuilder tpBuilder = new TerminationPointBuilder();
- tpBuilder.setKey(InstanceIdentifier.keyOf(tpIid));
- tpBuilder.addAugmentation(OvsdbTerminationPointAugmentation.class, tpAugmentationBuilder.build());
- /* TODO SB_MIGRATION should this be merge or mdsalUtils.put */
- return mdsalUtils.put(LogicalDatastoreType.CONFIGURATION, tpIid, tpBuilder.build());
- }
-
- public TerminationPoint readTerminationPoint(Node bridgeNode, String bridgeName, String portName) {
- InstanceIdentifier<TerminationPoint> tpIid = MdsalHelper.createTerminationPointInstanceIdentifier(
- bridgeNode, portName);
- return mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, tpIid);
- }
-
- public Boolean addTunnelTerminationPoint(Node bridgeNode, String bridgeName, String portName, String type,
- Map<String, String> options) {
- return addTerminationPoint(bridgeNode, bridgeName, portName, type, options);
- }
-
- public Boolean isTunnelTerminationPointExist(Node bridgeNode, String bridgeName, String portName){
- return readTerminationPoint(bridgeNode, bridgeName, portName) != null;
- }
-
- public Boolean addPatchTerminationPoint(Node node, String bridgeName, String portName, String peerPortName) {
- Map<String, String> option = new HashMap<>();
- option.put("peer", peerPortName);
- return addTerminationPoint(node, bridgeName, portName, PATCH_PORT_TYPE, option);
- }
-
- public String getExternalId(Node node, OvsdbTables table, String key) {
- switch (table) {
- case BRIDGE:
- OvsdbBridgeAugmentation bridge = extractBridgeAugmentation(node);
- if (bridge != null && bridge.getBridgeExternalIds() != null) {
- for (BridgeExternalIds bridgeExternaIds :bridge.getBridgeExternalIds()) {
- if (bridgeExternaIds.getBridgeExternalIdKey().equals(key)) {
- return bridgeExternaIds.getBridgeExternalIdValue();
- }
- }
- }
- break;
- case CONTROLLER:
- LOG.warn("getExternalId: There is no external_id for OvsdbTables: ", table);
- return null;
- case OPENVSWITCH:
- OvsdbNodeAugmentation ovsdbNode = extractNodeAugmentation(node);
- if (ovsdbNode == null) {
- Node nodeFromReadOvsdbNode = readOvsdbNode(node);
- if (nodeFromReadOvsdbNode != null) {
- ovsdbNode = extractNodeAugmentation(nodeFromReadOvsdbNode);
- }
- }
- if (ovsdbNode != null && ovsdbNode.getOpenvswitchExternalIds() != null) {
- for (OpenvswitchExternalIds openvswitchExternalIds : ovsdbNode.getOpenvswitchExternalIds()) {
- if (openvswitchExternalIds.getExternalIdKey().equals(key)) {
- return openvswitchExternalIds.getExternalIdValue();
- }
- }
- }
- break;
- case PORT:
- List <OvsdbTerminationPointAugmentation> ports = extractTerminationPointAugmentations(node);
- for (OvsdbTerminationPointAugmentation port : ports) {
- if (port != null && port.getPortExternalIds() != null) {
- for (PortExternalIds portExternalIds :port.getPortExternalIds()) {
- if (portExternalIds.getExternalIdKey().equals(key)) {
- return portExternalIds.getExternalIdValue();
- }
- }
- }
- }
- break;
- default:
- LOG.debug("getExternalId: Couldn't find the specified OvsdbTable: ", table);
- return null;
- }
- return null;
- }
-
- public String getOtherConfig(Node node, OvsdbTables table, String key) {
- switch (table) {
- case BRIDGE:
- OvsdbBridgeAugmentation bridge = extractBridgeAugmentation(node);
- if (bridge != null && bridge.getBridgeOtherConfigs() != null) {
- for (BridgeOtherConfigs bridgeOtherConfigs : bridge.getBridgeOtherConfigs()) {
- if (bridgeOtherConfigs.getBridgeOtherConfigKey().equals(key)) {
- return bridgeOtherConfigs.getBridgeOtherConfigValue();
- }
- }
- }
- break;
- case CONTROLLER:
- LOG.warn("getOtherConfig: There is no other_config for OvsdbTables: ", table);
- return null;
-
- case OPENVSWITCH:
- OvsdbNodeAugmentation ovsdbNode = extractNodeAugmentation(node);
- if (ovsdbNode == null) {
- Node nodeFromReadOvsdbNode = readOvsdbNode(node);
- if (nodeFromReadOvsdbNode != null) {
- ovsdbNode = extractNodeAugmentation(nodeFromReadOvsdbNode);
- }
- }
- if (ovsdbNode != null && ovsdbNode.getOpenvswitchOtherConfigs() != null) {
- for (OpenvswitchOtherConfigs openvswitchOtherConfigs : ovsdbNode.getOpenvswitchOtherConfigs()) {
- if (openvswitchOtherConfigs.getOtherConfigKey().equals(key)) {
- return openvswitchOtherConfigs.getOtherConfigValue();
- }
- }
- }
- break;
- case PORT:
- List <OvsdbTerminationPointAugmentation> ports = extractTerminationPointAugmentations(node);
- for (OvsdbTerminationPointAugmentation port : ports) {
- if (port != null && port.getPortOtherConfigs() != null) {
- for (PortOtherConfigs portOtherConfigs : port.getPortOtherConfigs()) {
- if (portOtherConfigs.getOtherConfigKey().equals(key)) {
- return portOtherConfigs.getOtherConfigValue();
- }
- }
- }
- }
- break;
- default:
- LOG.debug("getOtherConfig: Couldn't find the specified OvsdbTable: ", table);
- return null;
- }
- return null;
- }
-
- public boolean addVlanToTp(long vlan) {
- return false;
- }
-
- public boolean isTunnel(OvsdbTerminationPointAugmentation port) {
- LOG.trace("SouthboundImpl#isTunnel: Interface : {}", port);
-
- if(port.getInterfaceType() == null){
- LOG.warn("No type found for the interface : {}", port);
- return false;
- }
- return MdsalHelper.createOvsdbInterfaceType(
- port.getInterfaceType()).equals(NetworkHandler.NETWORK_TYPE_VXLAN)
- || MdsalHelper.createOvsdbInterfaceType(
- port.getInterfaceType()).equals(NetworkHandler.NETWORK_TYPE_GRE);
- }
-
- public String getOptionsValue(List<Options> options, String key) {
- String value = null;
- for (Options option : options) {
- if (option.getOption().equals(key)) {
- value = option.getValue();
- }
- }
- return value;
- }
-
- public Topology getOvsdbTopology() {
- InstanceIdentifier<Topology> path = InstanceIdentifier
- .create(NetworkTopology.class)
- .child(Topology.class, new TopologyKey(MdsalHelper.OVSDB_TOPOLOGY_ID));
-
- return mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, path);
- }
-
- public Long getOFPort(OvsdbTerminationPointAugmentation port) {
- Long ofPort = 0L;
- if (port.getOfport() != null) {
- ofPort = port.getOfport();
- }
- return ofPort;
- }
-
- public Long getOFPort(Node bridgeNode, String portName) {
- Long ofPort = 0L;
- OvsdbTerminationPointAugmentation port = extractTerminationPointAugmentation(bridgeNode, portName);
- if (port != null) {
- ofPort = getOFPort(port);
- } else {
- TerminationPoint tp = readTerminationPoint(bridgeNode, null, portName);
- if (tp != null) {
- port = tp.getAugmentation(OvsdbTerminationPointAugmentation.class);
- if (port != null) {
- ofPort = getOFPort(port);
- }
- }
- }
- return ofPort;
- }
- public OvsdbBridgeAugmentation getBridgeFromConfig(Node node, String bridge) {
- OvsdbBridgeAugmentation ovsdbBridgeAugmentation = null;
- InstanceIdentifier<Node> bridgeIid =
- MdsalHelper.createInstanceIdentifier(node.getKey(), bridge);
- Node bridgeNode = mdsalUtils.read(LogicalDatastoreType.CONFIGURATION, bridgeIid);
- if (bridgeNode != null) {
- ovsdbBridgeAugmentation = bridgeNode.getAugmentation(OvsdbBridgeAugmentation.class);
- }
- return ovsdbBridgeAugmentation;
- }
-
- @Override
- public Node readConfigBridge(Node node, String name) {
- LOG.trace("readConfigBridge: EntryPoint: Node:{}::BridgeName:{}", node, name);
- Node bridgeNode = null;
- ConnectionInfo connectionInfo = getConnectionInfo(node);
- if (connectionInfo != null) {
- InstanceIdentifier<Node> bridgeIid =
- MdsalHelper.createInstanceIdentifier(node.getKey(), name);
- bridgeNode = mdsalUtils.read(LogicalDatastoreType.CONFIGURATION, bridgeIid);
- LOG.trace("readConfigBridge: bridgeNode:{}", bridgeNode);
- }
- return bridgeNode;
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.impl;
-
-import com.google.common.base.Preconditions;
-
-import java.util.List;
-
-import org.opendaylight.netvirt.openstack.netvirt.ConfigInterface;
-import org.opendaylight.netvirt.openstack.netvirt.api.TenantNetworkManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.VlanConfigurationCache;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronNetworkCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronPortCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.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.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class TenantNetworkManagerImpl implements ConfigInterface, TenantNetworkManager {
- private static final Logger LOG = LoggerFactory.getLogger(TenantNetworkManagerImpl.class);
- private INeutronNetworkCRUD neutronNetworkCache;
- private INeutronPortCRUD neutronPortCache;
- private VlanConfigurationCache vlanConfigurationCache;
- private Southbound southbound;
- private volatile NeutronL3Adapter neutronL3Adapter;
-
- @Override
- public int getInternalVlan(Node node, String networkId) {
- Integer vlan = vlanConfigurationCache.getInternalVlan(node, networkId);
- if (vlan == null) {
- return 0;
- }
- return vlan;
- }
-
- @Override
- public void reclaimInternalVlan(Node node, NeutronNetwork network) {
- int vlan = vlanConfigurationCache.reclaimInternalVlan(node, network.getID());
- if (vlan <= 0) {
- LOG.debug("Unable to get an internalVlan for Network {}", network);
- return;
- }
- LOG.debug("Removed Vlan {} on {}", vlan);
- }
-
- @Override
- public void programInternalVlan(Node node, OvsdbTerminationPointAugmentation tp, NeutronNetwork network) {
- int vlan = vlanConfigurationCache.getInternalVlan(node, network.getID());
- LOG.debug("Programming Vlan {} on {}", vlan, tp);
- if (vlan <= 0) {
- LOG.debug("Unable to get an internalVlan for Network {}", network);
- return;
- }
-
- southbound.addVlanToTp(vlan);
- }
-
- @Override
- public boolean isTenantNetworkPresentInNode(Node node, String segmentationId) {
- String networkId = this.getNetworkId(segmentationId);
- if (networkId == null) {
- LOG.debug("Tenant Network not found with Segmenation-id {}", segmentationId);
- return false;
- }
-
- try {
- // Make sure to get fresh list of termination points, and not use the ones provided in node param!
- List<OvsdbTerminationPointAugmentation> ports = southbound.readTerminationPointAugmentations(node);
-
- for (OvsdbTerminationPointAugmentation port : ports) {
- String ifaceId = southbound.getInterfaceExternalIdsValue(port, Constants.EXTERNAL_ID_INTERFACE_ID);
- if (ifaceId != null && isInterfacePresentInTenantNetwork(ifaceId, networkId)) {
- LOG.debug("Tenant Network {} with Segmentation-id {} is present in Node {} / Interface {}",
- networkId, segmentationId, node, port);
- return true;
- }
- }
- } catch (Exception e) {
- LOG.error("Error while trying to determine if network is present on node", e);
- return false;
- }
-
- LOG.debug("Tenant Network {} with Segmenation-id {} is NOT present in Node {}",
- networkId, segmentationId, node);
-
- return false;
- }
-
- @Override
- public String getNetworkId(String segmentationId) {
- Preconditions.checkNotNull(neutronNetworkCache);
- List <NeutronNetwork> networks = neutronNetworkCache.getAllNetworks();
- for (NeutronNetwork network : networks) {
- if (network.getProviderSegmentationID() != null &&
- network.getProviderSegmentationID().equalsIgnoreCase(segmentationId)) {
- return network.getNetworkUUID();
- }
- }
- for (String networkUuid : neutronL3Adapter.getNetworkCleanupCache().keySet()) {
- NeutronNetwork network = neutronL3Adapter.getNetworkFromCleanupCache(networkUuid);
- if (network.getProviderSegmentationID() != null &&
- network.getProviderSegmentationID().equalsIgnoreCase(segmentationId)) {
- return network.getNetworkUUID();
- }
- }
- return null;
- }
-
- @Override
- public NeutronNetwork getTenantNetwork(OvsdbTerminationPointAugmentation terminationPointAugmentation) {
- Preconditions.checkNotNull(neutronNetworkCache);
- Preconditions.checkNotNull(neutronPortCache);
- NeutronNetwork neutronNetwork = null;
-
- LOG.debug("getTenantNetwork for {}", terminationPointAugmentation);
- String neutronPortId = southbound.getInterfaceExternalIdsValue(terminationPointAugmentation,
- Constants.EXTERNAL_ID_INTERFACE_ID);
- if (neutronPortId != null) {
- NeutronPort neutronPort = neutronL3Adapter.getPortPreferablyFromCleanupCache(neutronPortId);
- if (neutronPort != null) {
- neutronNetwork = neutronNetworkCache.getNetwork(neutronPort.getNetworkUUID());
- if (null == neutronNetwork) {
- neutronNetwork = neutronL3Adapter.getNetworkFromCleanupCache(neutronPort.getNetworkUUID());
- }
- if (neutronNetwork != null) {
- LOG.debug("mapped to {}", neutronNetwork);
- } else {
- LOG.debug("getTenantNetwork: did not find neutronNetwork in cache from neutronPort {}",
- neutronPortId);
- }
- } else {
- LOG.info("getTenantNetwork did not find neutronPort {} from termination point {}",
- neutronPortId, terminationPointAugmentation.getName());
- }
- } else {
- LOG.debug("getTenantNetwork: did not find {} in external_ids", Constants.EXTERNAL_ID_INTERFACE_ID);
- }
- return neutronNetwork;
- }
-
- @Override
- public NeutronPort getTenantPort(OvsdbTerminationPointAugmentation terminationPointAugmentation) {
- Preconditions.checkNotNull(neutronPortCache);
- NeutronPort neutronPort = null;
-
- LOG.trace("getTenantPort for {}", terminationPointAugmentation.getName());
- String neutronPortId = southbound.getInterfaceExternalIdsValue(terminationPointAugmentation,
- Constants.EXTERNAL_ID_INTERFACE_ID);
- if (neutronPortId != null) {
- neutronPort = neutronL3Adapter.getPortPreferablyFromCleanupCache(neutronPortId);
- }
-
- return neutronPort;
- }
-
- @Override
- public int networkCreated (Node node, String networkId) {
- return vlanConfigurationCache.assignInternalVlan(node, networkId);
- }
-
- @Override
- public void networkDeleted(String id) {
- //ToDo: Delete? This method does nothing since container support was dropped...
- }
-
- private boolean isInterfacePresentInTenantNetwork (String portId, String networkId) {
- NeutronPort neutronPort = neutronL3Adapter.getPortPreferablyFromCleanupCache(portId);
- return neutronPort != null && neutronPort.getNetworkUUID().equalsIgnoreCase(networkId);
- }
-
- @Override
- public void setDependencies(ServiceReference serviceReference) {
- vlanConfigurationCache =
- (VlanConfigurationCache) ServiceHelper.getGlobalInstance(VlanConfigurationCache.class, this);
- southbound =
- (Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this);
- neutronL3Adapter =
- (NeutronL3Adapter) ServiceHelper.getGlobalInstance(NeutronL3Adapter.class, this);
- }
-
- @Override
- public void setDependencies(Object impl) {
- if (impl instanceof INeutronNetworkCRUD) {
- neutronNetworkCache = (INeutronNetworkCRUD)impl;
- } else if (impl instanceof INeutronPortCRUD) {
- neutronPortCache = (INeutronPortCRUD)impl;
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 Hewlett-Packard Development Company, L.P. 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.netvirt.openstack.netvirt.impl;
-
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import org.opendaylight.netvirt.openstack.netvirt.ConfigInterface;
-import org.opendaylight.netvirt.openstack.netvirt.NodeConfiguration;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.openstack.netvirt.api.TenantNetworkManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.VlanConfigurationCache;
-import org.opendaylight.netvirt.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.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * @author Dave Tucker
- * @author Sam Hague
- */
-public class VlanConfigurationCacheImpl implements ConfigInterface, VlanConfigurationCache {
- private static final Logger LOG = LoggerFactory.getLogger(VlanConfigurationCacheImpl.class);
- private Map<String, NodeConfiguration> configurationCache = new ConcurrentHashMap<>();
- private volatile TenantNetworkManager tenantNetworkManager;
- private volatile Southbound southbound;
-
- private NodeConfiguration getNodeConfiguration(Node node){
- String nodeUuid = getNodeUUID(node);
- if (configurationCache.get(nodeUuid) != null) {
- return configurationCache.get(nodeUuid);
- }
-
- // Cache miss
- initializeNodeConfiguration(node, nodeUuid);
-
- return configurationCache.get(nodeUuid);
- }
-
- private String getNodeUUID(Node node) {
- return southbound.getOvsdbNodeUUID(node);
- }
-
- private void initializeNodeConfiguration(Node node, String nodeUuid) {
- NodeConfiguration nodeConfiguration = new NodeConfiguration();
- List<OvsdbTerminationPointAugmentation> ports = southbound.getTerminationPointsOfBridge(node);
- for (OvsdbTerminationPointAugmentation port : ports) {
- Integer vlan = port.getVlanTag().getValue();
- String networkId = tenantNetworkManager.getTenantNetwork(port).getNetworkUUID();
- if (vlan != 0 && networkId != null) {
- internalVlanInUse(nodeConfiguration, vlan);
- nodeConfiguration.getTenantVlanMap().put(networkId, vlan);
- } else {
- LOG.debug("Node: {} initialized without a vlan", node);
- }
- }
- configurationCache.put(nodeUuid, nodeConfiguration);
- }
-
- /**
- * Return the currently mapped internal vlan or get the next
- * free internal vlan from the available pool and map it to the networkId.
- */
- @Override
- public Integer assignInternalVlan (Node node, String networkId) {
- NodeConfiguration nodeConfiguration = getNodeConfiguration(node);
- Integer mappedVlan = nodeConfiguration.getTenantVlanMap().get(networkId);
- if (mappedVlan != null) {
- return mappedVlan;
- }
- mappedVlan = nodeConfiguration.getInternalVlans().poll();
- if (mappedVlan != null) {
- nodeConfiguration.getTenantVlanMap().put(networkId, mappedVlan);
- }
- return mappedVlan;
- }
-
- /**
- * Return the mapped internal vlan to the available pool.
- */
- @Override
- public Integer reclaimInternalVlan(Node node, String networkId) {
- NodeConfiguration nodeConfiguration = getNodeConfiguration(node);
- Integer mappedVlan = nodeConfiguration.getTenantVlanMap().get(networkId);
- if (mappedVlan != null) {
- nodeConfiguration.getTenantVlanMap().remove(networkId);
- nodeConfiguration.getInternalVlans().add(mappedVlan);
- return mappedVlan;
- }
- return 0;
- }
-
- private void internalVlanInUse(NodeConfiguration nodeConfiguration, Integer vlan) {
- nodeConfiguration.getInternalVlans().remove(vlan);
- }
-
- @Override
- public Integer getInternalVlan(Node node, String networkId) {
- NodeConfiguration nodeConfiguration = getNodeConfiguration(node);
- Integer vlan = nodeConfiguration.getTenantVlanMap().get(networkId);
- return vlan == null ? 0 : vlan;
- }
-
- @Override
- public void setDependencies(ServiceReference serviceReference) {
- tenantNetworkManager =
- (TenantNetworkManager) ServiceHelper.getGlobalInstance(TenantNetworkManager.class, this);
- southbound =
- (Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this);
- }
-
- @Override
- public void setDependencies(Object impl) {
-
- }
-}
+++ /dev/null
-/*
- * Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator;
-
-/**
- * This class contains behaviour common to Neutron configuration objects
- */
-public interface INeutronObject {
-
- String getID();
-
- void setID(String id);
-}
+++ /dev/null
-/*
- * Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-import java.io.Serializable;
-import java.util.List;
-
-/**
- * OpenStack Neutron v2.0 Firewall as a service
- * (FWaaS) bindings. See OpenStack Network API
- * v2.0 Reference for description of the fields:
- * Implemented fields are as follows:
- *
- * id uuid-str
- * tenant_id uuid-str
- * name String
- * description String
- * admin_state_up Bool
- * status String
- * shared Bool
- * firewall_policy_id uuid-str
- * http://docs.openstack.org/api/openstack-network/2.0/openstack-network.pdf
- *
- */
-
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.NONE)
-
-public class NeutronFirewall implements Serializable, INeutronObject {
- private static final long serialVersionUID = 1L;
-
- @XmlElement(name = "id")
- String firewallUUID;
-
- @XmlElement (name = "tenant_id")
- String firewallTenantID;
-
- @XmlElement (name = "name")
- String firewallName;
-
- @XmlElement (name = "description")
- String firewallDescription;
-
- @XmlElement (defaultValue = "true", name = "admin_state_up")
- Boolean firewallAdminStateIsUp;
-
- @XmlElement (name = "status")
- String firewallStatus;
-
- @XmlElement (defaultValue = "false", name = "shared")
- Boolean firewallIsShared;
-
- @XmlElement (name = "firewall_policy_id")
- String neutronFirewallPolicyID;
-
- public String getID() {
- return firewallUUID;
- }
-
- public void setID(String id) {
- firewallUUID = id;
- }
-
- // @deprecated use getID()
- public String getFirewallUUID() {
- return firewallUUID;
- }
-
- // @deprecated use setID()
- public void setFirewallUUID(String firewallUUID) {
- this.firewallUUID = firewallUUID;
- }
-
- public String getFirewallTenantID() {
- return firewallTenantID;
- }
-
- public void setFirewallTenantID(String firewallTenantID) {
- this.firewallTenantID = firewallTenantID;
- }
-
- public String getFirewallName() {
- return firewallName;
- }
-
- public void setFirewallName(String firewallName) {
- this.firewallName = firewallName;
- }
-
- public String getFirewallDescription() {
- return firewallDescription;
- }
-
- public void setFirewallDescription(String firewallDescription) {
- this.firewallDescription = firewallDescription;
- }
-
- public Boolean getFirewallAdminStateIsUp() {
- return firewallAdminStateIsUp;
- }
-
- public void setFirewallAdminStateIsUp(Boolean firewallAdminStateIsUp) {
- this.firewallAdminStateIsUp = firewallAdminStateIsUp;
- }
-
- public String getFirewallStatus() {
- return firewallStatus;
- }
-
- public void setFirewallStatus(String firewallStatus) {
- this.firewallStatus = firewallStatus;
- }
-
- public Boolean getFirewallIsShared() {
- return firewallIsShared;
- }
-
- public void setFirewallIsShared(Boolean firewallIsShared) {
- this.firewallIsShared = firewallIsShared;
- }
-
- public String getFirewallPolicyID() {
- return neutronFirewallPolicyID;
- }
-
- public void setNeutronFirewallPolicyID(String firewallPolicy) {
- this.neutronFirewallPolicyID = firewallPolicy;
- }
-
- public NeutronFirewall extractFields(List<String> fields) {
- NeutronFirewall ans = new NeutronFirewall();
- for (String s : fields) {
- switch (s) {
- case "id":
- ans.setID(this.getID());
- break;
- case "tenant_id":
- ans.setFirewallTenantID(this.getFirewallTenantID());
- break;
- case "name":
- ans.setFirewallName(this.getFirewallName());
- break;
- case "description":
- ans.setFirewallDescription(this.getFirewallDescription());
- break;
- case "admin_state_up":
- ans.setFirewallAdminStateIsUp(firewallAdminStateIsUp);
- break;
- case "status":
- ans.setFirewallStatus(this.getFirewallStatus());
- break;
- case "shared":
- ans.setFirewallIsShared(firewallIsShared);
- break;
- case "firewall_policy_id":
- ans.setNeutronFirewallPolicyID(this.getFirewallPolicyID());
- break;
- }
- }
- return ans;
- }
-
- @Override
- public String toString() {
- return "NeutronFirewall{" +
- "firewallUUID='" + firewallUUID + '\'' +
- ", firewallTenantID='" + firewallTenantID + '\'' +
- ", firewallName='" + firewallName + '\'' +
- ", firewallDescription='" + firewallDescription + '\'' +
- ", firewallAdminStateIsUp=" + firewallAdminStateIsUp +
- ", firewallStatus='" + firewallStatus + '\'' +
- ", firewallIsShared=" + firewallIsShared +
- ", firewallRulePolicyID=" + neutronFirewallPolicyID +
- '}';
- }
-}
+++ /dev/null
-/*
- * Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * OpenStack Neutron v2.0 Firewall as a service
- * (FWaaS) bindings. See OpenStack Network API
- * v2.0 Reference for description of the fields.
- * The implemented fields are as follows:
- *
- * id uuid-str
- * tenant_id uuid-str
- * name String
- * description String
- * shared Boolean
- * firewall_rules List
- * audited Boolean
- * http://docs.openstack.org/api/openstack-network/2.0/openstack-network.pdf
- *
- */
-
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.NONE)
-
-public class NeutronFirewallPolicy implements Serializable, INeutronObject {
- private static final long serialVersionUID = 1L;
-
- @XmlElement(name = "id")
- String firewallPolicyUUID;
-
- @XmlElement (name = "tenant_id")
- String firewallPolicyTenantID;
-
- @XmlElement (name = "name")
- String firewallPolicyName;
-
- @XmlElement (name = "description")
- String firewallPolicyDescription;
-
- @XmlElement (defaultValue = "false", name = "shared")
- Boolean firewallPolicyIsShared;
-
- @XmlElement (name = "firewall_rules")
- List<String> firewallPolicyRules;
-
- @XmlElement (defaultValue = "false", name = "audited")
- Boolean firewallPolicyIsAudited;
-
- public Boolean getFirewallPolicyIsAudited() {
- return firewallPolicyIsAudited;
- }
-
- public void setFirewallPolicyIsAudited(Boolean firewallPolicyIsAudited) {
- this.firewallPolicyIsAudited = firewallPolicyIsAudited;
- }
-
- public void setFirewallPolicyRules(List<String> firewallPolicyRules) {
- this.firewallPolicyRules = firewallPolicyRules;
- }
-
- public List<String> getFirewallPolicyRules() {
- return firewallPolicyRules;
- }
-
- public Boolean getFirewallPolicyIsShared() {
- return firewallPolicyIsShared;
- }
-
- public void setFirewallPolicyIsShared(Boolean firewallPolicyIsShared) {
- this.firewallPolicyIsShared = firewallPolicyIsShared;
- }
-
- public String getFirewallPolicyDescription() {
- return firewallPolicyDescription;
- }
-
- public void setFirewallPolicyDescription(String firewallPolicyDescription) {
- this.firewallPolicyDescription = firewallPolicyDescription;
- }
-
- public String getFirewallPolicyName() {
- return firewallPolicyName;
- }
-
- public void setFirewallPolicyName(String firewallPolicyName) {
- this.firewallPolicyName = firewallPolicyName;
- }
-
- public String getFirewallPolicyTenantID() {
- return firewallPolicyTenantID;
- }
-
- public void setFirewallPolicyTenantID(String firewallPolicyTenantID) {
- this.firewallPolicyTenantID = firewallPolicyTenantID;
- }
-
- public String getID() {
- return firewallPolicyUUID;
- }
-
- public void setID(String id) {
- firewallPolicyUUID = id;
- }
-
- // @deprecated use getID()
- public String getFirewallPolicyUUID() {
- return firewallPolicyUUID;
- }
-
- // @deprecated use setID()
- public void setFirewallPolicyUUID(String firewallPolicyUUID) {
- this.firewallPolicyUUID = firewallPolicyUUID;
- }
-
- public NeutronFirewallPolicy extractFields(List<String> fields) {
- NeutronFirewallPolicy ans = new NeutronFirewallPolicy();
- for (String s : fields) {
- switch (s) {
- case "id":
- ans.setID(this.getID());
- break;
- case "tenant_id":
- ans.setFirewallPolicyTenantID(this.getFirewallPolicyTenantID());
- break;
- case "name":
- ans.setFirewallPolicyName(this.getFirewallPolicyName());
- break;
- case "description":
- ans.setFirewallPolicyDescription(this.getFirewallPolicyDescription());
- break;
- case "shared":
- ans.setFirewallPolicyIsShared(firewallPolicyIsShared);
- break;
- case "firewall_rules":
- List<String> firewallRuleList = new ArrayList<>();
- firewallRuleList.addAll(this.getFirewallPolicyRules());
- ans.setFirewallPolicyRules(firewallRuleList);
- break;
- case "audited":
- ans.setFirewallPolicyIsAudited(firewallPolicyIsAudited);
- break;
- }
- }
- return ans;
- }
-
- @Override
- public String toString() {
- return "NeutronFirewallPolicy{" +
- "firewallPolicyUUID='" + firewallPolicyUUID + '\'' +
- ", firewallPolicyTenantID='" + firewallPolicyTenantID + '\'' +
- ", firewallPolicyName='" + firewallPolicyName + '\'' +
- ", firewallPolicyDescription='" + firewallPolicyDescription + '\'' +
- ", firewallPolicyIsShared=" + firewallPolicyIsShared +
- ", firewallPolicyRules=" + firewallPolicyRules +
- ", firewallPolicyIsAudited='" + firewallPolicyIsAudited + '\'' +
- '}';
- }
-}
+++ /dev/null
-/*
- * Copyright (C) 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-import java.io.Serializable;
-import java.util.List;
-
-/**
- * OpenStack Neutron v2.0 Firewall as a service
- * (FWaaS) bindings. See OpenStack Network API
- * v2.0 Reference for description of the fields.
- * The implemented fields are as follows:
- *
- * tenant_id uuid-str
- * name String
- * description String
- * admin_state_up Bool
- * status String
- * shared Bool
- * firewall_policy_id uuid-str
- * protocol String
- * ip_version Integer
- * source_ip_address String (IP addr or CIDR)
- * destination_ip_address String (IP addr or CIDR)
- * source_port Integer
- * destination_port Integer
- * position Integer
- * action String
- * enabled Bool
- * id uuid-str
- * http://docs.openstack.org/api/openstack-network/2.0/openstack-network.pdf
- *
- */
-
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.NONE)
-
-public class NeutronFirewallRule implements Serializable, INeutronObject {
- private static final long serialVersionUID = 1L;
-
- @XmlElement(name = "id")
- String firewallRuleUUID;
-
- @XmlElement(name = "tenant_id")
- String firewallRuleTenantID;
-
- @XmlElement(name = "name")
- String firewallRuleName;
-
- @XmlElement(name = "description")
- String firewallRuleDescription;
-
- @XmlElement(name = "status")
- String firewallRuleStatus;
-
- @XmlElement(defaultValue = "false", name = "shared")
- Boolean firewallRuleIsShared;
-
- @XmlElement(name = "firewall_policy_id")
- String firewallRulePolicyID;
-
- @XmlElement(name = "protocol")
- String firewallRuleProtocol;
-
- @XmlElement(name = "ip_version")
- Integer firewallRuleIpVer;
-
- @XmlElement(name = "source_ip_address")
- String firewallRuleSrcIpAddr;
-
- @XmlElement(name = "destination_ip_address")
- String firewallRuleDstIpAddr;
-
- @XmlElement(name = "source_port")
- Integer firewallRuleSrcPort;
-
- @XmlElement(name = "destination_port")
- Integer firewallRuleDstPort;
-
- @XmlElement(name = "position")
- Integer firewallRulePosition;
-
- @XmlElement(name = "action")
- String firewallRuleAction;
-
- @XmlElement(name = "enabled")
- Boolean firewallRuleIsEnabled;
-
- public Boolean getFirewallRuleIsEnabled() {
- return firewallRuleIsEnabled;
- }
-
- public void setFirewallRuleIsEnabled(Boolean firewallRuleIsEnabled) {
- this.firewallRuleIsEnabled = firewallRuleIsEnabled;
- }
-
- public String getFirewallRuleAction() {
- return firewallRuleAction;
- }
-
- public void setFirewallRuleAction(String firewallRuleAction) {
- this.firewallRuleAction = firewallRuleAction;
- }
-
- public Integer getFirewallRulePosition() {
- return firewallRulePosition;
- }
-
- public void setFirewallRulePosition(Integer firewallRulePosition) {
- this.firewallRulePosition = firewallRulePosition;
- }
-
- public Integer getFirewallRuleDstPort() {
- return firewallRuleDstPort;
- }
-
- public void setFirewallRuleDstPort(Integer firewallRuleDstPort) {
- this.firewallRuleDstPort = firewallRuleDstPort;
- }
-
- public Integer getFirewallRuleSrcPort() {
- return firewallRuleSrcPort;
- }
-
- public void setFirewallRuleSrcPort(Integer firewallRuleSrcPort) {
- this.firewallRuleSrcPort = firewallRuleSrcPort;
- }
-
- public String getFirewallRuleDstIpAddr() {
- return firewallRuleDstIpAddr;
- }
-
- public void setFirewallRuleDstIpAddr(String firewallRuleDstIpAddr) {
- this.firewallRuleDstIpAddr = firewallRuleDstIpAddr;
- }
-
- public String getFirewallRuleSrcIpAddr() {
- return firewallRuleSrcIpAddr;
- }
-
- public void setFirewallRuleSrcIpAddr(String firewallRuleSrcIpAddr) {
- this.firewallRuleSrcIpAddr = firewallRuleSrcIpAddr;
- }
-
- public Integer getFirewallRuleIpVer() {
- return firewallRuleIpVer;
- }
-
- public void setFirewallRuleIpVer(Integer firewallRuleIpVer) {
- this.firewallRuleIpVer = firewallRuleIpVer;
- }
-
- public String getFirewallRuleProtocol() {
- return firewallRuleProtocol;
- }
-
- public void setFirewallRuleProtocol(String firewallRuleProtocol) {
- this.firewallRuleProtocol = firewallRuleProtocol;
- }
-
- public String getFirewallRulePolicyID() {
- return firewallRulePolicyID;
- }
-
- public void setFirewallRulesPolicyID(String firewallRulePolicyID) {
- this.firewallRulePolicyID = firewallRulePolicyID;
- }
-
- public Boolean getFirewallRuleIsShared() {
- return firewallRuleIsShared;
- }
-
- public void setFirewallRuleIsShared(Boolean firewallRuleIsShared) {
- this.firewallRuleIsShared = firewallRuleIsShared;
- }
-
- public String getFirewallRuleStatus() {
- return firewallRuleStatus;
- }
-
- public void setFirewallRuleStatus(String firewallRuleStatus) {
- this.firewallRuleStatus = firewallRuleStatus;
- }
-
- public String getFirewallRuleDescription() {
- return firewallRuleDescription;
- }
-
- public void setFirewallRuleDescription(String firewallRuleDescription) {
- this.firewallRuleDescription = firewallRuleDescription;
- }
-
- public String getFirewallRuleName() {
- return firewallRuleName;
- }
-
- public void setFirewallRuleName(String firewallRuleName) {
- this.firewallRuleName = firewallRuleName;
- }
-
- public String getFirewallRuleTenantID() {
- return firewallRuleTenantID;
- }
-
- public void setFirewallRuleTenantID(String firewallRuleTenantID) {
- this.firewallRuleTenantID = firewallRuleTenantID;
- }
-
- public String getID() {
- return firewallRuleUUID;
- }
-
- public void setID(String id) {
- firewallRuleUUID = id;
- }
-
- // @deprecated use getID()
- public String getFirewallRuleUUID() {
- return firewallRuleUUID;
- }
-
- // @deprecated use setID()
- public void setFireWallRuleID(String firewallRuleUUID) {
- this.firewallRuleUUID = firewallRuleUUID;
- }
-
- public NeutronFirewallRule extractFields(List<String> fields) {
- NeutronFirewallRule ans = new NeutronFirewallRule();
- for (String s : fields) {
- switch (s) {
- case "id":
- ans.setID(this.getID());
- break;
- case "tenant_id":
- ans.setFirewallRuleTenantID(this.getFirewallRuleTenantID());
- break;
- case "name":
- ans.setFirewallRuleName(this.getFirewallRuleName());
- break;
- case "description":
- ans.setFirewallRuleDescription(this.getFirewallRuleDescription());
- break;
- case "status":
- ans.setFirewallRuleStatus(this.getFirewallRuleStatus());
- break;
- case "shared":
- ans.setFirewallRuleIsShared(firewallRuleIsShared);
- break;
- case "firewall_policy_id":
- ans.setFirewallRulesPolicyID(this.getFirewallRulePolicyID());
- break;
- case "protocol":
- ans.setFirewallRuleProtocol(this.getFirewallRuleProtocol());
- break;
- case "source_ip_address":
- ans.setFirewallRuleSrcIpAddr(this.getFirewallRuleSrcIpAddr());
- break;
- case "destination_ip_address":
- ans.setFirewallRuleDstIpAddr(this.getFirewallRuleDstIpAddr());
- break;
- case "source_port":
- ans.setFirewallRuleSrcPort(this.getFirewallRuleSrcPort());
- break;
- case "destination_port":
- ans.setFirewallRuleDstPort(this.getFirewallRuleDstPort());
- break;
- case "position":
- ans.setFirewallRulePosition(this.getFirewallRulePosition());
- break;
- case "action":
- ans.setFirewallRuleAction(this.getFirewallRuleAction());
- break;
- case "enabled":
- ans.setFirewallRuleIsEnabled(firewallRuleIsEnabled);
- break;
- }
-
- }
- return ans;
- }
-
- @Override
- public String toString() {
- return "firewallPolicyRules{" +
- "firewallRuleUUID='" + firewallRuleUUID + '\'' +
- ", firewallRuleTenantID='" + firewallRuleTenantID + '\'' +
- ", firewallRuleName='" + firewallRuleName + '\'' +
- ", firewallRuleDescription='" + firewallRuleDescription + '\'' +
- ", firewallRuleStatus='" + firewallRuleStatus + '\'' +
- ", firewallRuleIsShared=" + firewallRuleIsShared +
- ", firewallRulePolicyID=" + firewallRulePolicyID +
- ", firewallRuleProtocol='" + firewallRuleProtocol + '\'' +
- ", firewallRuleIpVer=" + firewallRuleIpVer +
- ", firewallRuleSrcIpAddr='" + firewallRuleSrcIpAddr + '\'' +
- ", firewallRuleDstIpAddr='" + firewallRuleDstIpAddr + '\'' +
- ", firewallRuleSrcPort=" + firewallRuleSrcPort +
- ", firewallRuleDstPort=" + firewallRuleDstPort +
- ", firewallRulePosition=" + firewallRulePosition +
- ", firewallRuleAction='" + firewallRuleAction + '\'' +
- ", firewallRuleIsEnabled=" + firewallRuleIsEnabled +
- '}';
- }
-
- public void initDefaults() {
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 IBM Corporation 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.netvirt.openstack.netvirt.translator;
-
-import java.io.Serializable;
-import java.util.List;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.NONE)
-
-public class NeutronFloatingIP implements Serializable, INeutronObject {
- private static final long serialVersionUID = 1L;
-
- // See OpenStack Network API v2.0 Reference for description of
- // annotated attributes
-
- @XmlElement (name = "id")
- String floatingIPUUID;
-
- @XmlElement (name = "floating_network_id")
- String floatingNetworkUUID;
-
- @XmlElement (name = "port_id")
- String portUUID;
-
- @XmlElement (name = "fixed_ip_address")
- String fixedIPAddress;
-
- @XmlElement (name = "floating_ip_address")
- String floatingIPAddress;
-
- @XmlElement (name = "tenant_id")
- String tenantUUID;
-
- @XmlElement (name="router_id")
- String routerUUID;
-
- @XmlElement (name="status")
- String status;
-
- public NeutronFloatingIP() {
- }
-
- public String getID() {
- return floatingIPUUID;
- }
-
- public void setID(String id) {
- floatingIPUUID = id;
- }
-
- // @deprecated use getID()
- public String getFloatingIPUUID() {
- return floatingIPUUID;
- }
-
- // @deprecated use setID()
- public void setFloatingIPUUID(String floatingIPUUID) {
- this.floatingIPUUID = floatingIPUUID;
- }
-
- public String getFloatingNetworkUUID() {
- return floatingNetworkUUID;
- }
-
- public void setFloatingNetworkUUID(String floatingNetworkUUID) {
- this.floatingNetworkUUID = floatingNetworkUUID;
- }
-
- public String getPortUUID() {
- return portUUID;
- }
-
- public String getRouterUUID() {
- return routerUUID;
- }
-
- public void setPortUUID(String portUUID) {
- this.portUUID = portUUID;
- }
-
- public String getFixedIPAddress() {
- return fixedIPAddress;
- }
-
- public void setFixedIPAddress(String fixedIPAddress) {
- this.fixedIPAddress = fixedIPAddress;
- }
-
- public String getFloatingIPAddress() {
- return floatingIPAddress;
- }
-
- public void setFloatingIPAddress(String floatingIPAddress) {
- this.floatingIPAddress = floatingIPAddress;
- }
-
- public String getTenantUUID() {
- return tenantUUID;
- }
-
- public void setTenantUUID(String tenantUUID) {
- this.tenantUUID = tenantUUID;
- }
-
- public void setRouterUUID(String routerUUID) {
- this.routerUUID = routerUUID;
- }
-
- public String getStatus() {
- return status;
- }
-
- public void setStatus(String status) {
- this.status = status;
- }
-
- /**
- * This method copies selected fields from the object and returns them
- * as a new object, suitable for marshaling.
- *
- * @param fields
- * List of attributes to be extracted
- * @return an OpenStackFloatingIPs object with only the selected fields
- * populated
- */
-
- public NeutronFloatingIP extractFields(List<String> fields) {
- NeutronFloatingIP ans = new NeutronFloatingIP();
- for (String s : fields) {
- switch (s) {
- case "id":
- ans.setID(this.getID());
- break;
- case "floating_network_id":
- ans.setFloatingNetworkUUID(this.getFloatingNetworkUUID());
- break;
- case "port_id":
- ans.setPortUUID(this.getPortUUID());
- break;
- case "fixed_ip_address":
- ans.setFixedIPAddress(this.getFixedIPAddress());
- break;
- case "floating_ip_address":
- ans.setFloatingIPAddress(this.getFloatingIPAddress());
- break;
- case "tenant_id":
- ans.setTenantUUID(this.getTenantUUID());
- break;
- case "router_id":
- ans.setRouterUUID(this.getRouterUUID());
- break;
- case "status":
- ans.setStatus(this.getStatus());
- break;
- }
- }
- return ans;
- }
-
- @Override
- public String toString() {
- return "NeutronFloatingIP{" +
- "fipUUID='" + floatingIPUUID + '\'' +
- ", fipFloatingNetworkId='" + floatingNetworkUUID + '\'' +
- ", fipPortUUID='" + portUUID + '\'' +
- ", fipFixedIPAddress='" + fixedIPAddress + '\'' +
- ", fipFloatingIPAddress=" + floatingIPAddress +
- ", fipTenantId='" + tenantUUID + '\'' +
- ", fipRouterId='" + routerUUID + '\'' +
- ", fipStatus='" + status + '\'' +
- '}';
- }
-
- public void initDefaults() {
- }
-}
+++ /dev/null
-/*
- * Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-import java.io.Serializable;
-import java.util.List;
-
-/**
- * OpenStack Neutron v2.0 Load Balancer as a service
- * (LBaaS) bindings. See OpenStack Network API
- * v2.0 Reference for description of the fields:
- * Implemented fields are as follows:
- *
- * id uuid-str
- * tenant_id uuid-str
- * name String
- * description String
- * status String
- * vip_address IP address
- * vip_subnet uuid-str
- * http://docs.openstack.org/api/openstack-network/2.0/openstack-network.pdf
- */
-
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.NONE)
-
-public class NeutronLoadBalancer implements Serializable, INeutronObject {
- private static final long serialVersionUID = 1L;
-
- @XmlElement(name = "id")
- String loadBalancerID;
-
- @XmlElement (name = "tenant_id")
- String loadBalancerTenantID;
-
- @XmlElement (name = "name")
- String loadBalancerName;
-
- @XmlElement (name = "description")
- String loadBalancerDescription;
-
- @XmlElement (name = "status")
- String loadBalancerStatus;
-
- @XmlElement (name = "admin_state_up")
- Boolean loadBalancerAdminStateUp;
-
- @XmlElement (name = "vip_address")
- String loadBalancerVipAddress;
-
- @XmlElement (name = "vip_subnet_id")
- String loadBalancerVipSubnetID;
-
- public String getID() {
- return loadBalancerID;
- }
-
- public void setID(String id) {
- loadBalancerID = id;
- }
-
- // @deprecated use getID()
- public String getLoadBalancerID() {
- return loadBalancerID;
- }
-
- // @deprecated use setID()
- public void setLoadBalancerID(String loadBalancerID) {
- this.loadBalancerID = loadBalancerID;
- }
-
- public String getLoadBalancerTenantID() {
- return loadBalancerTenantID;
- }
-
- public void setLoadBalancerTenantID(String loadBalancerTenantID) {
- this.loadBalancerTenantID = loadBalancerTenantID;
- }
-
- public String getLoadBalancerName() {
- return loadBalancerName;
- }
-
- public void setLoadBalancerName(String loadBalancerName) {
- this.loadBalancerName = loadBalancerName;
- }
-
- public String getLoadBalancerDescription() {
- return loadBalancerDescription;
- }
-
- public void setLoadBalancerDescription(String loadBalancerDescription) {
- this.loadBalancerDescription = loadBalancerDescription;
- }
-
- public String getLoadBalancerStatus() {
- return loadBalancerStatus;
- }
-
- public void setLoadBalancerStatus(String loadBalancerStatus) {
- this.loadBalancerStatus = loadBalancerStatus;
- }
-
- public Boolean getLoadBalancerAdminStateUp() {
- return loadBalancerAdminStateUp;
- }
-
- public void setLoadBalancerAdminStateUp(Boolean loadBalancerAdminStateUp) {
- this.loadBalancerAdminStateUp = loadBalancerAdminStateUp;
- }
-
- public String getLoadBalancerVipAddress() {
- return loadBalancerVipAddress;
- }
-
- public void setLoadBalancerVipAddress(String loadBalancerVipAddress) {
- this.loadBalancerVipAddress = loadBalancerVipAddress;
- }
-
- public String getLoadBalancerVipSubnetID() {
- return loadBalancerVipSubnetID;
- }
-
- public void setLoadBalancerVipSubnetID(String loadBalancerVipSubnetID) {
- this.loadBalancerVipSubnetID = loadBalancerVipSubnetID;
- }
-
- public NeutronLoadBalancer extractFields(List<String> fields) {
- NeutronLoadBalancer ans = new NeutronLoadBalancer();
- for (String s : fields) {
- switch (s) {
- case "id":
- ans.setID(this.getID());
- break;
- case "tenant_id":
- ans.setLoadBalancerTenantID(this.getLoadBalancerTenantID());
- break;
- case "name":
- ans.setLoadBalancerName(this.getLoadBalancerName());
- break;
- case "description":
- ans.setLoadBalancerDescription(this.getLoadBalancerDescription());
- break;
- case "vip_address":
- ans.setLoadBalancerVipAddress(this.getLoadBalancerVipAddress());
- break;
- case "vip_subnet_id":
- ans.setLoadBalancerVipSubnetID(this.getLoadBalancerVipSubnetID());
- break;
- case "status":
- ans.setLoadBalancerStatus(this.getLoadBalancerStatus());
- break;
- case "admin_state_up":
- ans.setLoadBalancerAdminStateUp(this.getLoadBalancerAdminStateUp());
- break;
- }
- }
- return ans;
- }
-
- @Override public String toString() {
- return "NeutronLoadBalancer{" +
- "loadBalancerID='" + loadBalancerID + '\'' +
- ", loadBalancerTenantID='" + loadBalancerTenantID + '\'' +
- ", loadBalancerName='" + loadBalancerName + '\'' +
- ", loadBalancerDescription='" + loadBalancerDescription + '\'' +
- ", loadBalancerStatus='" + loadBalancerStatus + '\'' +
- ", loadBalancerAdminStateUp='" + loadBalancerAdminStateUp + '\'' +
- ", loadBalancerVipAddress='" + loadBalancerVipAddress + '\'' +
- ", loadBalancerVipSubnetID='" + loadBalancerVipSubnetID + '\'' +
- '}';
- }
-}
+++ /dev/null
-/*
- * Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-import java.io.Serializable;
-import java.util.List;
-
-/**
- * OpenStack Neutron v2.0 Load Balancer as a service
- * (LBaaS) bindings. See OpenStack Network API
- * v2.0 Reference for description of the fields:
- * Implemented fields are as follows:
- *
- *
- * id uuid-str
- * tenant_id uuid-str
- * type String
- * delay Integer
- * timeout Integer
- * max_retries Integer
- * http_method String
- * url_path String
- * expected_codes String
- * admin_state_up Boolean
- * status String
- * http://docs.openstack.org/api/openstack-network/2.0/openstack-network.pdf
- */
-
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.NONE)
-
-public class NeutronLoadBalancerHealthMonitor
- implements Serializable, INeutronObject {
- private static final long serialVersionUID = 1L;
-
- @XmlElement(name = "id")
- String loadBalancerHealthMonitorID;
-
- @XmlElement (name = "tenant_id")
- String loadBalancerHealthMonitorTenantID;
-
- @XmlElement (name = "type")
- String loadBalancerHealthMonitorType;
-
- @XmlElement (name = "delay")
- Integer loadBalancerHealthMonitorDelay;
-
- @XmlElement (name = "timeout")
- Integer loadBalancerHealthMonitorTimeout;
-
- @XmlElement (name = "max_retries")
- Integer loadBalancerHealthMonitorMaxRetries;
-
- @XmlElement (name = "http_method")
- String loadBalancerHealthMonitorHttpMethod;
-
- @XmlElement (name = "url_path")
- String loadBalancerHealthMonitorUrlPath;
-
- @XmlElement (name = "expected_codes")
- String loadBalancerHealthMonitorExpectedCodes;
-
- @XmlElement (defaultValue = "true", name = "admin_state_up")
- Boolean loadBalancerHealthMonitorAdminStateIsUp;
-
- @XmlElement (name = "pools")
- List<Neutron_ID> loadBalancerHealthMonitorPools;
-
- public String getID() {
- return loadBalancerHealthMonitorID;
- }
-
- public void setID(String id) {
- loadBalancerHealthMonitorID = id;
- }
-
- // @deprecated use getID()
- public String getLoadBalancerHealthMonitorID() {
- return loadBalancerHealthMonitorID;
- }
-
- // @deprecated use setID()
- public void setLoadBalancerHealthMonitorID(String loadBalancerHealthMonitorID) {
- this.loadBalancerHealthMonitorID = loadBalancerHealthMonitorID;
- }
-
- public String getLoadBalancerHealthMonitorTenantID() {
- return loadBalancerHealthMonitorTenantID;
- }
-
- public void setLoadBalancerHealthMonitorTenantID(String loadBalancerHealthMonitorTenantID) {
- this.loadBalancerHealthMonitorTenantID = loadBalancerHealthMonitorTenantID;
- }
-
- public String getLoadBalancerHealthMonitorType() {
- return loadBalancerHealthMonitorType;
- }
-
- public void setLoadBalancerHealthMonitorType(String loadBalancerHealthMonitorType) {
- this.loadBalancerHealthMonitorType = loadBalancerHealthMonitorType;
- }
-
- public Integer getLoadBalancerHealthMonitorDelay() {
- return loadBalancerHealthMonitorDelay;
- }
-
- public void setLoadBalancerHealthMonitorDelay(Integer loadBalancerHealthMonitorDelay) {
- this.loadBalancerHealthMonitorDelay = loadBalancerHealthMonitorDelay;
- }
-
- public Integer getLoadBalancerHealthMonitorTimeout() {
- return loadBalancerHealthMonitorTimeout;
- }
-
- public void setLoadBalancerHealthMonitorTimeout(Integer loadBalancerHealthMonitorTimeout) {
- this.loadBalancerHealthMonitorTimeout = loadBalancerHealthMonitorTimeout;
- }
-
- public Integer getLoadBalancerHealthMonitorMaxRetries() {
- return loadBalancerHealthMonitorMaxRetries;
- }
-
- public void setLoadBalancerHealthMonitorMaxRetries(Integer loadBalancerHealthMonitorMaxRetries) {
- this.loadBalancerHealthMonitorMaxRetries = loadBalancerHealthMonitorMaxRetries;
- }
-
- public String getLoadBalancerHealthMonitorHttpMethod() {
- return loadBalancerHealthMonitorHttpMethod;
- }
-
- public void setLoadBalancerHealthMonitorHttpMethod(String loadBalancerHealthMonitorHttpMethod) {
- this.loadBalancerHealthMonitorHttpMethod = loadBalancerHealthMonitorHttpMethod;
- }
-
- public String getLoadBalancerHealthMonitorUrlPath() {
- return loadBalancerHealthMonitorUrlPath;
- }
-
- public void setLoadBalancerHealthMonitorUrlPath(String loadBalancerHealthMonitorUrlPath) {
- this.loadBalancerHealthMonitorUrlPath = loadBalancerHealthMonitorUrlPath;
- }
-
- public String getLoadBalancerHealthMonitorExpectedCodes() {
- return loadBalancerHealthMonitorExpectedCodes;
- }
-
- public void setLoadBalancerHealthMonitorExpectedCodes(String loadBalancerHealthMonitorExpectedCodes) {
- this.loadBalancerHealthMonitorExpectedCodes = loadBalancerHealthMonitorExpectedCodes;
- }
-
- public Boolean getLoadBalancerHealthMonitorAdminStateIsUp() {
- return loadBalancerHealthMonitorAdminStateIsUp;
- }
-
- public void setLoadBalancerHealthMonitorAdminStateIsUp(Boolean loadBalancerHealthMonitorAdminStateIsUp) {
- this.loadBalancerHealthMonitorAdminStateIsUp = loadBalancerHealthMonitorAdminStateIsUp;
- }
-
- public List<Neutron_ID> getLoadBalancerHealthMonitorPools() {
- return loadBalancerHealthMonitorPools;
- }
-
- public void setLoadBalancerHealthMonitorPools(List<Neutron_ID> loadBalancerHealthMonitorPools) {
- this.loadBalancerHealthMonitorPools = loadBalancerHealthMonitorPools;
- }
-
- public NeutronLoadBalancerHealthMonitor extractFields(List<String> fields) {
- NeutronLoadBalancerHealthMonitor ans = new NeutronLoadBalancerHealthMonitor();
- for (String s : fields) {
- switch (s) {
- case "id":
- ans.setID(this.getID());
- break;
- case "tenant_id":
- ans.setLoadBalancerHealthMonitorTenantID(this.getLoadBalancerHealthMonitorTenantID());
- break;
- case "type":
- ans.setLoadBalancerHealthMonitorType(this.getLoadBalancerHealthMonitorType());
- break;
- case "delay":
- ans.setLoadBalancerHealthMonitorDelay(this.getLoadBalancerHealthMonitorDelay());
- break;
- case "timeout":
- ans.setLoadBalancerHealthMonitorTimeout(this.getLoadBalancerHealthMonitorTimeout());
- break;
- case "max_retries":
- ans.setLoadBalancerHealthMonitorMaxRetries(this.getLoadBalancerHealthMonitorMaxRetries());
- break;
- case "http_method":
- ans.setLoadBalancerHealthMonitorHttpMethod(this.getLoadBalancerHealthMonitorHttpMethod());
- break;
- case "url_path":
- ans.setLoadBalancerHealthMonitorUrlPath(this.getLoadBalancerHealthMonitorUrlPath());
- break;
- case "expected_codes":
- ans.setLoadBalancerHealthMonitorExpectedCodes(this.getLoadBalancerHealthMonitorExpectedCodes());
- break;
- case "admin_state_up":
- ans.setLoadBalancerHealthMonitorAdminStateIsUp(loadBalancerHealthMonitorAdminStateIsUp);
- break;
- }
- }
- return ans;
- }
-
- @Override public String toString() {
- return "NeutronLoadBalancerHealthMonitor{" +
- "loadBalancerHealthMonitorID='" + loadBalancerHealthMonitorID + '\'' +
- ", loadBalancerHealthMonitorTenantID='" + loadBalancerHealthMonitorTenantID + '\'' +
- ", loadBalancerHealthMonitorType='" + loadBalancerHealthMonitorType + '\'' +
- ", loadBalancerHealthMonitorDelay=" + loadBalancerHealthMonitorDelay +
- ", loadBalancerHealthMonitorTimeout=" + loadBalancerHealthMonitorTimeout +
- ", loadBalancerHealthMonitorMaxRetries=" + loadBalancerHealthMonitorMaxRetries +
- ", loadBalancerHealthMonitorHttpMethod='" + loadBalancerHealthMonitorHttpMethod + '\'' +
- ", loadBalancerHealthMonitorUrlPath='" + loadBalancerHealthMonitorUrlPath + '\'' +
- ", loadBalancerHealthMonitorExpectedCodes='" + loadBalancerHealthMonitorExpectedCodes + '\'' +
- ", loadBalancerHealthMonitorAdminStateIsUp=" + loadBalancerHealthMonitorAdminStateIsUp +
- '}';
- }
-}
+++ /dev/null
-/*
- * Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-import java.io.Serializable;
-import java.util.List;
-
-/**
- * OpenStack Neutron v2.0 Load Balancer as a service
- * (LBaaS) bindings. See OpenStack Network API
- * v2.0 Reference for description of the fields:
- * Implemented fields are as follows:
- *
- * id uuid-str
- * default_pool_id String
- * tenant_id uuid-str
- * name String
- * description String
- * shared Bool
- * protocol String
- * protocol_port String
- * load_balancer_id String
- * admin_state_up Boolean
- * status String
- *
- * http://docs.openstack.org/api/openstack-network/2.0/openstack-network.pdf
- */
-
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.NONE)
-
-public class NeutronLoadBalancerListener
- implements Serializable, INeutronObject {
- private static final long serialVersionUID = 1L;
-
- @XmlElement(name = "id")
- String loadBalancerListenerID;
-
- @XmlElement (name = "default_pool_id")
- String neutronLoadBalancerListenerDefaultPoolID;
-
- @XmlElement (name = "connection_limit")
- Integer neutronLoadBalancerListenerConnectionLimit;
-
- @XmlElement (name = "tenant_id")
- String loadBalancerListenerTenantID;
-
- @XmlElement (name = "name")
- String loadBalancerListenerName;
-
- @XmlElement (name = "description")
- String loadBalancerListenerDescription;
-
- @XmlElement (defaultValue = "true", name = "admin_state_up")
- Boolean loadBalancerListenerAdminStateIsUp;
-
- @XmlElement (name = "protocol")
- String neutronLoadBalancerListenerProtocol;
-
- @XmlElement (name = "protocol_port")
- String neutronLoadBalancerListenerProtocolPort;
-
- @XmlElement (name = "load_balancers")
- List<Neutron_ID> neutronLoadBalancerListenerLoadBalancerIDs;
-
- public String getID() {
- return loadBalancerListenerID;
- }
-
- public void setID(String id) {
- loadBalancerListenerID = id;
- }
-
- // @deprecated use getID()
- public String getLoadBalancerListenerID() {
- return loadBalancerListenerID;
- }
-
- // @deprecated use setID()
- public void setLoadBalancerListenerID(String loadBalancerListenerID) {
- this.loadBalancerListenerID = loadBalancerListenerID;
- }
-
- public String getLoadBalancerListenerTenantID() {
- return loadBalancerListenerTenantID;
- }
-
- public void setLoadBalancerListenerTenantID(String loadBalancerListenerTenantID) {
- this.loadBalancerListenerTenantID = loadBalancerListenerTenantID;
- }
-
- public String getLoadBalancerListenerName() {
- return loadBalancerListenerName;
- }
-
- public void setLoadBalancerListenerName(String loadBalancerListenerName) {
- this.loadBalancerListenerName = loadBalancerListenerName;
- }
-
- public String getLoadBalancerListenerDescription() {
- return loadBalancerListenerDescription;
- }
-
- public void setLoadBalancerListenerDescription(String loadBalancerListenerDescription) {
- this.loadBalancerListenerDescription = loadBalancerListenerDescription;
- }
-
- public Boolean getLoadBalancerListenerAdminStateIsUp() {
- return loadBalancerListenerAdminStateIsUp;
- }
-
- public void setLoadBalancerListenerAdminStateIsUp(Boolean loadBalancerListenerAdminStateIsUp) {
- this.loadBalancerListenerAdminStateIsUp = loadBalancerListenerAdminStateIsUp;
- }
-
- public String getNeutronLoadBalancerListenerProtocol() {
- return neutronLoadBalancerListenerProtocol;
- }
-
- public void setNeutronLoadBalancerListenerProtocol(String neutronLoadBalancerListenerProtocol) {
- this.neutronLoadBalancerListenerProtocol = neutronLoadBalancerListenerProtocol;
- }
-
- public String getNeutronLoadBalancerListenerProtocolPort() {
- return neutronLoadBalancerListenerProtocolPort;
- }
-
- public void setNeutronLoadBalancerListenerProtocolPort(String neutronLoadBalancerListenerProtocolPort) {
- this.neutronLoadBalancerListenerProtocolPort = neutronLoadBalancerListenerProtocolPort;
- }
-
- public String getNeutronLoadBalancerListenerDefaultPoolID() {
- return neutronLoadBalancerListenerDefaultPoolID;
- }
-
- public void setNeutronLoadBalancerListenerDefaultPoolID(String neutronLoadBalancerListenerDefaultPoolID) {
- this.neutronLoadBalancerListenerDefaultPoolID = neutronLoadBalancerListenerDefaultPoolID;
- }
-
- public Integer getNeutronLoadBalancerListenerConnectionLimit() {
- return neutronLoadBalancerListenerConnectionLimit;
- }
-
- public void setNeutronLoadBalancerListenerConnectionLimit(Integer neutronLoadBalancerListenerConnectionLimit) {
- this.neutronLoadBalancerListenerConnectionLimit = neutronLoadBalancerListenerConnectionLimit;
- }
-
- public List<Neutron_ID> getNeutronLoadBalancerListenerLoadBalancerIDs() {
- return neutronLoadBalancerListenerLoadBalancerIDs;
- }
-
- public void setNeutronLoadBalancerListenerLoadBalancerIDs(List<Neutron_ID> neutronLoadBalancerListenerLoadBalancerIDs) {
- this.neutronLoadBalancerListenerLoadBalancerIDs = neutronLoadBalancerListenerLoadBalancerIDs;
- }
-
- public NeutronLoadBalancerListener extractFields(List<String> fields) {
- NeutronLoadBalancerListener ans = new NeutronLoadBalancerListener();
- for (String s : fields) {
- switch (s) {
- case "id":
- ans.setID(this.getID());
- break;
- case "default_pool_id":
- ans.setNeutronLoadBalancerListenerDefaultPoolID(this.getNeutronLoadBalancerListenerDefaultPoolID());
- break;
- case "tenant_id":
- ans.setLoadBalancerListenerTenantID(this.getLoadBalancerListenerTenantID());
- break;
- case "name":
- ans.setLoadBalancerListenerName(this.getLoadBalancerListenerName());
- break;
- case "description":
- ans.setLoadBalancerListenerDescription(this.getLoadBalancerListenerDescription());
- break;
- case "protocol":
- ans.setNeutronLoadBalancerListenerProtocol(this.getNeutronLoadBalancerListenerProtocol());
- break;
- case "protocol_port":
- ans.setNeutronLoadBalancerListenerProtocolPort(this.getNeutronLoadBalancerListenerProtocolPort());
- break;
- case "admin_state_up":
- ans.setLoadBalancerListenerAdminStateIsUp(loadBalancerListenerAdminStateIsUp);
- break;
- }
- }
- return ans;
- }
-
- @Override public String toString() {
- return "NeutronLoadBalancerListener{" +
- "loadBalancerListenerID='" + loadBalancerListenerID + '\'' +
- ", neutronLoadBalancerListenerDefaultPoolID='" + neutronLoadBalancerListenerDefaultPoolID + '\'' +
- ", neutronLoadBalancerListenerConnectionLimit='" + neutronLoadBalancerListenerConnectionLimit + '\'' +
- ", loadBalancerListenerTenantID='" + loadBalancerListenerTenantID + '\'' +
- ", loadBalancerListenerName='" + loadBalancerListenerName + '\'' +
- ", loadBalancerListenerDescription='" + loadBalancerListenerDescription + '\'' +
- ", loadBalancerListenerAdminStateIsUp=" + loadBalancerListenerAdminStateIsUp +
- ", neutronLoadBalancerListenerProtocol='" + neutronLoadBalancerListenerProtocol + '\'' +
- ", neutronLoadBalancerListenerProtocolPort='" + neutronLoadBalancerListenerProtocolPort + '\'' +
- '}';
- }
-}
+++ /dev/null
-/*
- * Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-import java.io.Serializable;
-import java.util.List;
-
-/**
- * OpenStack Neutron v2.0 Load Balancer as a service
- * (LBaaS) bindings. See OpenStack Network API
- * v2.0 Reference for description of the fields:
- * Implemented fields are as follows:
- *
- * id uuid-str
- * tenant_id uuid-str
- * name String
- * description String
- * protocol String
- * lb_algorithm String
- * healthmonitor_id String
- * admin_state_up Bool
- * status String
- * members List <NeutronLoadBalancerPoolMember>
- * http://docs.openstack.org/api/openstack-network/2.0/openstack-network.pdf
- */
-
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.NONE)
-
-public class NeutronLoadBalancerPool implements Serializable, INeutronObject {
- private static final long serialVersionUID = 1L;
-
- @XmlElement(name = "id")
- String loadBalancerPoolID;
-
- @XmlElement (name = "tenant_id")
- String loadBalancerPoolTenantID;
-
- @XmlElement (name = "name")
- String loadBalancerPoolName;
-
- @XmlElement (name = "description")
- String loadBalancerPoolDescription;
-
- @XmlElement (name = "protocol")
- String loadBalancerPoolProtocol;
-
- @XmlElement (name = "lb_algorithm")
- String loadBalancerPoolLbAlgorithm;
-
- @XmlElement (name = "healthmonitor_id")
- String neutronLoadBalancerPoolHealthMonitorID;
-
- @XmlElement (defaultValue = "true", name = "admin_state_up")
- Boolean loadBalancerPoolAdminStateIsUp;
-
- @XmlElement(name = "listeners")
- List<Neutron_ID> loadBalancerPoolListeners;
-
- @XmlElement(name = "session_persistence")
- NeutronLoadBalancer_SessionPersistence loadBalancerPoolSessionPersistence;
-
- @XmlElement(name = "members")
- List<NeutronLoadBalancerPoolMember> loadBalancerPoolMembers;
-
- public NeutronLoadBalancerPool() {
- }
-
- public String getID() {
- return loadBalancerPoolID;
- }
-
- public void setID(String id) {
- loadBalancerPoolID = id;
- }
-
- // @deprecated use getID()
- public String getLoadBalancerPoolID() {
- return loadBalancerPoolID;
- }
-
- // @deprecated use setID()
- public void setLoadBalancerPoolID(String loadBalancerPoolID) {
- this.loadBalancerPoolID = loadBalancerPoolID;
- }
-
- public String getLoadBalancerPoolTenantID() {
- return loadBalancerPoolTenantID;
- }
-
- public void setLoadBalancerPoolTenantID(String loadBalancerPoolTenantID) {
- this.loadBalancerPoolTenantID = loadBalancerPoolTenantID;
- }
-
- public String getLoadBalancerPoolName() {
- return loadBalancerPoolName;
- }
-
- public void setLoadBalancerPoolName(String loadBalancerPoolName) {
- this.loadBalancerPoolName = loadBalancerPoolName;
- }
-
- public String getLoadBalancerPoolDescription() {
- return loadBalancerPoolDescription;
- }
-
- public void setLoadBalancerPoolDescription(String loadBalancerPoolDescription) {
- this.loadBalancerPoolDescription = loadBalancerPoolDescription;
- }
-
- public String getLoadBalancerPoolProtocol() {
- return loadBalancerPoolProtocol;
- }
-
- public void setLoadBalancerPoolProtocol(String loadBalancerPoolProtocol) {
- this.loadBalancerPoolProtocol = loadBalancerPoolProtocol;
- }
-
- public String getLoadBalancerPoolLbAlgorithm() {
- return loadBalancerPoolLbAlgorithm;
- }
-
- public void setLoadBalancerPoolLbAlgorithm(String loadBalancerPoolLbAlgorithm) {
- this.loadBalancerPoolLbAlgorithm = loadBalancerPoolLbAlgorithm;
- }
-
- public String getNeutronLoadBalancerPoolHealthMonitorID() {
- return neutronLoadBalancerPoolHealthMonitorID;
- }
-
- public void setNeutronLoadBalancerPoolHealthMonitorID(String neutronLoadBalancerPoolHealthMonitorID) {
- this.neutronLoadBalancerPoolHealthMonitorID = neutronLoadBalancerPoolHealthMonitorID;
- }
-
- public Boolean getLoadBalancerPoolAdminIsStateIsUp() {
- return loadBalancerPoolAdminStateIsUp;
- }
-
- public void setLoadBalancerPoolAdminStateIsUp(Boolean loadBalancerPoolAdminStateIsUp) {
- this.loadBalancerPoolAdminStateIsUp = loadBalancerPoolAdminStateIsUp;
- }
-
- public NeutronLoadBalancer_SessionPersistence getLoadBalancerPoolSessionPersistence() {
- return loadBalancerPoolSessionPersistence;
- }
-
- public void setLoadBalancerSessionPersistence(NeutronLoadBalancer_SessionPersistence loadBalancerPoolSessionPersistence) {
- this.loadBalancerPoolSessionPersistence = loadBalancerPoolSessionPersistence;
- }
-
- public List<Neutron_ID> getLoadBalancerPoolListeners() {
- return loadBalancerPoolListeners;
- }
-
- public void setLoadBalancerPoolListeners(List<Neutron_ID> loadBalancerPoolListeners) {
- this.loadBalancerPoolListeners = loadBalancerPoolListeners;
- }
-
- public List<NeutronLoadBalancerPoolMember> getLoadBalancerPoolMembers() {
- /*
- * Update the pool_id of the member to that this.loadBalancerPoolID
- */
- if (loadBalancerPoolMembers != null) {
- for (NeutronLoadBalancerPoolMember member: loadBalancerPoolMembers) {
- member.setPoolID(loadBalancerPoolID);
- }
- return loadBalancerPoolMembers;
- }
- return loadBalancerPoolMembers;
- }
-
- public void setLoadBalancerPoolMembers(List<NeutronLoadBalancerPoolMember> loadBalancerPoolMembers) {
- this.loadBalancerPoolMembers = loadBalancerPoolMembers;
- }
-
- public void addLoadBalancerPoolMember(NeutronLoadBalancerPoolMember loadBalancerPoolMember) {
- this.loadBalancerPoolMembers.add(loadBalancerPoolMember);
- }
-
- public void removeLoadBalancerPoolMember(NeutronLoadBalancerPoolMember loadBalancerPoolMember) {
- this.loadBalancerPoolMembers.remove(loadBalancerPoolMember);
- }
-
- public NeutronLoadBalancerPool extractFields(List<String> fields) {
- NeutronLoadBalancerPool ans = new NeutronLoadBalancerPool();
- for (String s : fields) {
- switch (s) {
- case "id":
- ans.setID(this.getID());
- break;
- case "tenant_id":
- ans.setLoadBalancerPoolTenantID(this.getLoadBalancerPoolTenantID());
- break;
- case "name":
- ans.setLoadBalancerPoolName(this.getLoadBalancerPoolName());
- break;
- case "description":
- ans.setLoadBalancerPoolDescription(this.getLoadBalancerPoolDescription());
- break;
- case "protocol":
- ans.setLoadBalancerPoolProtocol(this.getLoadBalancerPoolProtocol());
- break;
- case "lb_algorithm":
- ans.setLoadBalancerPoolLbAlgorithm(this.getLoadBalancerPoolLbAlgorithm());
- break;
- case "healthmonitor_id":
- ans.setNeutronLoadBalancerPoolHealthMonitorID(this.getNeutronLoadBalancerPoolHealthMonitorID());
- break;
- case "admin_state_up":
- ans.setLoadBalancerPoolAdminStateIsUp(loadBalancerPoolAdminStateIsUp);
- break;
- case "members":
- ans.setLoadBalancerPoolMembers(getLoadBalancerPoolMembers());
- break;
- }
- }
- return ans;
- }
-
- @Override
- public String toString() {
- return "NeutronLoadBalancerPool{" +
- "id='" + loadBalancerPoolID + '\'' +
- ", tenantID='" + loadBalancerPoolTenantID + '\'' +
- ", name='" + loadBalancerPoolName + '\'' +
- ", description='" + loadBalancerPoolDescription + '\'' +
- ", protocol=" + loadBalancerPoolProtocol +'\''+
- ", lbAlgorithm='" + loadBalancerPoolLbAlgorithm + '\'' +
- ", healthmonitorID=" + neutronLoadBalancerPoolHealthMonitorID +
- ", adminStateUp=" + loadBalancerPoolAdminStateIsUp +
-// todo: add loadBalancerPoolMembers as joined string
- '}';
- }
-
-}
+++ /dev/null
-/*
- * Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-import javax.xml.bind.annotation.XmlTransient;
-import java.io.Serializable;
-import java.util.List;
-
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.NONE)
-
-public class NeutronLoadBalancerPoolMember
- implements Serializable, INeutronObject {
-
- private static final long serialVersionUID = 1L;
-
- /**
- * TODO: Plumb into LBaaS Pool. Members are nested underneath Pool CRUD.
- */
- @XmlElement (name = "id")
- String poolMemberID;
-
- @XmlElement (name = "tenant_id")
- String poolMemberTenantID;
-
- @XmlElement (name = "address")
- String poolMemberAddress;
-
- @XmlElement (name = "protocol_port")
- Integer poolMemberProtoPort;
-
- @XmlElement (name = "admin_state_up")
- Boolean poolMemberAdminStateIsUp;
-
- @XmlElement (name = "weight")
- Integer poolMemberWeight;
-
- @XmlElement (name = "subnet_id")
- String poolMemberSubnetID;
-
- String poolID;
-
- public NeutronLoadBalancerPoolMember() {
- }
-
- @XmlTransient
- public String getPoolID() {
- return poolID;
- }
-
- public void setPoolID(String poolID) {
- this.poolID = poolID;
- }
-
- public String getID() {
- return poolMemberID;
- }
-
- public void setID(String id) {
- poolMemberID = id;
- }
-
- // @deprecated use getID()
- public String getPoolMemberID() {
- return poolMemberID;
- }
-
- // @deprecated use setID()
- public void setPoolMemberID(String poolMemberID) {
- this.poolMemberID = poolMemberID;
- }
-
- public String getPoolMemberTenantID() {
- return poolMemberTenantID;
- }
-
- public void setPoolMemberTenantID(String poolMemberTenantID) {
- this.poolMemberTenantID = poolMemberTenantID;
- }
-
- public String getPoolMemberAddress() {
- return poolMemberAddress;
- }
-
- public void setPoolMemberAddress(String poolMemberAddress) {
- this.poolMemberAddress = poolMemberAddress;
- }
-
- public Integer getPoolMemberProtoPort() {
- return poolMemberProtoPort;
- }
-
- public void setPoolMemberProtoPort(Integer poolMemberProtoPort) {
- this.poolMemberProtoPort = poolMemberProtoPort;
- }
-
- public Boolean getPoolMemberAdminStateIsUp() {
- return poolMemberAdminStateIsUp;
- }
-
- public void setPoolMemberAdminStateIsUp(Boolean poolMemberAdminStateIsUp) {
- this.poolMemberAdminStateIsUp = poolMemberAdminStateIsUp;
- }
-
- public Integer getPoolMemberWeight() {
- return poolMemberWeight;
- }
-
- public void setPoolMemberWeight(Integer poolMemberWeight) {
- this.poolMemberWeight = poolMemberWeight;
- }
-
- public String getPoolMemberSubnetID() {
- return poolMemberSubnetID;
- }
-
- public void setPoolMemberSubnetID(String poolMemberSubnetID) {
- this.poolMemberSubnetID = poolMemberSubnetID;
- }
-
- public NeutronLoadBalancerPoolMember extractFields(List<String> fields) {
- NeutronLoadBalancerPoolMember ans = new NeutronLoadBalancerPoolMember();
- for (String s : fields) {
- switch (s) {
- case "id":
- ans.setID(this.getID());
- break;
- case "pool_id":
- ans.setPoolID(this.getPoolID());
- break;
- case "tenant_id":
- ans.setPoolMemberTenantID(this.getPoolMemberTenantID());
- break;
- case "address":
- ans.setPoolMemberAddress(this.getPoolMemberAddress());
- break;
- case "protocol_port":
- ans.setPoolMemberProtoPort(this.getPoolMemberProtoPort());
- break;
- case "admin_state_up":
- ans.setPoolMemberAdminStateIsUp(poolMemberAdminStateIsUp);
- break;
- case "weight":
- ans.setPoolMemberWeight(this.getPoolMemberWeight());
- break;
- case "subnet_id":
- ans.setPoolMemberSubnetID(this.getPoolMemberSubnetID());
- break;
- }
- }
- return ans;
- }
- @Override public String toString() {
- return "NeutronLoadBalancerPoolMember{" +
- "poolMemberID='" + poolMemberID + '\'' +
- ", poolID='" + poolID + '\'' +
- ", poolMemberTenantID='" + poolMemberTenantID + '\'' +
- ", poolMemberAddress='" + poolMemberAddress + '\'' +
- ", poolMemberProtoPort=" + poolMemberProtoPort +
- ", poolMemberAdminStateIsUp=" + poolMemberAdminStateIsUp +
- ", poolMemberWeight=" + poolMemberWeight +
- ", poolMemberSubnetID='" + poolMemberSubnetID + '\'' +
- '}';
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 IBM Corporation 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.netvirt.openstack.netvirt.translator;
-
-import java.io.Serializable;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.NONE)
-public class NeutronLoadBalancer_SessionPersistence implements Serializable {
- private static final long serialVersionUID = 1L;
-
- // See OpenStack Network API v2.0 Reference for description of
- // annotated attributes
-
- @XmlElement(name = "cookie_name")
- String cookieName;
-
- @XmlElement(name = "type")
- String type;
-
- public NeutronLoadBalancer_SessionPersistence() {
- }
-
- public NeutronLoadBalancer_SessionPersistence(String cookieName, String type) {
- this.cookieName = cookieName;
- this.type = type;
- }
-
- public String getCookieName() {
- return cookieName;
- }
-
- public void setCookieName(String cookieName) {
- this.cookieName = cookieName;
- }
-
- public String getType() {
- return type;
- }
-
- public void setType(String type) {
- this.type = type;
- }
-}
-
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 IBM Corporation 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.netvirt.openstack.netvirt.translator;
-
-import java.io.Serializable;
-import java.util.List;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-
-@XmlRootElement(name = "network")
-@XmlAccessorType(XmlAccessType.NONE)
-
-public class NeutronNetwork implements Serializable, INeutronObject {
- // See OpenStack Network API v2.0 Reference for description of
- // annotated attributes
-
- private static final long serialVersionUID = 1L;
-
- @XmlElement (name = "id")
- String networkUUID;
-
- @XmlElement (name = "name")
- String networkName;
-
- @XmlElement (defaultValue = "true", name = "admin_state_up")
- Boolean adminStateUp;
-
- @XmlElement (defaultValue = "false", name = "shared")
- Boolean shared;
-
- @XmlElement (name = "tenant_id")
- String tenantID;
-
- // @XmlElement (defaultValue = "false", name = "router:external")
- @XmlElement (defaultValue="false", namespace="router", name="external")
- Boolean routerExternal;
-
- // @XmlElement (defaultValue = "flat", name = "provider:network_type")
- @XmlElement (namespace="provider", name="network_type")
- String providerNetworkType;
-
- // @XmlElement (name = "provider:physical_network")
- @XmlElement (namespace="provider", name="physical_network")
- String providerPhysicalNetwork;
-
- // @XmlElement (name = "provider:segmentation_id")
- @XmlElement (namespace="provider", name="segmentation_id")
- String providerSegmentationID;
-
- @XmlElement (name = "status")
- String status;
-
- @XmlElement (name="segments")
- List<NeutronNetwork_Segment> segments;
-
- @XmlElement (name="vlan_transparent")
- Boolean vlanTransparent;
-
- @XmlElement (name="mtu")
- Integer mtu;
-
- /* This attribute lists the ports associated with an instance
- * which is needed for determining if that instance can be deleted
- */
-
- public NeutronNetwork() {
- }
-
- public void initDefaults() {
- if (status == null) {
- status = "ACTIVE";
- }
- if (adminStateUp == null) {
- adminStateUp = true;
- }
- if (shared == null) {
- shared = false;
- }
- if (routerExternal == null) {
- routerExternal = false;
- }
- if (providerNetworkType == null) {
- providerNetworkType = "flat";
- }
- }
-
- public String getID() { return networkUUID; }
-
- public void setID(String id) { this.networkUUID = id; }
-
- public String getNetworkUUID() {
- return networkUUID;
- }
-
- public void setNetworkUUID(String networkUUID) {
- this.networkUUID = networkUUID;
- }
-
- public String getNetworkName() {
- return networkName;
- }
-
- public void setNetworkName(String networkName) {
- this.networkName = networkName;
- }
-
- public boolean isAdminStateUp() {
- return adminStateUp;
- }
-
- public Boolean getAdminStateUp() { return adminStateUp; }
-
- public void setAdminStateUp(boolean newValue) {
- adminStateUp = newValue;
- }
-
- public boolean isShared() { return shared; }
-
- public Boolean getShared() { return shared; }
-
- public void setShared(boolean newValue) {
- shared = newValue;
- }
-
- public String getTenantID() {
- return tenantID;
- }
-
- public void setTenantID(String tenantID) {
- this.tenantID = tenantID;
- }
-
- public boolean isRouterExternal() { return routerExternal; }
-
- public Boolean getRouterExternal() { return routerExternal; }
-
- public void setRouterExternal(boolean newValue) {
- routerExternal = newValue;
- }
-
- public String getProviderNetworkType() {
- return providerNetworkType;
- }
-
- public void setProviderNetworkType(String providerNetworkType) {
- this.providerNetworkType = providerNetworkType;
- }
-
- public String getProviderPhysicalNetwork() {
- return providerPhysicalNetwork;
- }
-
- public void setProviderPhysicalNetwork(String providerPhysicalNetwork) {
- this.providerPhysicalNetwork = providerPhysicalNetwork;
- }
-
- public String getProviderSegmentationID() {
- return providerSegmentationID;
- }
-
- public void setProviderSegmentationID(String providerSegmentationID) {
- this.providerSegmentationID = providerSegmentationID;
- }
-
- public String getStatus() {
- return status;
- }
-
- public void setStatus(String status) {
- this.status = status;
- }
-
- public void setSegments(List<NeutronNetwork_Segment> segments) {
- this.segments = segments;
- }
-
- public List<NeutronNetwork_Segment> getSegments() {
- return segments;
- }
-
- public Boolean getVlanTransparent() {
- return vlanTransparent;
- }
-
- public void setVlanTransparent(Boolean input) {
- this.vlanTransparent = input;
- }
-
- public Integer getMtu() {
- return mtu;
- }
-
- public void setMtu(Integer input) {
- mtu = input;
- }
-
- /**
- * This method copies selected fields from the object and returns them
- * as a new object, suitable for marshaling.
- *
- * @param fields
- * List of attributes to be extracted
- * @return an OpenStackNetworks object with only the selected fields
- * populated
- */
-
- public NeutronNetwork extractFields(List<String> fields) {
- NeutronNetwork ans = new NeutronNetwork();
- for (String s : fields) {
- switch (s) {
- case "id":
- ans.setNetworkUUID(this.getNetworkUUID());
- break;
- case "name":
- ans.setNetworkName(this.getNetworkName());
- break;
- case "admin_state_up":
- ans.setAdminStateUp(adminStateUp);
- break;
- case "status":
- ans.setStatus(this.getStatus());
- break;
- case "shared":
- ans.setShared(shared);
- break;
- case "tenant_id":
- ans.setTenantID(this.getTenantID());
- break;
- case "external":
- ans.setRouterExternal(this.getRouterExternal());
- break;
- case "segmentation_id":
- ans.setProviderSegmentationID(this.getProviderSegmentationID());
- break;
- case "physical_network":
- ans.setProviderPhysicalNetwork(this.getProviderPhysicalNetwork());
- break;
- case "network_type":
- ans.setProviderNetworkType(this.getProviderNetworkType());
- break;
- }
- }
- return ans;
- }
-
- @Override
- public String toString() {
- return "NeutronNetwork [networkUUID=" + networkUUID + ", networkName=" + networkName + ", adminStateUp="
- + adminStateUp + ", shared=" + shared + ", tenantID=" + tenantID + ", routerExternal=" + routerExternal
- + ", providerNetworkType=" + providerNetworkType + ", providerPhysicalNetwork="
- + providerPhysicalNetwork + ", providerSegmentationID=" + providerSegmentationID + ", status=" + status
- + ", segments = " + segments + "]";
- }
-}
-
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 IBM Corporation 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.netvirt.openstack.netvirt.translator;
-
-import java.io.Serializable;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-
-@XmlRootElement(name = "network")
-@XmlAccessorType(XmlAccessType.NONE)
-
-public class NeutronNetwork_Segment implements Serializable {
- // See OpenStack Network API v2.0 Reference for description of
- // annotated attributes
-
- private static final long serialVersionUID = 1L;
-
- // @XmlElement (defaultValue="flat", name="provider:network_type")
- @XmlElement (defaultValue="flat", namespace="provider", name="network_type")
- String providerNetworkType;
-
- // @XmlElement (name="provider:physical_network")
- @XmlElement (namespace="provider", name="physical_network")
- String providerPhysicalNetwork;
-
- // @XmlElement (name="provider:segmentation_id")
- @XmlElement (namespace="provider", name="segmentation_id")
- String providerSegmentationID;
-
- public NeutronNetwork_Segment() {
- }
-
- public String getProviderNetworkType() {
- return providerNetworkType;
- }
-
- public void setProviderNetworkType(String providerNetworkType) {
- this.providerNetworkType = providerNetworkType;
- }
-
- public String getProviderPhysicalNetwork() {
- return providerPhysicalNetwork;
- }
-
- public void setProviderPhysicalNetwork(String providerPhysicalNetwork) {
- this.providerPhysicalNetwork = providerPhysicalNetwork;
- }
-
- public String getProviderSegmentationID() {
- return providerSegmentationID;
- }
-
- public void setProviderSegmentationID(String providerSegmentationID) {
- this.providerSegmentationID = providerSegmentationID;
- }
-
- @Override
- public String toString() {
- return "NeutronNetwork_Segment [ " +
- ", providerNetworkType=" + providerNetworkType +
- ", providerPhysicalNetwork=" + providerPhysicalNetwork +
- ", providerSegmentationID=" + providerSegmentationID + "]";
- }
-}
-
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 IBM Corporation 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.netvirt.openstack.netvirt.translator;
-
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-
-
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.NONE)
-
-public class NeutronPort implements Serializable, INeutronObject {
- private static final long serialVersionUID = 1L;
-
- // See OpenStack Network API v2.0 Reference for description of
- // annotated attributes
-
- @XmlElement (name = "id")
- String portUUID;
-
- @XmlElement (name = "network_id")
- String networkUUID;
-
- @XmlElement (name = "name")
- String name;
-
- @XmlElement (defaultValue = "true", name = "admin_state_up")
- Boolean adminStateUp;
-
- @XmlElement (name = "status")
- String status;
-
- @XmlElement (name = "mac_address")
- String macAddress;
-
- @XmlElement (name = "fixed_ips")
- List<Neutron_IPs> fixedIPs;
-
- @XmlElement (name = "device_id")
- String deviceID;
-
- @XmlElement (name = "device_owner")
- String deviceOwner;
-
- @XmlElement (name = "tenant_id")
- String tenantID;
-
- @XmlElement (name = "security_groups")
- List<NeutronSecurityGroup> securityGroups;
-
- @XmlElement (name = "allowed_address_pairs")
- List<NeutronPort_AllowedAddressPairs> allowedAddressPairs;
-
- //@XmlElement (name = "binding:host_id")
- @XmlElement (namespace = "binding", name = "host_id")
- String bindinghostID;
-
- //@XmlElement (name = "binding:vnic_type")
- @XmlElement (namespace = "binding", name = "vnic_type")
- String bindingvnicType;
-
- //@XmlElement (name = "binding:vif_type")
- @XmlElement (namespace = "binding", name = "vif_type")
- String bindingvifType;
-
- //@XmlElement (name = "binding:vif_details")
- @XmlElement (namespace = "binding", name = "vif_details")
- Map<String, String> vifDetails;
-
- @XmlElement (name = "extra_dhcp_opts")
- List<NeutronPort_ExtraDHCPOption> extraDHCPOptions;
-
- //Port security is enabled by default for backward compatibility.
- @XmlElement (defaultValue = "true", name = "port_security_enabled")
- Boolean portSecurityEnabled;
-
-
- NeutronPort originalPort;
-
- public NeutronPort() {
- }
-
- public String getID() { return portUUID; }
-
- public void setID(String id) { this.portUUID = id; }
-
- public String getPortUUID() {
- return portUUID;
- }
-
- public void setPortUUID(String portUUID) {
- this.portUUID = portUUID;
- }
-
- public String getNetworkUUID() {
- return networkUUID;
- }
-
- public void setNetworkUUID(String networkUUID) {
- this.networkUUID = networkUUID;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public boolean isAdminStateUp() {
- if (adminStateUp == null) {
- return true;
- }
- return adminStateUp;
- }
-
- public Boolean getAdminStateUp() { return adminStateUp; }
-
- public void setAdminStateUp(Boolean newValue) {
- adminStateUp = newValue;
- }
-
- public String getStatus() {
- return status;
- }
-
- public void setStatus(String status) {
- this.status = status;
- }
-
- public String getMacAddress() {
- return macAddress;
- }
-
- public void setMacAddress(String macAddress) {
- this.macAddress = macAddress;
- }
-
- public List<Neutron_IPs> getFixedIPs() {
- return fixedIPs;
- }
-
- public void setFixedIPs(List<Neutron_IPs> fixedIPs) {
- this.fixedIPs = fixedIPs;
- }
-
- public String getDeviceID() {
- return deviceID;
- }
-
- public void setDeviceID(String deviceID) {
- this.deviceID = deviceID;
- }
-
- public String getDeviceOwner() {
- return deviceOwner;
- }
-
- public void setDeviceOwner(String deviceOwner) {
- this.deviceOwner = deviceOwner;
- }
-
- public String getTenantID() {
- return tenantID;
- }
-
- public void setTenantID(String tenantID) {
- this.tenantID = tenantID;
- }
-
- public List<NeutronSecurityGroup> getSecurityGroups() {
- return securityGroups;
- }
-
- public void setSecurityGroups(List<NeutronSecurityGroup> securityGroups) {
- this.securityGroups = securityGroups;
- }
-
- public List<NeutronPort_AllowedAddressPairs> getAllowedAddressPairs() {
- return allowedAddressPairs;
- }
-
- public void setAllowedAddressPairs(List<NeutronPort_AllowedAddressPairs> allowedAddressPairs) {
- this.allowedAddressPairs = allowedAddressPairs;
- }
-
- public List<NeutronPort_ExtraDHCPOption> getExtraDHCPOptions() {
- return extraDHCPOptions;
- }
-
- public void setExtraDHCPOptions(List<NeutronPort_ExtraDHCPOption> extraDHCPOptions) {
- this.extraDHCPOptions = extraDHCPOptions;
- }
-
- public Map<String, String> getVIFDetails() {
- return vifDetails;
- }
-
- public void setVIFDetails(Map<String, String> vifDetails) {
- this.vifDetails = vifDetails;
- }
-
- public String getBindinghostID() {
- return bindinghostID;
- }
-
- public void setBindinghostID(String bindinghostID) {
- this.bindinghostID = bindinghostID;
- }
-
- public String getBindingvnicType() {
- return bindingvnicType;
- }
-
- public void setBindingvnicType(String bindingvnicType) {
- this.bindingvnicType = bindingvnicType;
- }
-
- public String getBindingvifType() {
- return bindingvifType;
- }
-
- public void setBindingvifType(String bindingvifType) {
- this.bindingvifType = bindingvifType;
- }
-
- public Boolean getPortSecurityEnabled() {
- if (portSecurityEnabled == null || portSecurityEnabled) {
- // port with device owner of network:xxx is created by
- // neutorn for its internal use. So security group doesn't apply.
- // router interface, dhcp port and floating ip.
- return !(deviceOwner != null && deviceOwner.startsWith("network:"));
- }
- return portSecurityEnabled;
- }
-
- public void setPortSecurityEnabled(Boolean newValue) {
- portSecurityEnabled = newValue;
- }
-
-
- public NeutronPort getOriginalPort() {
- return originalPort;
- }
-
-
- public void setOriginalPort(NeutronPort originalPort) {
- this.originalPort = originalPort;
- }
-
- /**
- * This method copies selected fields from the object and returns them
- * as a new object, suitable for marshaling.
- *
- * @param fields
- * List of attributes to be extracted
- * @return an OpenStackPorts object with only the selected fields
- * populated
- */
-
- public NeutronPort extractFields(List<String> fields) {
- NeutronPort ans = new NeutronPort();
- for (String field: fields) {
- if ("id".equals(field)) {
- ans.setPortUUID(this.getPortUUID());
- }
- if ("network_id".equals(field)) {
- ans.setNetworkUUID(this.getNetworkUUID());
- }
- if ("name".equals(field)) {
- ans.setName(this.getName());
- }
- if ("admin_state_up".equals(field)) {
- ans.setAdminStateUp(this.getAdminStateUp());
- }
- if ("status".equals(field)) {
- ans.setStatus(this.getStatus());
- }
- if ("mac_address".equals(field)) {
- ans.setMacAddress(this.getMacAddress());
- }
- if ("fixed_ips".equals(field)) {
- ans.setFixedIPs(new ArrayList<>(this.getFixedIPs()));
- }
- if ("device_id".equals(field)) {
- ans.setDeviceID(this.getDeviceID());
- }
- if ("device_owner".equals(field)) {
- ans.setDeviceOwner(this.getDeviceOwner());
- }
- if ("tenant_id".equals(field)) {
- ans.setTenantID(this.getTenantID());
- }
- if ("security_groups".equals(field)) {
- ans.setSecurityGroups(new ArrayList<>(this.getSecurityGroups()));
- }
- if ("port_security_enabled".equals(field)) {
- ans.setPortSecurityEnabled(this.getPortSecurityEnabled());
- }
- }
- return ans;
- }
-
- public void initDefaults() {
- adminStateUp = true;
- portSecurityEnabled = true;
- if (status == null) {
- status = "ACTIVE";
- }
- if (fixedIPs == null) {
- fixedIPs = new ArrayList<>();
- }
- }
-
- @Override
- public String toString() {
- return "NeutronPort [portUUID=" + portUUID + ", networkUUID=" + networkUUID + ", name=" + name
- + ", adminStateUp=" + adminStateUp + ", status=" + status + ", macAddress=" + macAddress
- + ", fixedIPs=" + fixedIPs + ", deviceID=" + deviceID + ", deviceOwner=" + deviceOwner + ", tenantID="
- + tenantID + ", securityGroups=" + securityGroups
- + ", bindinghostID=" + bindinghostID + ", bindingvnicType=" + bindingvnicType
- + ", bindingvnicType=" + bindingvnicType + ", portSecurityEnabled=" + portSecurityEnabled +"]";
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 IBM Corporation 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.netvirt.openstack.netvirt.translator;
-
-import java.io.Serializable;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.NONE)
-public class NeutronPort_AllowedAddressPairs implements Serializable {
- private static final long serialVersionUID = 1L;
-
- @XmlElement (name = "port_id")
- String portID;
-
- @XmlElement (name = "mac_address")
- String macAddress;
-
- @XmlElement (name = "ip_address")
- String ipAddress;
-
- public NeutronPort_AllowedAddressPairs() {
- }
-
- public NeutronPort_AllowedAddressPairs(String portID, String macAddress, String ipAddress) {
- this.portID = portID;
- this.macAddress = macAddress;
- this.ipAddress = ipAddress;
- }
-
- public String getPortID() { return(portID); }
-
- public void setPortID(String portID) { this.portID = portID; }
-
- public String getMacAddress() { return(macAddress); }
-
- public void setMacAddress(String macAddress) { this.macAddress = macAddress; }
-
- public String getIpAddress() { return(ipAddress); }
-
- public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 IBM Corporation 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.netvirt.openstack.netvirt.translator;
-
-import java.io.Serializable;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.NONE)
-public class NeutronPort_ExtraDHCPOption implements Serializable {
- private static final long serialVersionUID = 1L;
-
- @XmlElement (name = "opt_value")
- String value;
-
- @XmlElement (name = "opt_name")
- String name;
-
- public NeutronPort_ExtraDHCPOption() {
- }
-
- public NeutronPort_ExtraDHCPOption(String value, String name) {
- this.value = value;
- this.name = name;
- }
-
- public String getValue() { return(value); }
-
- public void setValue(String value) { this.value = value; }
-
- public String getName() { return(name); }
-
- public void setName(String name) { this.name = name; }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 IBM Corporation 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.netvirt.openstack.netvirt.translator;
-
-import java.io.Serializable;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.NONE)
-public class NeutronPort_VIFDetail implements Serializable {
- private static final long serialVersionUID = 1L;
-
- @XmlElement (name = "port_filter")
- Boolean portFilter;
-
- @XmlElement (name = "ovs_hybrid_plug")
- Boolean ovsHybridPlug;
-
- public NeutronPort_VIFDetail() {
- }
-
- public NeutronPort_VIFDetail(Boolean portFilter, Boolean ovsHybridPlug) {
- this.portFilter = portFilter;
- this.ovsHybridPlug = ovsHybridPlug;
- }
-
- public Boolean getPortFilter() { return(portFilter); }
-
- public void setPortFilter(Boolean portFilter) { this.portFilter = portFilter; }
-
- public Boolean getOvsHybridPlug() { return(ovsHybridPlug); }
-
- public void setOvsHybridPlug(Boolean ovsHybridPlug) { this.ovsHybridPlug = ovsHybridPlug; }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 IBM Corporation 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.netvirt.openstack.netvirt.translator;
-
-import java.io.Serializable;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.l3.attributes.Routes;
-
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.NONE)
-
-public class NeutronRouter implements Serializable, INeutronObject {
- private static final long serialVersionUID = 1L;
-
- // See OpenStack Network API v2.0 Reference for description of
- // annotated attributes
- @XmlElement (name = "id")
- String routerUUID;
-
- @XmlElement (name = "name")
- String name;
-
- @XmlElement (defaultValue = "true", name = "admin_state_up")
- Boolean adminStateUp;
-
- @XmlElement (name = "status")
- String status;
-
- @XmlElement (name = "tenant_id")
- String tenantID;
-
- @XmlElement (name = "external_gateway_info", nillable = true)
- NeutronRouter_NetworkReference externalGatewayInfo;
-
- @XmlElement (name = "distributed")
- Boolean distributed;
-
- @XmlElement (name = "gw_port_id", nillable = true)
- String gatewayPortId;
-
- @XmlElement (name = "routes")
- List<Routes> routes;
-
- public String getID() { return routerUUID; }
-
- public void setID(String id) { this.routerUUID = id; }
-
- public String getRouterUUID() {
- return routerUUID;
- }
-
- public void setRouterUUID(String routerUUID) {
- this.routerUUID = routerUUID;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public boolean isAdminStateUp() {
- if (adminStateUp == null) {
- return true;
- }
- return adminStateUp;
- }
-
- public Boolean getAdminStateUp() { return adminStateUp; }
-
- public void setAdminStateUp(Boolean newValue) {
- adminStateUp = newValue;
- }
-
- public String getStatus() {
- return status;
- }
-
- public void setStatus(String status) {
- this.status = status;
- }
-
- public String getTenantID() {
- return tenantID;
- }
-
- public void setTenantID(String tenantID) {
- this.tenantID = tenantID;
- }
-
- public NeutronRouter_NetworkReference getExternalGatewayInfo() {
- return externalGatewayInfo;
- }
-
- public void setExternalGatewayInfo(NeutronRouter_NetworkReference externalGatewayInfo) {
- this.externalGatewayInfo = externalGatewayInfo;
- }
-
- public Boolean getDistributed() {
- return distributed;
- }
-
- public void setDistributed(Boolean distributed) {
- this.distributed = distributed;
- }
-
- public String getGatewayPortId() {
- return gatewayPortId;
- }
-
- public void setGatewayPortId(String gatewayPortId) {
- this.gatewayPortId = gatewayPortId;
- }
-
- public List<Routes> getRoutes() {
- return routes;
- }
-
- public void setRoutes(List<Routes> routes) {
- this.routes = routes;
- }
-
- /**
- * This method copies selected fields from the object and returns them
- * as a new object, suitable for marshaling.
- *
- * @param fields
- * List of attributes to be extracted
- * @return an OpenStackRouters object with only the selected fields
- * populated
- */
- public NeutronRouter extractFields(List<String> fields) {
- NeutronRouter ans = new NeutronRouter();
- for (String s : fields) {
- switch (s) {
- case "id":
- ans.setRouterUUID(this.getRouterUUID());
- break;
- case "name":
- ans.setName(this.getName());
- break;
- case "admin_state_up":
- ans.setAdminStateUp(this.getAdminStateUp());
- break;
- case "status":
- ans.setStatus(this.getStatus());
- break;
- case "tenant_id":
- ans.setTenantID(this.getTenantID());
- break;
- case "external_gateway_info":
- ans.setExternalGatewayInfo(this.getExternalGatewayInfo());
- break;
- case "distributed":
- ans.setDistributed(this.getDistributed());
- break;
- case "gw_port_id":
- ans.setGatewayPortId(this.getGatewayPortId());
- break;
- case "routes":
- ans.setRoutes(this.getRoutes());
- break;
- }
- }
- return ans;
- }
-
- public void initDefaults() {
- adminStateUp = true;
- }
-
- @Override
- public String toString() {
- return "NeutronRouter [" +
- "id=" + routerUUID +
- ", name=" + name +
- ", adminStateUp=" + adminStateUp +
- ", status=" + status +
- ", tenantID=" + tenantID +
- ", external_gateway_info=" + externalGatewayInfo +
- ", distributed=" + distributed +
- ", gw_port_id=" + gatewayPortId +
- ", routes=" + routes +
- "]";
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 IBM Corporation 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.netvirt.openstack.netvirt.translator;
-
-import java.io.Serializable;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.NONE)
-public class NeutronRouter_Interface implements Serializable {
- private static final long serialVersionUID = 1L;
-
- // See OpenStack Network API v2.0 Reference for description of
- // annotated attributes
-
- @XmlElement (name = "subnet_id")
- String subnetUUID;
-
- @XmlElement (name = "port_id")
- String portUUID;
-
- @XmlElement (name = "id")
- String id;
-
- @XmlElement (name = "tenant_id")
- String tenantID;
-
- public NeutronRouter_Interface() {
- }
-
- public NeutronRouter_Interface(String subnetUUID, String portUUID) {
- this.subnetUUID = subnetUUID;
- this.portUUID = portUUID;
- }
-
- public String getSubnetUUID() {
- return subnetUUID;
- }
-
- public void setSubnetUUID(String subnetUUID) {
- this.subnetUUID = subnetUUID;
- }
-
- public String getPortUUID() {
- return portUUID;
- }
-
- public void setPortUUID(String portUUID) {
- this.portUUID = portUUID;
- }
-
- public String getID() {
- return id;
- }
-
- public void setID(String id) {
- this.id = id;
- }
-
- public void setTenantID(String tenantID) {
- this.tenantID = tenantID;
- }
-
- @Override
- public String toString() {
- return "NeutronRouterInterface [" +
- "subnetUUID=" + subnetUUID +
- ", portUUID=" + portUUID +
- ", id=" + id +
- ", tenantID=" + tenantID + "]";
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 IBM Corporation 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.netvirt.openstack.netvirt.translator;
-
-import java.io.Serializable;
-
-import java.util.List;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.NONE)
-
-public class NeutronRouter_NetworkReference implements Serializable {
- private static final long serialVersionUID = 1L;
-
- // See OpenStack Network API v2.0 Reference for description of
- // annotated attributes
-
- @XmlElement(name = "network_id")
- String networkID;
-
- @XmlElement(name = "enable_snat")
- Boolean enableSNAT;
-
- @XmlElement(name = "external_fixed_ips")
- List<Neutron_IPs> externalFixedIPs;
-
- public NeutronRouter_NetworkReference() {
- }
-
- public String getNetworkID() {
- return networkID;
- }
-
- public void setNetworkID(String networkID) {
- this.networkID = networkID;
- }
-
- public Boolean getEnableSNAT() {
- return enableSNAT;
- }
-
- public void setEnableSNAT(Boolean enableSNAT) {
- this.enableSNAT = enableSNAT;
- }
-
- public List<Neutron_IPs> getExternalFixedIPs() {
- return externalFixedIPs;
- }
-
- public void setExternalFixedIPs(List<Neutron_IPs> externalFixedIPs) {
- this.externalFixedIPs = externalFixedIPs;
- }
-
- @Override
- public String toString() {
- return "NeutronRouterNetworkReference [networkID=" + networkID +
- " enableSNAT=" + enableSNAT +
- " externalFixedIPs=" + externalFixedIPs + "]";
- }
-
-}
+++ /dev/null
-/*
- * Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-
-/**
- * OpenStack Neutron v2.0 Security Group bindings.
- * See OpenStack Network API v2.0 Reference for description of
- * annotated attributes. The current fields are as follows:
- * <p>
- * id uuid-str unique ID for the security group.
- * name String name of the security group.
- * description String name of the security group.
- * tenant_id uuid-str Owner of security rule..
- */
-
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.NONE)
-
-public class NeutronSecurityGroup implements Serializable, INeutronObject {
- private static final long serialVersionUID = 1L;
-
- @XmlElement(name = "id")
- String securityGroupUUID;
-
- @XmlElement(name = "name")
- String securityGroupName;
-
- @XmlElement(name = "description")
- String securityGroupDescription;
-
- @XmlElement(name = "tenant_id")
- String securityGroupTenantID;
-
- public NeutronSecurityGroup() {
- }
-
- public String getID() {
- return securityGroupUUID;
- }
-
- public void setID(String id) {
- securityGroupUUID = id;
- }
-
- // @deprecated use getID()
- public String getSecurityGroupUUID() {
- return securityGroupUUID;
- }
-
- // @deprecated use setID()
- public void setSecurityGroupUUID(String securityGroupUUID) {
- this.securityGroupUUID = securityGroupUUID;
- }
-
- public String getSecurityGroupName() {
- return securityGroupName;
- }
-
- public void setSecurityGroupName(String securityGroupName) {
- this.securityGroupName = securityGroupName;
- }
-
- public String getSecurityGroupDescription() {
- return securityGroupDescription;
- }
-
- public void setSecurityGroupDescription(String securityGroupDescription) {
- this.securityGroupDescription = securityGroupDescription;
- }
-
- public String getSecurityGroupTenantID() {
- return securityGroupTenantID;
- }
-
- public void setSecurityGroupTenantID(String securityGroupTenantID) {
- this.securityGroupTenantID = securityGroupTenantID;
- }
-
- public NeutronSecurityGroup extractFields(List<String> fields) {
- NeutronSecurityGroup ans = new NeutronSecurityGroup ();
- for (String s : fields) {
- switch (s) {
- case "id":
- ans.setID(this.getID());
- break;
- case "name":
- ans.setSecurityGroupName(this.getSecurityGroupName());
- break;
- case "description":
- ans.setSecurityGroupDescription(this.getSecurityGroupDescription());
- break;
- case "tenant_id":
- ans.setSecurityGroupTenantID(this.getSecurityGroupTenantID());
- break;
- }
- }
- return ans;
- }
-
- @Override
- public String toString() {
- return "NeutronSecurityGroup{" +
- "securityGroupUUID='" + securityGroupUUID + '\'' +
- ", securityGroupName='" + securityGroupName + '\'' +
- ", securityGroupDescription='" + securityGroupDescription + '\'' +
- ", securityGroupTenantID='" + securityGroupTenantID + '\'' +
- "]";
- }
-
- public void initDefaults() {
- //TODO verify no defaults values are nessecary required.
- }
-}
+++ /dev/null
-/*
- * Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-import java.io.Serializable;
-import java.util.List;
-
-/**
- * See OpenStack Network API v2.0 Reference for description of
- * annotated attributes. The current fields are as follows:
- * <p>
- * id uuid (String) UUID for the security group rule.
- * security_rule_id uuid (String) The security group to associate rule.
- * direction String Direction the VM traffic (ingress/egress).
- * security_group_id The security group to associate rule with.
- * protocol String IP Protocol (icmp, tcp, udp, etc).
- * port_range_min Integer Port at start of range
- * port_range_max Integer Port at end of range
- * ethertype String ethertype in L2 packet (IPv4, IPv6, etc)
- * remote_ip_prefix String (IP cidr) CIDR for address range.
- * remote_group_id uuid-str Source security group to apply to rule.
- * tenant_id uuid-str Owner of security rule. Admin only outside tenant.
- */
-
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.NONE)
-
-public class NeutronSecurityRule implements Serializable, INeutronObject {
- private static final long serialVersionUID = 1L;
-
- @XmlElement(name = "id")
- String securityRuleUUID;
-
- public static final String DIRECTION_EGRESS = "egress";
- public static final String DIRECTION_INGRESS = "ingress";
-
- @XmlElement(name = "direction")
- String securityRuleDirection;
-
- public static final String PROTOCOL_ICMP = "icmp";
- public static final String PROTOCOL_TCP = "tcp";
- public static final String PROTOCOL_UDP = "udp";
- public static final String PROTOCOL_ICMPV6 = "icmpv6";
-
- @XmlElement(name = "protocol")
- String securityRuleProtocol;
-
- @XmlElement(name = "port_range_min")
- Integer securityRulePortMin;
-
- @XmlElement(name = "port_range_max")
- Integer securityRulePortMax;
-
- public static final String ETHERTYPE_IPV4 = "IPv4";
- public static final String ETHERTYPE_IPV6 = "IPv6";
-
- @XmlElement(name = "ethertype")
- String securityRuleEthertype;
-
- @XmlElement(name = "remote_ip_prefix")
- String securityRuleRemoteIpPrefix;
-
- @XmlElement(name = "remote_group_id")
- String securityRemoteGroupID;
-
- @XmlElement(name = "security_group_id")
- String securityRuleGroupID;
-
- @XmlElement(name = "tenant_id")
- String securityRuleTenantID;
-
- public NeutronSecurityRule() {
- }
-
- public String getID() {
- return securityRuleUUID;
- }
-
- public void setID(String id) {
- securityRuleUUID = id;
- }
-
- // @deprecated use getID()
- public String getSecurityRuleUUID() {
- return securityRuleUUID;
- }
-
- // @deprecated use setID()
- public void setSecurityRuleUUID(String securityRuleUUID) {
- this.securityRuleUUID = securityRuleUUID;
- }
-
- public String getSecurityRuleDirection() {
- return securityRuleDirection;
- }
-
- public void setSecurityRuleDirection(String securityRuleDirection) {
- this.securityRuleDirection = securityRuleDirection;
- }
-
- public String getSecurityRuleProtocol() {
- return securityRuleProtocol;
- }
-
- public void setSecurityRuleProtocol(String securityRuleProtocol) {
- this.securityRuleProtocol = securityRuleProtocol;
- }
-
- public Integer getSecurityRulePortMin() {
- return securityRulePortMin;
- }
-
- public void setSecurityRulePortMin(Integer securityRulePortMin) {
- this.securityRulePortMin = securityRulePortMin;
- }
-
- public Integer getSecurityRulePortMax() {
- return securityRulePortMax;
- }
-
- public void setSecurityRulePortMax(Integer securityRulePortMax) {
- this.securityRulePortMax = securityRulePortMax;
- }
-
- public String getSecurityRuleEthertype() {
- return securityRuleEthertype;
- }
-
- public void setSecurityRuleEthertype(String securityRuleEthertype) {
- this.securityRuleEthertype = securityRuleEthertype;
- }
-
- public String getSecurityRuleRemoteIpPrefix() {
- return securityRuleRemoteIpPrefix;
- }
-
- public void setSecurityRuleRemoteIpPrefix(String securityRuleRemoteIpPrefix) {
- this.securityRuleRemoteIpPrefix = securityRuleRemoteIpPrefix;
- }
-
- public String getSecurityRemoteGroupID() {
- return securityRemoteGroupID;
- }
-
- public void setSecurityRemoteGroupID(String securityRemoteGroupID) {
- this.securityRemoteGroupID = securityRemoteGroupID;
- }
-
- public String getSecurityRuleGroupID() {
- return securityRuleGroupID;
- }
-
- public void setSecurityRuleGroupID(String securityRuleGroupID) {
- this.securityRuleGroupID = securityRuleGroupID;
- }
-
- public String getSecurityRuleTenantID() {
- return securityRuleTenantID;
- }
-
- public void setSecurityRuleTenantID(String securityRuleTenantID) {
- this.securityRuleTenantID = securityRuleTenantID;
- }
-
- public NeutronSecurityRule extractFields(List<String> fields) {
- NeutronSecurityRule ans = new NeutronSecurityRule();
- for (String s : fields) {
- switch (s) {
- case "id":
- ans.setID(this.getID());
- break;
- case "direction":
- ans.setSecurityRuleDirection(this.getSecurityRuleDirection());
- break;
- case "protocol":
- ans.setSecurityRuleProtocol(this.getSecurityRuleProtocol());
- break;
- case "port_range_min":
- ans.setSecurityRulePortMin(this.getSecurityRulePortMin());
- break;
- case "port_range_max":
- ans.setSecurityRulePortMax(this.getSecurityRulePortMax());
- break;
- case "ethertype":
- ans.setSecurityRuleEthertype(this.getSecurityRuleEthertype());
- break;
- case "remote_ip_prefix":
- ans.setSecurityRuleRemoteIpPrefix(this.getSecurityRuleRemoteIpPrefix());
- break;
- case "remote_group_id":
- ans.setSecurityRemoteGroupID(this.getSecurityRemoteGroupID());
- break;
- case "security_group_id":
- ans.setSecurityRuleGroupID(this.getSecurityRuleGroupID());
- break;
- case "tenant_id":
- ans.setSecurityRuleTenantID(this.getSecurityRuleTenantID());
- break;
- }
- }
- return ans;
- }
-
- @Override
- public String toString() {
- return "NeutronSecurityRule{" +
- "securityRuleUUID='" + securityRuleUUID + '\'' +
- ", securityRuleDirection='" + securityRuleDirection + '\'' +
- ", securityRuleProtocol='" + securityRuleProtocol + '\'' +
- ", securityRulePortMin=" + securityRulePortMin +
- ", securityRulePortMax=" + securityRulePortMax +
- ", securityRuleEthertype='" + securityRuleEthertype + '\'' +
- ", securityRuleRemoteIpPrefix='" + securityRuleRemoteIpPrefix + '\'' +
- ", securityRemoteGroupID=" + securityRemoteGroupID +
- ", securityRuleGroupID='" + securityRuleGroupID + '\'' +
- ", securityRuleTenantID='" + securityRuleTenantID + '\'' +
- '}';
- }
-
- public void initDefaults() {
- //TODO verify no defaults values are nessecary required.
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 IBM Corporation 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.netvirt.openstack.netvirt.translator;
-
-import java.io.Serializable;
-import java.math.BigInteger;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-
-import org.apache.commons.net.util.SubnetUtils;
-import org.apache.commons.net.util.SubnetUtils.SubnetInfo;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.NeutronCRUDInterfaces;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.NONE)
-
-public class NeutronSubnet implements Serializable, INeutronObject {
- private static final Logger LOGGER = LoggerFactory
- .getLogger(NeutronCRUDInterfaces.class);
-
- private static final long serialVersionUID = 1L;
- private static final int IPV4_VERSION = 4;
- private static final int IPV6_VERSION = 6;
- private static final int IPV6_LENGTH = 128;
- private static final int IPV6_LENGTH_BYTES = 8;
- private static final long IPV6_LSB_MASK = 0x000000FF;
- private static final int IPV6_BYTE_OFFSET = 7;
-
- // See OpenStack Network API v2.0 Reference for description of
- // annotated attributes
-
- @XmlElement (name = "id")
- String subnetUUID;
-
- @XmlElement (name = "network_id")
- String networkUUID;
-
- @XmlElement (name = "name")
- String name;
-
- @XmlElement (defaultValue = "4", name = "ip_version")
- Integer ipVersion;
-
- @XmlElement (name = "cidr")
- String cidr;
-
- @XmlElement (name = "gateway_ip")
- String gatewayIP;
-
- @XmlElement (name = "dns_nameservers")
- List<String> dnsNameservers;
-
- @XmlElement (name = "allocation_pools")
- List<NeutronSubnetIPAllocationPool> allocationPools;
-
- @XmlElement (name = "host_routes")
- List<NeutronSubnet_HostRoute> hostRoutes;
-
- @XmlElement (defaultValue = "true", name = "enable_dhcp")
- Boolean enableDHCP;
-
- @XmlElement (name = "tenant_id")
- String tenantID;
-
- @XmlElement (name = "ipv6_address_mode", nillable = true)
- String ipV6AddressMode;
-
- @XmlElement (name = "ipv6_ra_mode", nillable = true)
- String ipV6RaMode;
-
- /* stores the OpenStackPorts associated with an instance
- * used to determine if that instance can be deleted.
- *
- * @deprecated, will be removed in Boron
- */
-
- List<NeutronPort> myPorts;
-
- public NeutronSubnet() {
- myPorts = new ArrayList<>();
- }
-
- // @deprecated - will be removed in Boron
- public void setPorts(List<NeutronPort> arg) {
- myPorts = arg;
- }
-
- public String getID() { return subnetUUID; }
-
- public void setID(String id) { this.subnetUUID = id; }
-
- public String getSubnetUUID() {
- return subnetUUID;
- }
-
- public void setSubnetUUID(String subnetUUID) {
- this.subnetUUID = subnetUUID;
- }
-
- public String getNetworkUUID() {
- return networkUUID;
- }
-
- public void setNetworkUUID(String networkUUID) {
- this.networkUUID = networkUUID;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public Integer getIpVersion() {
- return ipVersion;
- }
-
- public void setIpVersion(Integer ipVersion) {
- this.ipVersion = ipVersion;
- }
-
- public String getCidr() {
- return cidr;
- }
-
- public void setCidr(String cidr) {
- this.cidr = cidr;
- }
-
- public String getGatewayIP() {
- return gatewayIP;
- }
-
- public void setGatewayIP(String gatewayIP) {
- this.gatewayIP = gatewayIP;
- }
-
- public List<String> getDnsNameservers() {
- return dnsNameservers;
- }
-
- public void setDnsNameservers(List<String> dnsNameservers) {
- this.dnsNameservers = dnsNameservers;
- }
-
- public List<NeutronSubnetIPAllocationPool> getAllocationPools() {
- return allocationPools;
- }
-
- public void setAllocationPools(List<NeutronSubnetIPAllocationPool> allocationPools) {
- this.allocationPools = allocationPools;
- }
-
- public List<NeutronSubnet_HostRoute> getHostRoutes() {
- return hostRoutes;
- }
-
- public void setHostRoutes(List<NeutronSubnet_HostRoute> hostRoutes) {
- this.hostRoutes = hostRoutes;
- }
-
- public boolean isEnableDHCP() {
- if (enableDHCP == null) {
- return true;
- }
- return enableDHCP;
- }
-
- public Boolean getEnableDHCP() { return enableDHCP; }
-
- public void setEnableDHCP(Boolean newValue) {
- enableDHCP = newValue;
- }
-
- public String getTenantID() {
- return tenantID;
- }
-
- public void setTenantID(String tenantID) {
- this.tenantID = tenantID;
- }
-
- public String getIpV6AddressMode() { return ipV6AddressMode; }
-
- public void setIpV6AddressMode(String ipV6AddressMode) { this.ipV6AddressMode = ipV6AddressMode; }
-
- public String getIpV6RaMode() { return ipV6RaMode; }
-
- public void setIpV6RaMode(String ipV6RaMode) { this.ipV6RaMode = ipV6RaMode; }
-
- /**
- * This method copies selected fields from the object and returns them
- * as a new object, suitable for marshaling.
- *
- * @param fields
- * List of attributes to be extracted
- * @return an OpenStackSubnets object with only the selected fields
- * populated
- */
-
- public NeutronSubnet extractFields(List<String> fields) {
- NeutronSubnet ans = new NeutronSubnet();
- for (String s : fields) {
- switch (s) {
- case "id":
- ans.setSubnetUUID(this.getSubnetUUID());
- break;
- case "network_id":
- ans.setNetworkUUID(this.getNetworkUUID());
- break;
- case "name":
- ans.setName(this.getName());
- break;
- case "ip_version":
- ans.setIpVersion(this.getIpVersion());
- break;
- case "cidr":
- ans.setCidr(this.getCidr());
- break;
- case "gateway_ip":
- ans.setGatewayIP(this.getGatewayIP());
- break;
- case "dns_nameservers":
- List<String> nsList = new ArrayList<>();
- nsList.addAll(this.getDnsNameservers());
- ans.setDnsNameservers(nsList);
- break;
- case "allocation_pools":
- List<NeutronSubnetIPAllocationPool> aPools = new ArrayList<>();
- aPools.addAll(this.getAllocationPools());
- ans.setAllocationPools(aPools);
- break;
- case "host_routes":
- List<NeutronSubnet_HostRoute> hRoutes = new ArrayList<>();
- hRoutes.addAll(this.getHostRoutes());
- ans.setHostRoutes(hRoutes);
- break;
- case "enable_dhcp":
- ans.setEnableDHCP(this.getEnableDHCP());
- break;
- case "tenant_id":
- ans.setTenantID(this.getTenantID());
- break;
- case "ipv6_address_mode":
- ans.setIpV6AddressMode(this.getIpV6AddressMode());
- break;
- case "ipv6_ra_mode":
- ans.setIpV6RaMode(this.getIpV6RaMode());
- break;
- }
- }
- return ans;
- }
-
- // @deprecated - will be removed in Boron
- public List<NeutronPort> getPortsInSubnet() {
- return myPorts;
- }
-
- // @deprecated - will be removed in Boron
- public List<NeutronPort> getPortsInSubnet(String ignore) {
- List<NeutronPort> answer = new ArrayList<>();
- for (NeutronPort port : myPorts) {
- if (!port.getDeviceOwner().equalsIgnoreCase(ignore)) {
- answer.add(port);
- }
- }
- return answer;
- }
-
- /* test to see if the cidr address used to define this subnet
- * is a valid network address (an necessary condition when creating
- * a new subnet)
- */
- public boolean isValidCIDR() {
- // fix for Bug 2290 - need to wrap the existing test as
- // IPv4 because SubnetUtils doesn't support IPv6
- if (ipVersion == IPV4_VERSION) {
- try {
- SubnetUtils util = new SubnetUtils(cidr);
- SubnetInfo info = util.getInfo();
- if (!info.getNetworkAddress().equals(info.getAddress())) {
- return false;
- }
- } catch (IllegalArgumentException e) {
- LOGGER.warn("Failure in isValidCIDR()", e);
- return false;
- }
- return true;
- }
- if (ipVersion == IPV6_VERSION) {
- // fix for Bug2290 - this is custom code because no classes
- // with ODL-friendly licenses have been found
- // extract address (in front of /) and length (after /)
- String[] parts = cidr.split("/");
- if (parts.length != 2) {
- return false;
- }
- try {
- int length = Integer.parseInt(parts[1]);
- //TODO?: limit check on length
- // convert to byte array
- byte[] addrBytes = InetAddress.getByName(parts[0]).getAddress();
- int i;
- for (i = length; i < IPV6_LENGTH; i++) {
- if (((((int) addrBytes[i/IPV6_LENGTH_BYTES]) & IPV6_LSB_MASK) & (1 << (IPV6_BYTE_OFFSET-(i%IPV6_LENGTH_BYTES)))) != 0) {
- return(false);
- }
- }
- return(true);
- } catch (UnknownHostException e) {
- LOGGER.warn("Failure in isValidCIDR()", e);
- return(false);
- }
- }
- return false;
- }
-
- /* test to see if the gateway IP specified overlaps with specified
- * allocation pools (an error condition when creating a new subnet
- * or assigning a gateway IP)
- */
- public boolean gatewayIP_Pool_overlap() {
- for (NeutronSubnetIPAllocationPool pool : allocationPools) {
- if (ipVersion == IPV4_VERSION && pool.contains(gatewayIP)) {
- return true;
- }
- if (ipVersion == IPV6_VERSION && pool.containsV6(gatewayIP)) {
- return true;
- }
- }
- return false;
- }
-
- public boolean initDefaults() {
- if (enableDHCP == null) {
- enableDHCP = true;
- }
- if (ipVersion == null) {
- ipVersion = IPV4_VERSION;
- }
- dnsNameservers = new ArrayList<>();
- if (hostRoutes == null) {
- hostRoutes = new ArrayList<>();
- }
- if (allocationPools == null) {
- allocationPools = new ArrayList<>();
- if (ipVersion == IPV4_VERSION) {
- try {
- SubnetUtils util = new SubnetUtils(cidr);
- SubnetInfo info = util.getInfo();
- if (gatewayIP == null || ("").equals(gatewayIP)) {
- gatewayIP = info.getLowAddress();
- }
- if (allocationPools.size() < 1) {
- NeutronSubnetIPAllocationPool source =
- new NeutronSubnetIPAllocationPool(info.getLowAddress(),
- info.getHighAddress());
- allocationPools = source.splitPool(gatewayIP);
- }
- } catch (IllegalArgumentException e) {
- LOGGER.warn("Failure in initDefault()", e);
- return false;
- }
- }
- if (ipVersion == IPV6_VERSION) {
- String[] parts = cidr.split("/");
- if (parts.length != 2) {
- return false;
- }
- try {
- int length = Integer.parseInt(parts[1]);
- BigInteger lowAddress_bi = NeutronSubnetIPAllocationPool.convertV6(parts[0]);
- String lowAddress = NeutronSubnetIPAllocationPool.bigIntegerToIP(lowAddress_bi.add(BigInteger.ONE));
- BigInteger mask = BigInteger.ONE.shiftLeft(length).subtract(BigInteger.ONE);
- String highAddress = NeutronSubnetIPAllocationPool.bigIntegerToIP(lowAddress_bi.add(mask).subtract(BigInteger.ONE));
- if (gatewayIP == null || ("").equals(gatewayIP)) {
- gatewayIP = lowAddress;
- }
- if (allocationPools.size() < 1) {
- NeutronSubnetIPAllocationPool source =
- new NeutronSubnetIPAllocationPool(lowAddress,
- highAddress);
- allocationPools = source.splitPoolV6(gatewayIP);
- }
- } catch (Exception e) {
- LOGGER.warn("Failure in initDefault()", e);
- return false;
- }
- }
- }
- return true;
- }
-
- /* this method tests to see if the supplied IPv4 address
- * is valid for this subnet or not
- */
- public boolean isValidIP(String ipAddress) {
- if (ipVersion == IPV4_VERSION) {
- try {
- SubnetUtils util = new SubnetUtils(cidr);
- SubnetInfo info = util.getInfo();
- return info.isInRange(ipAddress);
- } catch (IllegalArgumentException e) {
- LOGGER.warn("Failure in isValidIP()", e);
- return false;
- }
- }
-
- if (ipVersion == IPV6_VERSION) {
- String[] parts = cidr.split("/");
- try {
- int length = Integer.parseInt(parts[1]);
- byte[] cidrBytes = InetAddress.getByName(parts[0]).getAddress();
- byte[] ipBytes = InetAddress.getByName(ipAddress).getAddress();
- int i;
- for (i = 0; i < length; i++) {
- if (((((int) cidrBytes[i/IPV6_LENGTH_BYTES]) & IPV6_LSB_MASK) & (1 << (IPV6_BYTE_OFFSET-(i%IPV6_LENGTH_BYTES)))) !=
- ((((int) ipBytes[i/IPV6_LENGTH_BYTES]) & IPV6_LSB_MASK) & (1 << (IPV6_BYTE_OFFSET-(i%IPV6_LENGTH_BYTES))))) {
- return(false);
- }
- }
- return(true);
- } catch (UnknownHostException e) {
- LOGGER.warn("Failure in isValidIP()", e);
- return(false);
- }
- }
- return false;
- }
-
- /* method to get the lowest available address of the subnet.
- * go through all the allocation pools and keep the lowest of their
- * low addresses.
- */
- public String getLowAddr() {
- String ans = null;
- for (NeutronSubnetIPAllocationPool pool : allocationPools) {
- if (ans == null) {
- ans = pool.getPoolStart();
- } else {
- if (ipVersion == IPV4_VERSION &&
- NeutronSubnetIPAllocationPool.convert(pool.getPoolStart()) <
- NeutronSubnetIPAllocationPool.convert(ans)) {
- ans = pool.getPoolStart();
- }
- if (ipVersion == IPV6_VERSION &&
- NeutronSubnetIPAllocationPool.convertV6(pool.getPoolStart()).compareTo(
- NeutronSubnetIPAllocationPool.convertV6(ans)) < 0) {
- ans = pool.getPoolStart();
- }
- }
- }
- return ans;
- }
-
- @Override
- public String toString() {
- return "NeutronSubnet [subnetUUID=" + subnetUUID + ", networkUUID=" + networkUUID + ", name=" + name
- + ", ipVersion=" + ipVersion + ", cidr=" + cidr + ", gatewayIP=" + gatewayIP + ", dnsNameservers="
- + dnsNameservers + ", allocationPools=" + allocationPools + ", hostRoutes=" + hostRoutes
- + ", enableDHCP=" + enableDHCP + ", tenantID=" + tenantID
- + ", ipv6AddressMode=" + ipV6AddressMode
- + ", ipv6RaMode=" + ipV6RaMode + "]";
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 IBM Corporation 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.netvirt.openstack.netvirt.translator;
-
-import java.io.Serializable;
-import java.math.BigInteger;
-import java.net.InetAddress;
-import java.net.Inet6Address;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.NONE)
-public class NeutronSubnetIPAllocationPool implements Serializable {
- private static final Logger LOGGER = LoggerFactory
- .getLogger(NeutronSubnetIPAllocationPool.class);
-
- private static final long serialVersionUID = 1L;
-
- private static final int BYTE_LENGTH = 8;
- private static final int IPV4_DOTTED_QUADS = 4;
- private static final int IPV4_DOTTED_QUAD_OFFSET = 3;
- private static final int IPV4_DOTTED_QUAD_MASK = 255;
-
- // See OpenStack Network API v2.0 Reference for description of
- // annotated attributes
-
- @XmlElement(name = "start")
- String poolStart;
-
- @XmlElement(name = "end")
- String poolEnd;
-
- public NeutronSubnetIPAllocationPool() {
- }
-
- public NeutronSubnetIPAllocationPool(String lowAddress, String highAddress) {
- poolStart = lowAddress;
- poolEnd = highAddress;
- }
-
- public String getPoolStart() {
- return poolStart;
- }
-
- public void setPoolStart(String poolStart) {
- this.poolStart = poolStart;
- }
-
- public String getPoolEnd() {
- return poolEnd;
- }
-
- public void setPoolEnd(String poolEnd) {
- this.poolEnd = poolEnd;
- }
-
- /**
- * This method determines if this allocation pool contains the
- * input IPv4 address
- *
- * @param inputString
- * IPv4 address in dotted decimal format
- * @return a boolean on whether the pool contains the address or not
- */
-
- public boolean contains(String inputString) {
- long inputIP = convert(inputString);
- long startIP = convert(poolStart);
- long endIP = convert(poolEnd);
- return (inputIP >= startIP && inputIP <= endIP);
- }
-
- /**
- * This static method converts the supplied IPv4 address to a long
- * integer for comparison
- *
- * @param inputString
- * IPv4 address in dotted decimal format
- * @return high-endian representation of the IPv4 address as a long.
- * This method will return 0 if the input is null.
- */
-
- static long convert(String inputString) {
- long ans = 0;
- if (inputString != null) {
- String[] parts = inputString.split("\\.");
- for (String part: parts) {
- ans <<= BYTE_LENGTH;
- ans |= Integer.parseInt(part);
- }
- }
- return ans;
- }
-
- /**
- * This method determines if this allocation pool contains the
- * input IPv4 address
- *
- * @param inputString
- * IPv4 address in dotted decimal format
- * @return a boolean on whether the pool contains the address or not
- */
-
- public boolean containsV6(String inputString) {
- BigInteger inputIP = convertV6(inputString);
- BigInteger startIP = convertV6(poolStart);
- BigInteger endIP = convertV6(poolEnd);
- return (inputIP.compareTo(startIP) >= 0 && inputIP.compareTo(endIP) <= 0);
- }
-
- /**
- * This static method converts the supplied IPv4 address to a long
- * integer for comparison
- *
- * @param inputString
- * IPv6 address in dotted decimal format
- * @return high-endian representation of the IPv4 address as a BigInteger.
- * This method will return 0 if the input is null.
- */
-
- static BigInteger convertV6(String inputString) {
- if (inputString == null) {
- return BigInteger.ZERO;
- }
- try {
- return new BigInteger(InetAddress.getByName(inputString).getAddress());
- } catch (Exception e) {
- LOGGER.error("convertV6 error", e);
- return BigInteger.ZERO;
- }
- }
-
- /**
- * This static method converts the supplied high-ending long back
- * into a dotted decimal representation of an IPv4 address
- *
- * @param l
- * high-endian representation of the IPv4 address as a long
- * @return IPv4 address in dotted decimal format
- */
- static String longToIP(long input) {
- int part;
- long ipLong = input;
- String[] parts = new String[IPV4_DOTTED_QUADS];
- for (part = 0; part < IPV4_DOTTED_QUADS; part++) {
- parts[IPV4_DOTTED_QUAD_OFFSET-part] = String.valueOf(ipLong & IPV4_DOTTED_QUAD_MASK);
- ipLong >>= BYTE_LENGTH;
- }
- return join(parts,".");
- }
-
- /**
- * This static method converts the supplied high-ending long back
- * into a dotted decimal representation of an IPv4 address
- *
- * @param l
- * high-endian representation of the IPv4 address as a long
- * @return IPv4 address in dotted decimal format
- */
- static String bigIntegerToIP(BigInteger b) {
- try {
- return Inet6Address.getByAddress(b.toByteArray()).getHostAddress();
- } catch (Exception e) {
- LOGGER.error("bigIntegerToIP", e);
- return "ERROR";
- }
- }
-
- /*
- * helper routine used by longToIP
- */
- public static String join(String r[],String separator)
- {
- if (r.length == 0) {
- return "";
- }
- StringBuilder sb = new StringBuilder();
- int i;
- for(i = 0;i < r.length - 1;i++) {
- sb.append(r[i]);
- sb.append(separator);
- }
- return sb.toString() + r[i];
- }
-
- /*
- * This method splits the current instance by removing the supplied
- * parameter.
- *
- * If the parameter is either the low or high address,
- * then that member is adjusted and a list containing just this instance
- * is returned.
- *
- * If the parameter is in the middle of the pool, then
- * create two new instances, one ranging from low to parameter-1
- * the other ranging from parameter+1 to high
- */
- public List<NeutronSubnetIPAllocationPool> splitPool(String ipAddress) {
- List<NeutronSubnetIPAllocationPool> ans = new ArrayList<>();
- long gIP = NeutronSubnetIPAllocationPool.convert(ipAddress);
- long sIP = NeutronSubnetIPAllocationPool.convert(poolStart);
- long eIP = NeutronSubnetIPAllocationPool.convert(poolEnd);
- long i;
- NeutronSubnetIPAllocationPool p = new NeutronSubnetIPAllocationPool();
- boolean poolStarted = false;
- for (i = sIP; i <= eIP; i++) {
- if (i == sIP) {
- if (i != gIP) {
- p.setPoolStart(poolStart);
- poolStarted = true;
- } else {
- //FIX for bug 533
- p.setPoolStart(NeutronSubnetIPAllocationPool.longToIP(i+1));
- }
- }
- if (i == eIP) {
- if (i != gIP) {
- p.setPoolEnd(poolEnd);
- } else {
- p.setPoolEnd(NeutronSubnetIPAllocationPool.longToIP(i-1));
- }
- ans.add(p);
- }
- if (i != sIP && i != eIP) {
- if (i != gIP) {
- if (!poolStarted) {
- p.setPoolStart(NeutronSubnetIPAllocationPool.longToIP(i));
- poolStarted = true;
- }
- } else {
- p.setPoolEnd(NeutronSubnetIPAllocationPool.longToIP(i-1));
- poolStarted = false;
- ans.add(p);
- p = new NeutronSubnetIPAllocationPool();
- // Fix for 2120
- p.setPoolStart(NeutronSubnetIPAllocationPool.longToIP(i+1));
- poolStarted = true;
- }
- }
- }
- return ans;
- }
-
- @Override
- public String toString() {
- return "NeutronSubnetIPAllocationPool [" +
- "start=" + poolStart +
- ", end=" + poolEnd + "]";
- }
-
- /*
- * This method splits the current instance by removing the supplied
- * parameter.
- *
- * If the parameter is either the low or high address,
- * then that member is adjusted and a list containing just this instance
- * is returned.
- new *
- * If the parameter is in the middle of the pool, then
- * create two new instances, one ranging from low to parameter-1
- * the other ranging from parameter+1 to high
- * If the pool is a single address, return null
- */
- public List<NeutronSubnetIPAllocationPool> splitPoolV6(String ipAddress) {
- List<NeutronSubnetIPAllocationPool> ans = new ArrayList<>();
- BigInteger gIP = NeutronSubnetIPAllocationPool.convertV6(ipAddress);
- BigInteger sIP = NeutronSubnetIPAllocationPool.convertV6(poolStart);
- BigInteger eIP = NeutronSubnetIPAllocationPool.convertV6(poolEnd);
- if (gIP.compareTo(sIP) == 0 && gIP.compareTo(eIP) < 0) {
- NeutronSubnetIPAllocationPool p = new NeutronSubnetIPAllocationPool();
- p.setPoolStart(NeutronSubnetIPAllocationPool.bigIntegerToIP(sIP.add(BigInteger.ONE)));
- p.setPoolEnd(poolEnd);
- ans.add(p);
- return(ans);
- }
- if (gIP.compareTo(eIP) == 0 && gIP.compareTo(sIP) > 0) {
- NeutronSubnetIPAllocationPool p = new NeutronSubnetIPAllocationPool();
- p.setPoolStart(poolStart);
- p.setPoolEnd(NeutronSubnetIPAllocationPool.bigIntegerToIP(eIP.subtract(BigInteger.ONE)));
- ans.add(p);
- return(ans);
- }
- if (gIP.compareTo(eIP) < 0 && gIP.compareTo(sIP) > 0) {
- NeutronSubnetIPAllocationPool p = new NeutronSubnetIPAllocationPool();
- p.setPoolStart(poolStart);
- p.setPoolEnd(NeutronSubnetIPAllocationPool.bigIntegerToIP(gIP.subtract(BigInteger.ONE)));
- ans.add(p);
- NeutronSubnetIPAllocationPool p2 = new NeutronSubnetIPAllocationPool();
- p2.setPoolStart(NeutronSubnetIPAllocationPool.bigIntegerToIP(gIP.add(BigInteger.ONE)));
- p2.setPoolEnd(poolEnd);
- ans.add(p2);
- return ans;
- }
- return null;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 IBM Corporation 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.netvirt.openstack.netvirt.translator;
-
-import java.io.Serializable;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.NONE)
-public class NeutronSubnet_HostRoute implements Serializable {
- private static final long serialVersionUID = 1L;
-
- // See OpenStack Network API v2.0 Reference for description of
- // annotated attributes
-
- @XmlElement(name = "destination")
- String destination;
-
- @XmlElement(name = "nexthop")
- String nextHop;
-
- /**
- * HostRoute constructor
- */
- public NeutronSubnet_HostRoute() { }
-
- @Override
- public String toString() {
- return "NeutronSubnetHostRoute [" +
- "destination=" + destination +
- ", nextHop=" + nextHop + "]";
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 IBM Corporation 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.netvirt.openstack.netvirt.translator;
-
-import java.io.Serializable;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-
-
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.NONE)
-public class Neutron_ID implements Serializable {
- private static final long serialVersionUID = 1L;
-
- // See OpenStack Network API v2.0 Reference for description of
- // annotated attributes
-
- @XmlElement(name = "id")
- String uuid;
-
- public Neutron_ID() { }
-
- public Neutron_ID(String uuid) {
- this.uuid = uuid;
- }
-
- public String getID() {
- return uuid;
- }
-
- public void setID(String uuid) {
- this.uuid = uuid;
- }
-
- @Override
- public String toString() {
- return "Neutron_ID{" + "id='" + uuid + '\'' + "}";
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 IBM Corporation 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.netvirt.openstack.netvirt.translator;
-
-import java.io.Serializable;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-
-
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.NONE)
-public class Neutron_IPs implements Serializable {
- private static final long serialVersionUID = 1L;
-
- // See OpenStack Network API v2.0 Reference for description of
- // annotated attributes
-
- @XmlElement(name = "ip_address")
- String ipAddress;
-
- @XmlElement(name = "subnet_id")
- String subnetUUID;
-
- public Neutron_IPs() { }
-
- public Neutron_IPs(String uuid) {
- subnetUUID = uuid;
- }
-
- public String getIpAddress() {
- return ipAddress;
- }
-
- public void setIpAddress(String ipAddress) {
- this.ipAddress = ipAddress;
- }
-
- public String getSubnetUUID() {
- return subnetUUID;
- }
-
- public void setSubnetUUID(String subnetUUID) {
- this.subnetUUID = subnetUUID;
- }
-
- @Override
- public String toString() {
- return "Neutron_IPs{" +
- "ipAddress='" + ipAddress + '\'' +
- ", subnetUUID='" + subnetUUID + '\'' + "}";
- }
-}
+++ /dev/null
-/*
- * Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.crud;
-
-import java.util.List;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronFirewall;
-
-/**
- * This interface defines the methods for CRUD of NB OpenStack Firewall objects
- */
-
-public interface INeutronFirewallCRUD {
- /**
- * Applications call this interface method to determine if a particular
- *Firewall object exists
- *
- * @param uuid
- * UUID of the Firewall object
- * @return boolean
- */
-
- boolean neutronFirewallExists(String uuid);
-
- /**
- * Applications call this interface method to return if a particular
- * Firewall object exists
- *
- * @param uuid
- * UUID of the Firewall object
- * @return {@link NeutronFirewall}
- * OpenStackFirewall class
- */
-
- NeutronFirewall getNeutronFirewall(String uuid);
-
- /**
- * Applications call this interface method to return all Firewall objects
- *
- * @return List of OpenStackNetworks objects
- */
-
- List<NeutronFirewall> getAllNeutronFirewalls();
-
- /**
- * Applications call this interface method to add a Firewall object to the
- * concurrent map
- *
- * @param input
- * OpenStackNetwork object
- * @return boolean on whether the object was added or not
- */
-
- boolean addNeutronFirewall(NeutronFirewall input);
-
- /**
- * Applications call this interface method to remove a Neutron Firewall object to the
- * concurrent map
- *
- * @param uuid
- * identifier for the Firewall object
- * @return boolean on whether the object was removed or not
- */
-
- boolean removeNeutronFirewall(String uuid);
-
- /**
- * Applications call this interface method to edit a Firewall object
- *
- * @param uuid
- * identifier of the Firewall object
- * @param delta
- * OpenStackFirewall object containing changes to apply
- * @return boolean on whether the object was updated or not
- */
-
- boolean updateNeutronFirewall(String uuid, NeutronFirewall delta);
-
- /**
- * Applications call this interface method to see if a MAC address is in use
- *
- * @param uuid
- * identifier of the Firewall object
- * @return boolean on whether the macAddress is already associated with a
- * port or not
- */
-
- boolean neutronFirewallInUse(String uuid);
-
-}
+++ /dev/null
-/*
- * Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.crud;
-
-import java.util.List;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronFirewallPolicy;
-
-/**
- * This interface defines the methods for CRUD of NB OpenStack Firewall Policy objects
- *
- */
-
-public interface INeutronFirewallPolicyCRUD {
- /**
- * Applications call this interface method to determine if a particular
- *FirewallPolicy object exists
- *
- * @param uuid
- * UUID of the Firewall Policy object
- * @return boolean
- */
-
- boolean neutronFirewallPolicyExists(String uuid);
-
- /**
- * Applications call this interface method to return if a particular
- * FirewallPolicy object exists
- *
- * @param uuid
- * UUID of the Firewall Policy object
- * @return {@link NeutronFirewallPolicy}
- * OpenStackFirewallPolicy class
- */
-
- NeutronFirewallPolicy getNeutronFirewallPolicy(String uuid);
-
- /**
- * Applications call this interface method to return all Firewall Policy objects
- *
- * @return List of OpenStack Firewall Policy objects
- */
-
- List<NeutronFirewallPolicy> getAllNeutronFirewallPolicies();
-
- /**
- * Applications call this interface method to add a Firewall Policy object to the
- * concurrent map
- *
- * @param input
- * OpenStackNetwork object
- * @return boolean on whether the object was added or not
- */
-
- boolean addNeutronFirewallPolicy(NeutronFirewallPolicy input);
-
- /**
- * Applications call this interface method to remove a Neutron FirewallPolicy object to the
- * concurrent map
- *
- * @param uuid
- * identifier for the Firewall Policy object
- * @return boolean on whether the object was removed or not
- */
-
- boolean removeNeutronFirewallPolicy(String uuid);
-
- /**
- * Applications call this interface method to edit a FirewallPolicy object
- *
- * @param uuid
- * identifier of the Firewall Policy object
- * @param delta
- * OpenStackFirewallPolicy object containing changes to apply
- * @return boolean on whether the object was updated or not
- */
-
- boolean updateNeutronFirewallPolicy(String uuid, NeutronFirewallPolicy delta);
-
- /**
- * Applications call this interface method to see if a MAC address is in use
- *
- * @param uuid
- * identifier of the Firewall Policy object
- * @return boolean on whether the macAddress is already associated with a
- * port or not
- */
-
- boolean neutronFirewallPolicyInUse(String uuid);
-
-}
+++ /dev/null
-/*
- * Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.crud;
-
-import java.util.List;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronFirewallRule;
-
-/**
- * This interface defines the methods for CRUD of NB OpenStack Firewall Rule objects
- *
- */
-
-public interface INeutronFirewallRuleCRUD {
- /**
- * Applications call this interface method to determine if a particular
- *FirewallRule object exists
- *
- * @param uuid
- * UUID of the Firewall Rule object
- * @return boolean
- */
-
- boolean neutronFirewallRuleExists(String uuid);
-
- /**
- * Applications call this interface method to return if a particular
- * FirewallRule object exists
- *
- * @param uuid
- * UUID of the Firewall Rule object
- * @return {@link NeutronFirewallRule}
- * OpenStackFirewall Rule class
- */
-
- NeutronFirewallRule getNeutronFirewallRule(String uuid);
-
- /**
- * Applications call this interface method to return all Firewall Rule objects
- *
- * @return List of OpenStackNetworks objects
- */
-
- List<NeutronFirewallRule> getAllNeutronFirewallRules();
-
- /**
- * Applications call this interface method to add a Firewall Rule object to the
- * concurrent map
- *
- * @param input
- * OpenStackNetwork object
- * @return boolean on whether the object was added or not
- */
-
- boolean addNeutronFirewallRule(NeutronFirewallRule input);
-
- /**
- * Applications call this interface method to remove a Neutron FirewallRule object to the
- * concurrent map
- *
- * @param uuid
- * identifier for the Firewall Rule object
- * @return boolean on whether the object was removed or not
- */
-
- boolean removeNeutronFirewallRule(String uuid);
-
- /**
- * Applications call this interface method to edit a FirewallRule object
- *
- * @param uuid
- * identifier of the Firewall Rule object
- * @param delta
- * OpenStackFirewallRule object containing changes to apply
- * @return boolean on whether the object was updated or not
- */
-
- boolean updateNeutronFirewallRule(String uuid, NeutronFirewallRule delta);
-
- /**
- * Applications call this interface method to see if a MAC address is in use
- *
- * @param uuid
- * identifier of the Firewall Rule object
- * @return boolean on whether the macAddress is already associated with a
- * port or not
- */
-
- boolean neutronFirewallRuleInUse(String uuid);
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 IBM Corporation 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.netvirt.openstack.netvirt.translator.crud;
-
-import java.util.List;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronFloatingIP;
-
-/**
- * This interface defines the methods for CRUD of NB FloatingIP objects
- *
- */
-
-public interface INeutronFloatingIPCRUD {
- /**
- * Applications call this interface method to determine if a particular
- * FloatingIP object exists
- *
- * @param uuid
- * UUID of the FloatingIP object
- * @return boolean
- */
-
- boolean floatingIPExists(String uuid);
-
- /**
- * Applications call this interface method to return if a particular
- * FloatingIP object exists
- *
- * @param uuid
- * UUID of the FloatingIP object
- * @return {@link NeutronFloatingIP}
- * OpenStack FloatingIP class
- */
-
- NeutronFloatingIP getFloatingIP(String uuid);
-
- /**
- * Applications call this interface method to return all FloatingIP objects
- *
- * @return a Set of OpenStackFloatingIPs objects
- */
-
- List<NeutronFloatingIP> getAllFloatingIPs();
-
- /**
- * Applications call this interface method to add a FloatingIP object to the
- * concurrent map
- *
- * @param input
- * OpenStackFloatingIP object
- * @return boolean on whether the object was added or not
- */
-
- boolean addFloatingIP(NeutronFloatingIP input);
-
- /**
- * Applications call this interface method to remove a FloatingIP object to the
- * concurrent map
- *
- * @param uuid
- * identifier for the FloatingIP object
- * @return boolean on whether the object was removed or not
- */
-
- boolean removeFloatingIP(String uuid);
-
- /**
- * Applications call this interface method to edit a FloatingIP object
- *
- * @param uuid
- * identifier of the FloatingIP object
- * @param delta
- * OpenStackFloatingIP object containing changes to apply
- * @return boolean on whether the object was updated or not
- */
-
- boolean updateFloatingIP(String uuid, NeutronFloatingIP delta);
-}
+++ /dev/null
-/*
- * Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.crud;
-
-import java.util.List;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancer;
-
-/**
- * This interface defines the methods for CRUD of NB OpenStack LoadBalancer objects
- *
- */
-
-public interface INeutronLoadBalancerCRUD {
- /**
- * Applications call this interface method to determine if a particular
- *LoadBalancer object exists
- *
- * @param uuid
- * UUID of the LoadBalancer object
- * @return boolean
- */
-
- boolean neutronLoadBalancerExists(String uuid);
-
- /**
- * Applications call this interface method to return if a particular
- * LoadBalancer object exists
- *
- * @param uuid
- * UUID of the LoadBalancer object
- * @return {@link NeutronLoadBalancer}
- * OpenStackLoadBalancer class
- */
-
- NeutronLoadBalancer getNeutronLoadBalancer(String uuid);
-
- /**
- * Applications call this interface method to return all LoadBalancer objects
- *
- * @return List of OpenStackNetworks objects
- */
-
- List<NeutronLoadBalancer> getAllNeutronLoadBalancers();
-
- /**
- * Applications call this interface method to add a LoadBalancer object to the
- * concurrent map
- *
- * @param input
- * OpenStackNetwork object
- * @return boolean on whether the object was added or not
- */
-
- boolean addNeutronLoadBalancer(NeutronLoadBalancer input);
-
- /**
- * Applications call this interface method to remove a Neutron LoadBalancer object to the
- * concurrent map
- *
- * @param uuid
- * identifier for the LoadBalancer object
- * @return boolean on whether the object was removed or not
- */
-
- boolean removeNeutronLoadBalancer(String uuid);
-
- /**
- * Applications call this interface method to edit a LoadBalancer object
- *
- * @param uuid
- * identifier of the LoadBalancer object
- * @param delta
- * OpenStackLoadBalancer object containing changes to apply
- * @return boolean on whether the object was updated or not
- */
-
- boolean updateNeutronLoadBalancer(String uuid, NeutronLoadBalancer delta);
-
- /**
- * Applications call this interface method to see if a MAC address is in use
- *
- * @param uuid
- * identifier of the LoadBalancer object
- * @return boolean on whether the macAddress is already associated with a
- * port or not
- */
-
- boolean neutronLoadBalancerInUse(String uuid);
-
-}
+++ /dev/null
-/*
- * Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.crud;
-
-import java.util.List;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancerHealthMonitor;
-
-/**
- * This interface defines the methods for CRUD of NB OpenStack LoadBalancerHealthMonitor objects
- *
- */
-
-public interface INeutronLoadBalancerHealthMonitorCRUD {
- /**
- * Applications call this interface method to determine if a particular
- *LoadBalancerHealthMonitor object exists
- *
- * @param uuid
- * UUID of the LoadBalancerHealthMonitor object
- * @return boolean
- */
-
- boolean neutronLoadBalancerHealthMonitorExists(String uuid);
-
- /**
- * Applications call this interface method to return if a particular
- * LoadBalancerHealthMonitor object exists
- *
- * @param uuid
- * UUID of the LoadBalancerHealthMonitor object
- * @return {@link NeutronLoadBalancerHealthMonitor}
- * OpenStackLoadBalancerHealthMonitor class
- */
-
- NeutronLoadBalancerHealthMonitor getNeutronLoadBalancerHealthMonitor(String uuid);
-
- /**
- * Applications call this interface method to return all LoadBalancerHealthMonitor objects
- *
- * @return List of OpenStackNetworks objects
- */
-
- List<NeutronLoadBalancerHealthMonitor> getAllNeutronLoadBalancerHealthMonitors();
-
- /**
- * Applications call this interface method to add a LoadBalancerHealthMonitor object to the
- * concurrent map
- *
- * @param input
- * OpenStackNetwork object
- * @return boolean on whether the object was added or not
- */
-
- boolean addNeutronLoadBalancerHealthMonitor(NeutronLoadBalancerHealthMonitor input);
-
- /**
- * Applications call this interface method to remove a Neutron LoadBalancerHealthMonitor object to the
- * concurrent map
- *
- * @param uuid
- * identifier for the LoadBalancerHealthMonitor object
- * @return boolean on whether the object was removed or not
- */
-
- boolean removeNeutronLoadBalancerHealthMonitor(String uuid);
-
- /**
- * Applications call this interface method to edit a LoadBalancerHealthMonitor object
- *
- * @param uuid
- * identifier of the LoadBalancerHealthMonitor object
- * @param delta
- * OpenStackLoadBalancerHealthMonitor object containing changes to apply
- * @return boolean on whether the object was updated or not
- */
-
- boolean updateNeutronLoadBalancerHealthMonitor(String uuid, NeutronLoadBalancerHealthMonitor delta);
-
- /**
- * Applications call this interface method to see if a MAC address is in use
- *
- * @param uuid
- * identifier of the LoadBalancerHealthMonitor object
- * @return boolean on whether the macAddress is already associated with a
- * port or not
- */
-
- boolean neutronLoadBalancerHealthMonitorInUse(String uuid);
-
-}
+++ /dev/null
-/*
- * Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.crud;
-
-import java.util.List;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancerListener;
-
-/**
- * This interface defines the methods for CRUD of NB OpenStack LoadBalancerListener objects
- *
- */
-
-public interface INeutronLoadBalancerListenerCRUD {
- /**
- * Applications call this interface method to determine if a particular
- *LoadBalancerListener object exists
- *
- * @param uuid
- * UUID of the LoadBalancerListener object
- * @return boolean
- */
-
- boolean neutronLoadBalancerListenerExists(String uuid);
-
- /**
- * Applications call this interface method to return if a particular
- * LoadBalancerListener object exists
- *
- * @param uuid
- * UUID of the LoadBalancerListener object
- * @return {@link NeutronLoadBalancerListener}
- * OpenStackLoadBalancerListener class
- */
-
- NeutronLoadBalancerListener getNeutronLoadBalancerListener(String uuid);
-
- /**
- * Applications call this interface method to return all LoadBalancerListener objects
- *
- * @return List of OpenStackNetworks objects
- */
-
- List<NeutronLoadBalancerListener> getAllNeutronLoadBalancerListeners();
-
- /**
- * Applications call this interface method to add a LoadBalancerListener object to the
- * concurrent map
- *
- * @param input
- * OpenStackNetwork object
- * @return boolean on whether the object was added or not
- */
-
- boolean addNeutronLoadBalancerListener(NeutronLoadBalancerListener input);
-
- /**
- * Applications call this interface method to remove a Neutron LoadBalancerListener object to the
- * concurrent map
- *
- * @param uuid
- * identifier for the LoadBalancerListener object
- * @return boolean on whether the object was removed or not
- */
-
- boolean removeNeutronLoadBalancerListener(String uuid);
-
- /**
- * Applications call this interface method to edit a LoadBalancerListener object
- *
- * @param uuid
- * identifier of the LoadBalancerListener object
- * @param delta
- * OpenStackLoadBalancerListener object containing changes to apply
- * @return boolean on whether the object was updated or not
- */
-
- boolean updateNeutronLoadBalancerListener(String uuid, NeutronLoadBalancerListener delta);
-
- /**
- * Applications call this interface method to see if a MAC address is in use
- *
- * @param uuid
- * identifier of the LoadBalancerListener object
- * @return boolean on whether the macAddress is already associated with a
- * port or not
- */
-
- boolean neutronLoadBalancerListenerInUse(String uuid);
-
-}
+++ /dev/null
-/*
- * Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.crud;
-
-import java.util.List;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancerPool;
-
-/**
- * This interface defines the methods for CRUD of NB OpenStack LoadBalancerPool objects
- *
- */
-
-public interface INeutronLoadBalancerPoolCRUD {
- /**
- * Applications call this interface method to determine if a particular
- *LoadBalancerPool object exists
- *
- * @param uuid
- * UUID of the LoadBalancerPool object
- * @return boolean
- */
-
- boolean neutronLoadBalancerPoolExists(String uuid);
-
- /**
- * Applications call this interface method to return if a particular
- * LoadBalancerPool object exists
- *
- * @param uuid
- * UUID of the LoadBalancerPool object
- * @return {@link NeutronLoadBalancerPool}
- * OpenStackLoadBalancerPool class
- */
-
- NeutronLoadBalancerPool getNeutronLoadBalancerPool(String uuid);
-
- /**
- * Applications call this interface method to return all LoadBalancerPool objects
- *
- * @return List of OpenStackNetworks objects
- */
-
- List<NeutronLoadBalancerPool> getAllNeutronLoadBalancerPools();
-
- /**
- * Applications call this interface method to add a LoadBalancerPool object to the
- * concurrent map
- *
- * @param input
- * OpenStackNetwork object
- * @return boolean on whether the object was added or not
- */
-
- boolean addNeutronLoadBalancerPool(NeutronLoadBalancerPool input);
-
- /**
- * Applications call this interface method to remove a Neutron LoadBalancerPool object to the
- * concurrent map
- *
- * @param uuid
- * identifier for the LoadBalancerPool object
- * @return boolean on whether the object was removed or not
- */
-
- boolean removeNeutronLoadBalancerPool(String uuid);
-
- /**
- * Applications call this interface method to edit a LoadBalancerPool object
- *
- * @param uuid
- * identifier of the LoadBalancerPool object
- * @param delta
- * OpenStackLoadBalancerPool object containing changes to apply
- * @return boolean on whether the object was updated or not
- */
-
- boolean updateNeutronLoadBalancerPool(String uuid, NeutronLoadBalancerPool delta);
-
- /**
- * Applications call this interface method to see if a MAC address is in use
- *
- * @param uuid
- * identifier of the LoadBalancerPool object
- * @return boolean on whether the macAddress is already associated with a
- * port or not
- */
-
- boolean neutronLoadBalancerPoolInUse(String uuid);
-
-}
+++ /dev/null
-/*
- * Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.crud;
-
-import java.util.List;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancerPoolMember;
-
-public interface INeutronLoadBalancerPoolMemberCRUD {
-
- /**
- * Applications call this interface method to determine if a particular
- *NeutronLoadBalancerPoolMember object exists
- *
- * @param uuid
- * UUID of the NeutronLoadBalancerPoolMember object
- * @return boolean
- */
-
- boolean neutronLoadBalancerPoolMemberExists(String uuid);
-
- /**
- * Applications call this interface method to return if a particular
- * NeutronLoadBalancerPoolMember object exists
- *
- * @param uuid
- * UUID of the NeutronLoadBalancerPoolMember object
- * @return {@link NeutronLoadBalancerPoolMember}
- * OpenStackNeutronLoadBalancerPoolMember class
- */
-
- NeutronLoadBalancerPoolMember getNeutronLoadBalancerPoolMember(String uuid);
-
- /**
- * Applications call this interface method to return all NeutronLoadBalancerPoolMember objects
- *
- * @return List of OpenStackNetworks objects
- */
-
- List<NeutronLoadBalancerPoolMember> getAllNeutronLoadBalancerPoolMembers();
-
- /**
- * Applications call this interface method to add a NeutronLoadBalancerPoolMember object to the
- * concurrent map
- *
- * @param input
- * OpenStackNetwork object
- * @return boolean on whether the object was added or not
- */
-
- boolean addNeutronLoadBalancerPoolMember(NeutronLoadBalancerPoolMember input);
-
- /**
- * Applications call this interface method to remove a Neutron NeutronLoadBalancerPoolMember object to the
- * concurrent map
- *
- * @param uuid
- * identifier for the NeutronLoadBalancerPoolMember object
- * @return boolean on whether the object was removed or not
- */
-
- boolean removeNeutronLoadBalancerPoolMember(String uuid);
-
- /**
- * Applications call this interface method to edit a NeutronLoadBalancerPoolMember object
- *
- * @param uuid
- * identifier of the NeutronLoadBalancerPoolMember object
- * @param delta
- * OpenStackNeutronLoadBalancerPoolMember object containing changes to apply
- * @return boolean on whether the object was updated or not
- */
-
- boolean updateNeutronLoadBalancerPoolMember(String uuid, NeutronLoadBalancerPoolMember delta);
-
- /**
- * Applications call this interface method to see if a MAC address is in use
- *
- * @param uuid
- * identifier of the NeutronLoadBalancerPoolMember object
- * @return boolean on whether the macAddress is already associated with a
- * port or not
- */
-
- boolean neutronLoadBalancerPoolMemberInUse(String uuid);
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 IBM Corporation 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.netvirt.openstack.netvirt.translator.crud;
-
-import java.util.List;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-
-/**
- * This interface defines the methods for CRUD of NB network objects
- *
- */
-
-public interface INeutronNetworkCRUD {
- /**
- * Applications call this interface method to determine if a particular
- * Network object exists
- *
- * @param uuid
- * UUID of the Network object
- * @return boolean
- */
-
- boolean networkExists(String uuid);
-
- /**
- * Applications call this interface method to return if a particular
- * Network object exists
- *
- * @param uuid
- * UUID of the Network object
- * @return {@link NeutronNetwork}
- * OpenStack Network class
- */
-
- NeutronNetwork getNetwork(String uuid);
-
- /**
- * Applications call this interface method to return all Network objects
- *
- * @return List of OpenStackNetworks objects
- */
-
- List<NeutronNetwork> getAllNetworks();
-
- /**
- * Applications call this interface method to add a Network object to the
- * concurrent map
- *
- * @param input
- * OpenStackNetwork object
- * @return boolean on whether the object was added or not
- */
-
- boolean addNetwork(NeutronNetwork input);
-
- /**
- * Applications call this interface method to remove a Network object to the
- * concurrent map
- *
- * @param uuid
- * identifier for the network object
- * @return boolean on whether the object was removed or not
- */
-
- boolean removeNetwork(String uuid);
-
- /**
- * Applications call this interface method to edit a Network object
- *
- * @param uuid
- * identifier of the network object
- * @param delta
- * OpenStackNetwork object containing changes to apply
- * @return boolean on whether the object was updated or not
- */
-
- boolean updateNetwork(String uuid, NeutronNetwork delta);
-
- /**
- * Applications call this interface method to determine if a Network object
- * is use
- *
- * @param netUUID
- * identifier of the network object
- *
- * @return boolean on whether the network is in use or not
- */
-
- boolean networkInUse(String netUUID);
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 IBM Corporation 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.netvirt.openstack.netvirt.translator.crud;
-
-import java.util.List;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-
-/**
- * This interface defines the methods for CRUD of NB Port objects
- *
- */
-
-public interface INeutronPortCRUD {
- /**
- * Applications call this interface method to determine if a particular
- * Port object exists
- *
- * @param uuid
- * UUID of the Port object
- * @return boolean
- */
-
- boolean portExists(String uuid);
-
- /**
- * Applications call this interface method to return if a particular
- * Port object exists
- *
- * @param uuid
- * UUID of the Port object
- * @return {@link NeutronPort}
- * OpenStack Port class
- */
-
- NeutronPort getPort(String uuid);
-
- /**
- * Applications call this interface method to return all Port objects
- *
- * @return List of OpenStackPorts objects
- */
-
- List<NeutronPort> getAllPorts();
-
- /**
- * Applications call this interface method to add a Port object to the
- * concurrent map
- *
- * @param input
- * OpenStackPort object
- * @return boolean on whether the object was added or not
- */
-
- boolean addPort(NeutronPort input);
-
- /**
- * Applications call this interface method to remove a Port object to the
- * concurrent map
- *
- * @param uuid
- * identifier for the Port object
- * @return boolean on whether the object was removed or not
- */
-
- boolean removePort(String uuid);
-
- /**
- * Applications call this interface method to edit a Port object
- *
- * @param uuid
- * identifier of the Port object
- * @param delta
- * OpenStackPort object containing changes to apply
- * @return boolean on whether the object was updated or not
- */
-
- boolean updatePort(String uuid, NeutronPort delta);
-
- /**
- * Applications call this interface method to see if a MAC address is in use
- *
- * @param macAddress
- * mac Address to be tested
- * @return boolean on whether the macAddress is already associated with a
- * port or not
- *
- * @deprecated - will be removed in Boron
- */
-
- boolean macInUse(String macAddress);
-
- /**
- * Applications call this interface method to retrieve the port associated with
- * the gateway address of a subnet
- *
- * @param subnetUUID
- * identifier of the subnet
- * @return OpenStackPorts object if the port exists and null if it does not
- *
- * @deprecated - will be removed in Boron
- */
-
- NeutronPort getGatewayPort(String subnetUUID);
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 IBM Corporation 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.netvirt.openstack.netvirt.translator.crud;
-
-import java.util.List;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronRouter;
-
-/**
- * This interface defines the methods for CRUD of NB Router objects
- *
- */
-
-public interface INeutronRouterCRUD {
- /**
- * Applications call this interface method to determine if a particular
- * Router object exists
- *
- * @param uuid
- * UUID of the Router object
- * @return boolean
- */
-
- boolean routerExists(String uuid);
-
- /**
- * Applications call this interface method to return if a particular
- * Router object exists
- *
- * @param uuid
- * UUID of the Router object
- * @return {@link NeutronRouter}
- * OpenStack Router class
- */
-
- NeutronRouter getRouter(String uuid);
-
- /**
- * Applications call this interface method to return all Router objects
- *
- * @return List of OpenStackRouters objects
- */
-
- List<NeutronRouter> getAllRouters();
-
- /**
- * Applications call this interface method to add a Router object to the
- * concurrent map
- *
- * @param input
- * OpenStackRouter object
- * @return boolean on whether the object was added or not
- */
-
- boolean addRouter(NeutronRouter input);
-
- /**
- * Applications call this interface method to remove a Router object to the
- * concurrent map
- *
- * @param uuid
- * identifier for the Router object
- * @return boolean on whether the object was removed or not
- */
-
- boolean removeRouter(String uuid);
-
- /**
- * Applications call this interface method to edit a Router object
- *
- * @param uuid
- * identifier of the Router object
- * @param delta
- * OpenStackRouter object containing changes to apply
- * @return boolean on whether the object was updated or not
- */
-
- boolean updateRouter(String uuid, NeutronRouter delta);
-
- /**
- * Applications call this interface method to check if a router is in use
- *
- * @param routerUUID
- * identifier of the Router object
- * @return boolean on whether the router is in use or not
- */
-
- boolean routerInUse(String routerUUID);
-}
+++ /dev/null
-/*
- * Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.crud;
-
-import java.util.List;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityGroup;
-
-/**
- * This interface defines the methods for CRUD of NB OpenStack Security Group objects
- */
-
-public interface INeutronSecurityGroupCRUD {
- /**
- * Applications call this interface method to determine if a particular
- * Security Group object exists
- *
- * @param uuid UUID of the Security Group object
- * @return boolean
- */
-
- boolean neutronSecurityGroupExists(String uuid);
-
- /**
- * Applications call this interface method to return if a particular
- * Security Group object exists
- *
- * @param uuid UUID of the Security Group object
- * @return {@link NeutronSecurityGroup}
- * OpenStack Security Group class
- */
-
- NeutronSecurityGroup getNeutronSecurityGroup(String uuid);
-
- /**
- * Applications call this interface method to return all Security Group objects
- *
- * @return List of OpenStackSecurity Groups objects
- */
-
- List<NeutronSecurityGroup> getAllNeutronSecurityGroups();
-
- /**
- * Applications call this interface method to add a Security Group object to the
- * concurrent map
- *
- * @param input OpenStackSecurity Group object
- * @return boolean on whether the object was added or not
- */
-
- boolean addNeutronSecurityGroup(NeutronSecurityGroup input);
-
- /**
- * Applications call this interface method to remove a Neutron Security Group object to the
- * concurrent map
- *
- * @param uuid identifier for the security group object
- * @return boolean on whether the object was removed or not
- */
-
- boolean removeNeutronSecurityGroup(String uuid);
-
- /**
- * Applications call this interface method to edit a Security Group object
- *
- * @param uuid identifier of the security group object
- * @param delta OpenStackSecurity Group object containing changes to apply
- * @return boolean on whether the object was updated or not
- */
-
- boolean updateNeutronSecurityGroup(String uuid, NeutronSecurityGroup delta);
-
- /**
- * Applications call this interface method to see if a MAC address is in use
- *
- * @param uuid identifier of the security group object
- * @return boolean on whether the Security Groups is already in use
- */
-
- boolean neutronSecurityGroupInUse(String uuid);
-
-}
+++ /dev/null
-/*
- * Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.crud;
-
-import java.util.List;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityRule;
-
-/**
- * This interface defines the methods for CRUD of NB OpenStack Security Rule objects
- */
-
-public interface INeutronSecurityRuleCRUD {
- /**
- * Applications call this interface method to determine if a particular
- * Security Rule object exists
- *
- * @param uuid UUID of theSecurity Rule object
- * @return boolean
- */
-
- boolean neutronSecurityRuleExists(String uuid);
-
- /**
- * Applications call this interface method to return if a particular
- * Security Rule object exists
- *
- * @param uuid UUID of the security rule object
- * @return {@link NeutronSecurityRule}
- * OpenStackSecurity Rule class
- */
-
- NeutronSecurityRule getNeutronSecurityRule(String uuid);
-
- /**
- * Applications call this interface method to return all Security Rule objects
- *
- * @return List of OpenStack SecurityRules objects
- */
-
- List<NeutronSecurityRule> getAllNeutronSecurityRules();
-
- /**
- * Applications call this interface method to add a Security Rule object to the
- * concurrent map
- *
- * @param input OpenStack security rule object
- * @return boolean on whether the object was added or not
- */
-
- boolean addNeutronSecurityRule(NeutronSecurityRule input);
-
- /**
- * Applications call this interface method to remove a Neutron Security Rule object to the
- * concurrent map
- *
- * @param uuid identifier for the security rule object
- * @return boolean on whether the object was removed or not
- */
-
- boolean removeNeutronSecurityRule(String uuid);
-
- /**
- * Applications call this interface method to edit aSecurity Rule object
- *
- * @param uuid identifier of the security rule object
- * @param delta OpenStackSecurity Rule object containing changes to apply
- * @return boolean on whether the object was updated or not
- */
-
- boolean updateNeutronSecurityRule(String uuid, NeutronSecurityRule delta);
-
- /**
- * Applications call this interface method to see if a MAC address is in use
- *
- * @param uuid identifier of the security rule object
- * @return boolean on whether the macAddress is already associated with a
- * port or not
- */
-
- boolean neutronSecurityRuleInUse(String uuid);
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 IBM Corporation 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.netvirt.openstack.netvirt.translator.crud;
-
-import java.util.List;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSubnet;
-
-/**
- * This interface defines the methods for CRUD of NB Subnet objects
- *
- */
-
-public interface INeutronSubnetCRUD {
- /**
- * Applications call this interface method to determine if a particular
- * Subnet object exists
- *
- * @param uuid
- * UUID of the Subnet object
- * @return boolean
- */
-
- boolean subnetExists(String uuid);
-
- /**
- * Applications call this interface method to return if a particular
- * Subnet object exists
- *
- * @param uuid
- * UUID of the Subnet object
- * @return {@link NeutronSubnet}
- * OpenStack Subnet class
- */
-
- NeutronSubnet getSubnet(String uuid);
-
- /**
- * Applications call this interface method to return all Subnet objects
- *
- * @return List of OpenStackSubnets objects
- */
-
- List<NeutronSubnet> getAllSubnets();
-
- /**
- * Applications call this interface method to add a Subnet object to the
- * concurrent map
- *
- * @param input
- * OpenStackSubnet object
- * @return boolean on whether the object was added or not
- */
-
- boolean addSubnet(NeutronSubnet input);
-
- /**
- * Applications call this interface method to remove a Subnet object to the
- * concurrent map
- *
- * @param uuid
- * identifier for the Subnet object
- * @return boolean on whether the object was removed or not
- */
-
- boolean removeSubnet(String uuid);
-
- /**
- * Applications call this interface method to edit a Subnet object
- *
- * @param uuid
- * identifier of the Subnet object
- * @param delta
- * OpenStackSubnet object containing changes to apply
- * @return boolean on whether the object was updated or not
- */
-
- boolean updateSubnet(String uuid, NeutronSubnet delta);
-
- /**
- * Applications call this interface method to determine if a Subnet object
- * is use
- *
- * @param subnetUUID
- * identifier of the subnet object
- *
- * @return boolean on whether the subnet is in use or not
- *
- * @deprecated - will be removed in Boron
- */
-
- boolean subnetInUse(String subnetUUID);
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 IBM Corporation 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.netvirt.openstack.netvirt.translator.crud;
-
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.FrameworkUtil;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class NeutronCRUDInterfaces {
- private static final Logger LOGGER = LoggerFactory
- .getLogger(NeutronCRUDInterfaces.class);
-
- private INeutronNetworkCRUD networkInterface;
- private INeutronSubnetCRUD subnetInterface;
- private INeutronPortCRUD portInterface;
- private INeutronRouterCRUD routerInterface;
- private INeutronFloatingIPCRUD fipInterface;
- private INeutronSecurityGroupCRUD sgInterface;
- private INeutronSecurityRuleCRUD srInterface;
- private INeutronFirewallCRUD fwInterface;
- private INeutronFirewallPolicyCRUD fwpInterface;
- private INeutronFirewallRuleCRUD fwrInterface;
- private INeutronLoadBalancerCRUD lbInterface;
- private INeutronLoadBalancerPoolCRUD lbpInterface;
- private INeutronLoadBalancerListenerCRUD lblInterface;
- private INeutronLoadBalancerHealthMonitorCRUD lbhmInterface;
- private INeutronLoadBalancerPoolMemberCRUD lbpmInterface;
- public NeutronCRUDInterfaces() {
- }
-
- public INeutronNetworkCRUD getNetworkInterface() {
- return networkInterface;
- }
-
- public INeutronSubnetCRUD getSubnetInterface() {
- return subnetInterface;
- }
-
- public INeutronPortCRUD getPortInterface() {
- return portInterface;
- }
-
- public INeutronRouterCRUD getRouterInterface() {
- return routerInterface;
- }
-
- public INeutronFloatingIPCRUD getFloatingIPInterface() {
- return fipInterface;
- }
-
- public INeutronSecurityGroupCRUD getSecurityGroupInterface() {
- return sgInterface;
- }
-
- public INeutronSecurityRuleCRUD getSecurityRuleInterface() {
- return srInterface;
- }
-
- public INeutronFirewallCRUD getFirewallInterface() {
- return fwInterface;
- }
-
- public INeutronFirewallPolicyCRUD getFirewallPolicyInterface() {
- return fwpInterface;
- }
-
- public INeutronFirewallRuleCRUD getFirewallRuleInterface() {
- return fwrInterface;
- }
-
- public INeutronLoadBalancerCRUD getLoadBalancerInterface() {
- return lbInterface;
- }
-
- public INeutronLoadBalancerPoolCRUD getLoadBalancerPoolInterface() {
- return lbpInterface;
- }
-
- public INeutronLoadBalancerListenerCRUD getLoadBalancerListenerInterface() {
- return lblInterface;
- }
-
- public INeutronLoadBalancerHealthMonitorCRUD getLoadBalancerHealthMonitorInterface() {
- return lbhmInterface;
- }
-
- public INeutronLoadBalancerPoolMemberCRUD getLoadBalancerPoolMemberInterface() {
- return lbpmInterface;
- }
-
- public NeutronCRUDInterfaces fetchINeutronNetworkCRUD(Object obj) {
- networkInterface = (INeutronNetworkCRUD) getInstances(INeutronNetworkCRUD.class, obj);
- return this;
- }
-
- public NeutronCRUDInterfaces fetchINeutronSubnetCRUD(Object obj) {
- subnetInterface = (INeutronSubnetCRUD) getInstances(INeutronSubnetCRUD.class, obj);
- return this;
- }
-
- public NeutronCRUDInterfaces fetchINeutronPortCRUD(Object obj) {
- portInterface = (INeutronPortCRUD) getInstances(INeutronPortCRUD.class, obj);
- return this;
- }
-
- public NeutronCRUDInterfaces fetchINeutronRouterCRUD(Object obj) {
- routerInterface = (INeutronRouterCRUD) getInstances(INeutronRouterCRUD.class, obj);
- return this;
- }
-
- public NeutronCRUDInterfaces fetchINeutronFloatingIPCRUD(Object obj) {
- fipInterface = (INeutronFloatingIPCRUD) getInstances(INeutronFloatingIPCRUD.class, obj);
- return this;
- }
-
- public NeutronCRUDInterfaces fetchINeutronSecurityGroupCRUD(Object obj) {
- sgInterface = (INeutronSecurityGroupCRUD) getInstances(INeutronSecurityGroupCRUD.class, obj);
- return this;
- }
-
- public NeutronCRUDInterfaces fetchINeutronSecurityRuleCRUD(Object obj) {
- srInterface = (INeutronSecurityRuleCRUD) getInstances(INeutronSecurityRuleCRUD.class, obj);
- return this;
- }
-
- public NeutronCRUDInterfaces fetchINeutronFirewallCRUD(Object obj) {
- fwInterface = (INeutronFirewallCRUD) getInstances(INeutronFirewallCRUD.class, obj);
- return this;
- }
-
- public NeutronCRUDInterfaces fetchINeutronFirewallPolicyCRUD(Object obj) {
- fwpInterface = (INeutronFirewallPolicyCRUD) getInstances(INeutronFirewallPolicyCRUD.class, obj);
- return this;
- }
-
- public NeutronCRUDInterfaces fetchINeutronFirewallRuleCRUD(Object obj) {
- fwrInterface = (INeutronFirewallRuleCRUD) getInstances(INeutronFirewallRuleCRUD.class, obj);
- return this;
- }
-
- public NeutronCRUDInterfaces fetchINeutronLoadBalancerCRUD(Object obj) {
- lbInterface = (INeutronLoadBalancerCRUD) getInstances(INeutronLoadBalancerCRUD.class, obj);
- return this;
- }
-
- public NeutronCRUDInterfaces fetchINeutronLoadBalancerPoolCRUD(Object obj) {
- lbpInterface = (INeutronLoadBalancerPoolCRUD) getInstances(INeutronLoadBalancerPoolCRUD.class, obj);
- return this;
- }
-
- public NeutronCRUDInterfaces fetchINeutronLoadBalancerListenerCRUD(Object obj) {
- lblInterface = (INeutronLoadBalancerListenerCRUD) getInstances(INeutronLoadBalancerListenerCRUD.class, obj);
- return this;
- }
-
- public NeutronCRUDInterfaces fetchINeutronLoadBalancerHealthMonitorCRUD(Object obj) {
- lbhmInterface = (INeutronLoadBalancerHealthMonitorCRUD) getInstances(INeutronLoadBalancerHealthMonitorCRUD.class, obj);
- return this;
- }
-
- public NeutronCRUDInterfaces fetchINeutronLoadBalancerPoolMemberCRUD(Object obj) {
- lbpmInterface = (INeutronLoadBalancerPoolMemberCRUD) getInstances(INeutronLoadBalancerPoolMemberCRUD.class, obj);
- return this;
- }
-
- public Object getInstances(Class<?> clazz, Object bundle) {
- try {
- BundleContext bCtx = FrameworkUtil.getBundle(bundle.getClass()).getBundleContext();
-
- ServiceReference<?>[] services = null;
- services = bCtx.getServiceReferences(clazz.getName(), null);
- if (services != null) {
- return bCtx.getService(services[0]);
- }
- } catch (Exception e) {
- LOGGER.error("Error in getInstances", e);
- }
- return null;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.crud.impl;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.util.concurrent.CheckedFuture;
-import java.lang.reflect.Method;
-import java.util.concurrent.ExecutionException;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
-import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
-import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
-import org.opendaylight.netvirt.openstack.netvirt.translator.INeutronObject;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-
-public abstract class AbstractNeutronInterface<T extends DataObject, S extends INeutronObject> implements AutoCloseable {
- private static final Logger LOG = LoggerFactory.getLogger(AbstractNeutronInterface.class);
- private static final int DEDASHED_UUID_LENGTH = 32;
- private static final int DEDASHED_UUID_START = 0;
- private static final int DEDASHED_UUID_DIV1 = 8;
- private static final int DEDASHED_UUID_DIV2 = 12;
- private static final int DEDASHED_UUID_DIV3 = 16;
- private static final int DEDASHED_UUID_DIV4 = 20;
-
- private final DataBroker db;
-
- AbstractNeutronInterface(final DataBroker dataBroker) {
- this.db = dataBroker;
- }
-
- public DataBroker getDataBroker() {
- return db;
- }
-
- protected abstract InstanceIdentifier<T> createInstanceIdentifier(T item);
-
- protected abstract T toMd(S neutronObject);
-
- protected abstract T toMd(String uuid);
-
- protected <B extends org.opendaylight.yangtools.yang.binding.DataObject> B readMd(InstanceIdentifier<B> path) {
- B result = null;
- final ReadOnlyTransaction transaction = getDataBroker().newReadOnlyTransaction();
- CheckedFuture<Optional<B>, ReadFailedException> future = transaction.read(LogicalDatastoreType.CONFIGURATION, path);
- if (future != null) {
- try {
- result = future.checkedGet().orNull();
- } catch (ReadFailedException e) {
- LOG.warn("Failed to read {}", path, e);
- }
- }
- transaction.close();
- return result;
- }
-
- protected boolean addMd(S neutronObject) {
- // TODO think about adding existence logic
- return updateMd(neutronObject);
- }
-
- protected boolean updateMd(S neutronObject) {
- WriteTransaction transaction = getDataBroker().newWriteOnlyTransaction();
- T item = toMd(neutronObject);
- InstanceIdentifier<T> iid = createInstanceIdentifier(item);
- transaction.put(LogicalDatastoreType.CONFIGURATION, iid, item,true);
- CheckedFuture<Void, TransactionCommitFailedException> future = transaction.submit();
- try {
- future.get();
- } catch (InterruptedException | ExecutionException e) {
- LOG.warn("Transation failed ",e);
- return false;
- }
- return true;
- }
-
- protected boolean removeMd(T item) {
- WriteTransaction transaction = getDataBroker().newWriteOnlyTransaction();
- InstanceIdentifier<T> iid = createInstanceIdentifier(item);
- transaction.delete(LogicalDatastoreType.CONFIGURATION, iid);
- CheckedFuture<Void, TransactionCommitFailedException> future = transaction.submit();
- try {
- future.get();
- } catch (InterruptedException | ExecutionException e) {
- LOG.warn("Transation failed ",e);
- return false;
- }
- return true;
- }
-
- protected Uuid toUuid(String uuid) {
- Preconditions.checkNotNull(uuid);
- Uuid result;
- try {
- result = new Uuid(uuid);
- } catch(IllegalArgumentException e) {
- // OK... someone didn't follow RFC 4122... lets try this the hard way
- String dedashed = uuid.replace("-", "");
- if(dedashed.length() == DEDASHED_UUID_LENGTH) {
- String redashed = dedashed.substring(DEDASHED_UUID_START, DEDASHED_UUID_DIV1)
- + "-"
- + dedashed.substring(DEDASHED_UUID_DIV1, DEDASHED_UUID_DIV2)
- + "-"
- + dedashed.substring(DEDASHED_UUID_DIV2, DEDASHED_UUID_DIV3)
- + "-"
- + dedashed.substring(DEDASHED_UUID_DIV3, DEDASHED_UUID_DIV4)
- + "-"
- + dedashed.substring(DEDASHED_UUID_DIV4, DEDASHED_UUID_LENGTH);
- result = new Uuid(redashed);
- } else {
- throw e;
- }
- }
- return result;
- }
-
- // this method uses reflection to update an object from it's delta.
-
- protected boolean overwrite(Object target, Object delta) {
- Method[] methods = target.getClass().getMethods();
-
- for(Method toMethod: methods){
- if(toMethod.getDeclaringClass().equals(target.getClass())
- && toMethod.getName().startsWith("set")){
-
- String toName = toMethod.getName();
- String fromName = toName.replace("set", "get");
-
- try {
- Method fromMethod = delta.getClass().getMethod(fromName);
- Object value = fromMethod.invoke(delta, (Object[])null);
- if(value != null){
- toMethod.invoke(target, value);
- }
- } catch (Exception e) {
- LOG.error("Error in overwrite", e);
- return false;
- }
- }
- }
- return true;
- }
-
- @Override
- public void close() throws Exception {
- // TODO Auto-generated method stub
-
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.crud.impl;
-
-import java.util.List;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.netvirt.openstack.netvirt.translator.INeutronObject;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronFirewall;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronFirewallCRUD;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
-
-public class NeutronFirewallInterface extends AbstractNeutronInterface implements INeutronFirewallCRUD {
-
- NeutronFirewallInterface(final DataBroker dataBroker) {
- super(dataBroker);
- }
-
- public static void registerNewInterface(BundleContext context,
- final DataBroker dataBroker,
- List<ServiceRegistration<?>> registrations) {
- NeutronFirewallInterface neutronFirewallInterface = new NeutronFirewallInterface(dataBroker);
- ServiceRegistration<INeutronFirewallCRUD> neutronFirewallInterfaceRegistration = context.registerService(INeutronFirewallCRUD.class, neutronFirewallInterface, null);
- if(neutronFirewallInterfaceRegistration != null) {
- registrations.add(neutronFirewallInterfaceRegistration);
- }
- }
-
- @Override
- public boolean neutronFirewallExists(String uuid) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public NeutronFirewall getNeutronFirewall(String uuid) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public List<NeutronFirewall> getAllNeutronFirewalls() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public boolean addNeutronFirewall(NeutronFirewall input) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public boolean removeNeutronFirewall(String uuid) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public boolean updateNeutronFirewall(String uuid, NeutronFirewall delta) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public boolean neutronFirewallInUse(String uuid) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- protected InstanceIdentifier createInstanceIdentifier(DataObject item) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- protected DataObject toMd(INeutronObject neutronObject) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- protected DataObject toMd(String uuid) {
- // TODO Auto-generated method stub
- return null;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.crud.impl;
-
-import java.util.List;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.netvirt.openstack.netvirt.translator.INeutronObject;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronFirewallPolicy;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronFirewallPolicyCRUD;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
-
-/**
- */
-
-public class NeutronFirewallPolicyInterface extends AbstractNeutronInterface implements INeutronFirewallPolicyCRUD {
-
- NeutronFirewallPolicyInterface(final DataBroker dataBroker) {
- super(dataBroker);
- }
-
- @Override
- public boolean neutronFirewallPolicyExists(String uuid) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public NeutronFirewallPolicy getNeutronFirewallPolicy(String uuid) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public List<NeutronFirewallPolicy> getAllNeutronFirewallPolicies() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public boolean addNeutronFirewallPolicy(NeutronFirewallPolicy input) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public boolean removeNeutronFirewallPolicy(String uuid) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public boolean updateNeutronFirewallPolicy(String uuid,
- NeutronFirewallPolicy delta) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public boolean neutronFirewallPolicyInUse(String uuid) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- protected InstanceIdentifier createInstanceIdentifier(DataObject item) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- protected DataObject toMd(INeutronObject neutronObject) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- protected DataObject toMd(String uuid) {
- // TODO Auto-generated method stub
- return null;
- }
-
- public static void registerNewInterface(BundleContext context,
- final DataBroker dataBroker,
- List<ServiceRegistration<?>> registrations) {
- NeutronFirewallPolicyInterface neutronFirewallPolicyInterface = new NeutronFirewallPolicyInterface(dataBroker);
- ServiceRegistration<INeutronFirewallPolicyCRUD> neutronFirewallPolicyInterfaceRegistration = context.registerService(INeutronFirewallPolicyCRUD.class, neutronFirewallPolicyInterface, null);
- if(neutronFirewallPolicyInterfaceRegistration != null) {
- registrations.add(neutronFirewallPolicyInterfaceRegistration);
- }
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.crud.impl;
-
-import java.util.List;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.netvirt.openstack.netvirt.translator.INeutronObject;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronFirewallRule;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronFirewallRuleCRUD;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
-
-public class NeutronFirewallRuleInterface extends AbstractNeutronInterface implements INeutronFirewallRuleCRUD {
-
- NeutronFirewallRuleInterface(DataBroker dataBroker) {
- super(dataBroker);
- }
-
- @Override
- public boolean neutronFirewallRuleExists(String uuid) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public NeutronFirewallRule getNeutronFirewallRule(String uuid) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public List<NeutronFirewallRule> getAllNeutronFirewallRules() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public boolean addNeutronFirewallRule(NeutronFirewallRule input) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public boolean removeNeutronFirewallRule(String uuid) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public boolean updateNeutronFirewallRule(String uuid,
- NeutronFirewallRule delta) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public boolean neutronFirewallRuleInUse(String uuid) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- protected InstanceIdentifier createInstanceIdentifier(DataObject item) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- protected DataObject toMd(INeutronObject neutronObject) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- protected DataObject toMd(String uuid) {
- // TODO Auto-generated method stub
- return null;
- }
-
- public static void registerNewInterface(BundleContext context,
- final DataBroker dataBroker,
- List<ServiceRegistration<?>> registrations) {
- NeutronFirewallRuleInterface neutronFirewallRuleInterface = new NeutronFirewallRuleInterface(dataBroker);
- ServiceRegistration<INeutronFirewallRuleCRUD> neutronFirewallRuleInterfaceRegistration = context.registerService(INeutronFirewallRuleCRUD.class, neutronFirewallRuleInterface, null);
- if(neutronFirewallRuleInterfaceRegistration != null) {
- registrations.add(neutronFirewallRuleInterfaceRegistration);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 IBM Corporation 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.netvirt.openstack.netvirt.translator.crud.impl;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.ProviderContext;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronFloatingIP;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronFloatingIPCRUD;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.floatingips.attributes.Floatingips;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.floatingips.attributes.floatingips.Floatingip;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.floatingips.attributes.floatingips.FloatingipBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class NeutronFloatingIPInterface extends AbstractNeutronInterface<Floatingip, NeutronFloatingIP> implements INeutronFloatingIPCRUD {
- private static final Logger LOG = LoggerFactory.getLogger(NeutronFloatingIPInterface.class);
-
- NeutronFloatingIPInterface(final DataBroker dataBroker) {
- super(dataBroker);
- }
-
- // IfNBFloatingIPCRUD interface methods
-
- @Override
- public boolean floatingIPExists(String uuid) {
- Floatingip fip = readMd(createInstanceIdentifier(toMd(uuid)));
- return (fip != null);
- }
-
- @Override
- public NeutronFloatingIP getFloatingIP(String uuid) {
- Floatingip fip = readMd(createInstanceIdentifier(toMd(uuid)));
- if (fip == null) {
- return null;
- }
- return fromMd(fip);
- }
-
- @Override
- public List<NeutronFloatingIP> getAllFloatingIPs() {
- Set<NeutronFloatingIP> allIPs = new HashSet<>();
- Floatingips fips = readMd(createInstanceIdentifier());
- if (fips != null) {
- for (Floatingip fip: fips.getFloatingip()) {
- allIPs.add(fromMd(fip));
- }
- }
- LOG.debug("Exiting getAllFloatingIPs, Found {} FloatingIPs", allIPs.size());
- List<NeutronFloatingIP> ans = new ArrayList<>();
- ans.addAll(allIPs);
- return ans;
- }
-
- @Override
- public boolean addFloatingIP(NeutronFloatingIP input) {
- if (floatingIPExists(input.getID())) {
- return false;
- }
- return addMd(input);
- }
-
- @Override
- public boolean removeFloatingIP(String uuid) {
- NeutronFloatingIP fip = getFloatingIP(uuid);
- if (fip == null) {
- return false;
- }
- return removeMd(toMd(uuid));
- }
-
- @Override
- public boolean updateFloatingIP(String uuid, NeutronFloatingIP delta) {
- NeutronFloatingIP target = getFloatingIP(uuid);
- if (target == null) {
- return false;
- }
- delta.setPortUUID(target.getPortUUID());
- delta.setFixedIPAddress(target.getFixedIPAddress());
- return updateMd(delta);
- }
-
- @Override
- protected Floatingip toMd(String uuid) {
- FloatingipBuilder floatingipBuilder = new FloatingipBuilder();
- floatingipBuilder.setUuid(toUuid(uuid));
- return floatingipBuilder.build();
- }
-
- @Override
- protected Floatingip toMd(NeutronFloatingIP floatingIp) {
- FloatingipBuilder floatingipBuilder = new FloatingipBuilder();
- if (floatingIp.getFixedIPAddress() != null) {
- floatingipBuilder.setFixedIpAddress(new IpAddress(floatingIp.getFixedIPAddress().toCharArray()));
- }
- if(floatingIp.getFloatingIPAddress() != null) {
- floatingipBuilder.setFloatingIpAddress(new IpAddress(floatingIp.getFloatingIPAddress().toCharArray()));
- }
- if (floatingIp.getFloatingNetworkUUID() != null) {
- floatingipBuilder.setFloatingNetworkId(toUuid(floatingIp.getFloatingNetworkUUID()));
- }
- if (floatingIp.getPortUUID() != null) {
- floatingipBuilder.setPortId(toUuid(floatingIp.getPortUUID()));
- }
- if (floatingIp.getRouterUUID() != null) {
- floatingipBuilder.setRouterId(toUuid(floatingIp.getRouterUUID()));
- }
- if (floatingIp.getStatus() != null) {
- floatingipBuilder.setStatus(floatingIp.getStatus());
- }
- if (floatingIp.getTenantUUID() != null) {
- floatingipBuilder.setTenantId(toUuid(floatingIp.getTenantUUID()));
- }
- if (floatingIp.getID() != null) {
- floatingipBuilder.setUuid(toUuid(floatingIp.getID()));
- }
- else {
- LOG.warn("Attempting to write neutron floating IP without UUID");
- }
- return floatingipBuilder.build();
- }
-
- protected NeutronFloatingIP fromMd(Floatingip fip) {
- NeutronFloatingIP result = new NeutronFloatingIP();
- result.setID(String.valueOf(fip.getUuid().getValue()));
- if (fip.getFloatingNetworkId() != null) {
- result.setFloatingNetworkUUID(String.valueOf(fip.getFloatingNetworkId().getValue()));
- }
- if (fip.getPortId() != null) {
- result.setPortUUID(String.valueOf(fip.getPortId().getValue()));
- }
- if (fip.getFixedIpAddress() != null ) {
- result.setFixedIPAddress(String.valueOf(fip.getFixedIpAddress().getValue()));
- }
- if (fip.getFloatingIpAddress() != null) {
- result.setFloatingIPAddress(String.valueOf(fip.getFloatingIpAddress().getValue()));
- }
- if (fip.getTenantId() != null) {
- result.setTenantUUID(String.valueOf(fip.getTenantId().getValue()));
- }
- if (fip.getRouterId() != null) {
- result.setRouterUUID(String.valueOf(fip.getRouterId().getValue()));
- }
- result.setStatus(fip.getStatus());
- return result;
- }
-
- @Override
- protected InstanceIdentifier<Floatingip> createInstanceIdentifier(
- Floatingip item) {
- return InstanceIdentifier.create(Neutron.class)
- .child(Floatingips.class)
- .child(Floatingip.class,item.getKey());
- }
-
- protected InstanceIdentifier<Floatingips> createInstanceIdentifier() {
- return InstanceIdentifier.create(Neutron.class)
- .child(Floatingips.class);
- }
-
- public static void registerNewInterface(BundleContext context,
- final DataBroker dataBroker,
- List<ServiceRegistration<?>> registrations) {
- NeutronFloatingIPInterface neutronFloatingIPInterface = new NeutronFloatingIPInterface(dataBroker);
- ServiceRegistration<INeutronFloatingIPCRUD> neutronFloatingIPInterfaceRegistration = context.registerService(INeutronFloatingIPCRUD.class, neutronFloatingIPInterface, null);
- if (neutronFloatingIPInterfaceRegistration != null) {
- registrations.add(neutronFloatingIPInterfaceRegistration);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.crud.impl;
-
-import java.util.List;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.ProviderContext;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancerHealthMonitor;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronLoadBalancerHealthMonitorCRUD;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.lbaasv2.rev150712.lbaas.attributes.Healthmonitors;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
-
-public class NeutronLoadBalancerHealthMonitorInterface extends AbstractNeutronInterface<Healthmonitors, NeutronLoadBalancerHealthMonitor> implements INeutronLoadBalancerHealthMonitorCRUD {
-
- NeutronLoadBalancerHealthMonitorInterface(DataBroker dataBroker) {
- super(dataBroker);
- }
-
- @Override
- public boolean neutronLoadBalancerHealthMonitorExists(String uuid) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public NeutronLoadBalancerHealthMonitor getNeutronLoadBalancerHealthMonitor(
- String uuid) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public List<NeutronLoadBalancerHealthMonitor> getAllNeutronLoadBalancerHealthMonitors() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public boolean addNeutronLoadBalancerHealthMonitor(
- NeutronLoadBalancerHealthMonitor input) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public boolean removeNeutronLoadBalancerHealthMonitor(String uuid) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public boolean updateNeutronLoadBalancerHealthMonitor(String uuid,
- NeutronLoadBalancerHealthMonitor delta) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public boolean neutronLoadBalancerHealthMonitorInUse(String uuid) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- protected InstanceIdentifier<Healthmonitors> createInstanceIdentifier(
- Healthmonitors item) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- protected Healthmonitors toMd(NeutronLoadBalancerHealthMonitor neutronObject) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- protected Healthmonitors toMd(String uuid) {
- // TODO Auto-generated method stub
- return null;
- }
-
- public static void registerNewInterface(BundleContext context,
- final DataBroker dataBroker,
- List<ServiceRegistration<?>> registrations) {
- NeutronLoadBalancerHealthMonitorInterface neutronLoadBalancerHealthMonitorInterface = new NeutronLoadBalancerHealthMonitorInterface(dataBroker);
- ServiceRegistration<INeutronLoadBalancerHealthMonitorCRUD> neutronLoadBalancerHealthMonitorInterfaceRegistration = context.registerService(INeutronLoadBalancerHealthMonitorCRUD.class, neutronLoadBalancerHealthMonitorInterface, null);
- if(neutronLoadBalancerHealthMonitorInterfaceRegistration != null) {
- registrations.add(neutronLoadBalancerHealthMonitorInterfaceRegistration);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.crud.impl;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancer;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronLoadBalancerCRUD;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.lbaasv2.rev150712.lbaas.attributes.Loadbalancers;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.lbaasv2.rev150712.lbaas.attributes.loadbalancers.Loadbalancer;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.lbaasv2.rev150712.lbaas.attributes.loadbalancers.LoadbalancerBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * TODO: Migrate this to consume the MD-SAL data store, so that it can read all the data from data store.
- * No need to worry about the write/update related methods here. OVSDB net-virt will use these CRUD Interface
- * only for reading. We will cleanup these interface/methods later.
- */
-public class NeutronLoadBalancerInterface extends AbstractNeutronInterface<Loadbalancer, NeutronLoadBalancer> implements INeutronLoadBalancerCRUD {
- private static final Logger LOG = LoggerFactory.getLogger(NeutronLoadBalancerInterface.class);
- private ConcurrentMap<String, NeutronLoadBalancer> loadBalancerDB = new ConcurrentHashMap<>();
-
-
- NeutronLoadBalancerInterface(final DataBroker dataBroker) {
- super(dataBroker);
- }
-
- @Override
- public boolean neutronLoadBalancerExists(String uuid) {
- return loadBalancerDB.containsKey(uuid);
- }
-
- @Override
- public NeutronLoadBalancer getNeutronLoadBalancer(String uuid) {
- if (!neutronLoadBalancerExists(uuid)) {
- LOG.debug("No LoadBalancer Have Been Defined");
- return null;
- }
- return loadBalancerDB.get(uuid);
- }
-
- @Override
- public List<NeutronLoadBalancer> getAllNeutronLoadBalancers() {
- Set<NeutronLoadBalancer> allLoadBalancers = new HashSet<>();
- for (Entry<String, NeutronLoadBalancer> entry : loadBalancerDB.entrySet()) {
- NeutronLoadBalancer loadBalancer = entry.getValue();
- allLoadBalancers.add(loadBalancer);
- }
- LOG.debug("Exiting getLoadBalancers, Found {} OpenStackLoadBalancer", allLoadBalancers.size());
- List<NeutronLoadBalancer> ans = new ArrayList<>();
- ans.addAll(allLoadBalancers);
- return ans;
- }
-
- @Override
- public boolean addNeutronLoadBalancer(NeutronLoadBalancer input) {
- if (neutronLoadBalancerExists(input.getID())) {
- return false;
- }
- loadBalancerDB.putIfAbsent(input.getID(), input);
- //TODO: add code to find INeutronLoadBalancerAware services and call newtorkCreated on them
- return true;
- }
-
- @Override
- public boolean removeNeutronLoadBalancer(String uuid) {
- if (!neutronLoadBalancerExists(uuid)) {
- return false;
- }
- loadBalancerDB.remove(uuid);
- //TODO: add code to find INeutronLoadBalancerAware services and call newtorkDeleted on them
- return true;
- }
-
- @Override
- public boolean updateNeutronLoadBalancer(String uuid, NeutronLoadBalancer delta) {
- if (!neutronLoadBalancerExists(uuid)) {
- return false;
- }
- NeutronLoadBalancer target = loadBalancerDB.get(uuid);
- return overwrite(target, delta);
- }
-
- @Override
- public boolean neutronLoadBalancerInUse(String loadBalancerUUID) {
- return !neutronLoadBalancerExists(loadBalancerUUID);
- }
-
- @Override
- protected Loadbalancer toMd(String uuid) {
- LoadbalancerBuilder loadBalancersBuilder = new LoadbalancerBuilder();
- loadBalancersBuilder.setUuid(toUuid(uuid));
- return loadBalancersBuilder.build();
- }
-
- @Override
- protected InstanceIdentifier<Loadbalancer> createInstanceIdentifier(
- Loadbalancer loadBalancer) {
- return InstanceIdentifier.create(Neutron.class)
- .child(Loadbalancers.class)
- .child(Loadbalancer.class, loadBalancer.getKey());
- }
-
- @Override
- protected Loadbalancer toMd(NeutronLoadBalancer loadBalancer) {
- LoadbalancerBuilder loadBalancersBuilder = new LoadbalancerBuilder();
- loadBalancersBuilder.setAdminStateUp(loadBalancer.getLoadBalancerAdminStateUp());
- if (loadBalancer.getLoadBalancerName() != null) {
- loadBalancersBuilder.setName(loadBalancer.getLoadBalancerName());
- }
- if (loadBalancer.getLoadBalancerStatus() != null) {
- loadBalancersBuilder.setStatus(loadBalancer.getLoadBalancerStatus());
- }
- if (loadBalancer.getLoadBalancerTenantID() != null) {
- loadBalancersBuilder.setTenantId(toUuid(loadBalancer.getLoadBalancerTenantID()));
- }
- if (loadBalancer.getLoadBalancerVipAddress() != null) {
- loadBalancersBuilder.setVipAddress(new IpAddress(loadBalancer.getLoadBalancerVipAddress().toCharArray()));
- }
- if (loadBalancer.getLoadBalancerVipSubnetID() != null) {
- loadBalancersBuilder.setVipSubnetId(toUuid(loadBalancer.getLoadBalancerVipSubnetID()));
- }
- if (loadBalancer.getID() != null) {
- loadBalancersBuilder.setUuid(toUuid(loadBalancer.getID()));
- } else {
- LOG.warn("Attempting to write neutron load balancer without UUID");
- }
- return loadBalancersBuilder.build();
- }
-
- public static void registerNewInterface(BundleContext context,
- final DataBroker dataBroker,
- List<ServiceRegistration<?>> registrations) {
- NeutronLoadBalancerInterface neutronLoadBalancerInterface = new NeutronLoadBalancerInterface(dataBroker);
- ServiceRegistration<INeutronLoadBalancerCRUD> neutronLoadBalancerInterfaceRegistration = context.registerService(INeutronLoadBalancerCRUD.class, neutronLoadBalancerInterface, null);
- if(neutronLoadBalancerInterfaceRegistration != null) {
- registrations.add(neutronLoadBalancerInterfaceRegistration);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.crud.impl;
-
-import java.util.List;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.ProviderContext;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancerListener;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronLoadBalancerListenerCRUD;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.lbaasv2.rev150712.lbaas.attributes.Listeners;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
-
-public class NeutronLoadBalancerListenerInterface extends AbstractNeutronInterface<Listeners, NeutronLoadBalancerListener> implements INeutronLoadBalancerListenerCRUD {
-
- NeutronLoadBalancerListenerInterface(final DataBroker dataBroker) {
- super(dataBroker);
- }
-
- @Override
- public boolean neutronLoadBalancerListenerExists(String uuid) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public NeutronLoadBalancerListener getNeutronLoadBalancerListener(
- String uuid) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public List<NeutronLoadBalancerListener> getAllNeutronLoadBalancerListeners() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public boolean addNeutronLoadBalancerListener(
- NeutronLoadBalancerListener input) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public boolean removeNeutronLoadBalancerListener(String uuid) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public boolean updateNeutronLoadBalancerListener(String uuid,
- NeutronLoadBalancerListener delta) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public boolean neutronLoadBalancerListenerInUse(String uuid) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- protected InstanceIdentifier<Listeners> createInstanceIdentifier(
- Listeners item) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- protected Listeners toMd(NeutronLoadBalancerListener neutronObject) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- protected Listeners toMd(String uuid) {
- // TODO Auto-generated method stub
- return null;
- }
-
- public static void registerNewInterface(BundleContext context,
- final DataBroker dataBroker,
- List<ServiceRegistration<?>> registrations) {
- NeutronLoadBalancerListenerInterface neutronLoadBalancerListenerInterface = new NeutronLoadBalancerListenerInterface(dataBroker);
- ServiceRegistration<INeutronLoadBalancerListenerCRUD> neutronLoadBalancerListenerInterfaceRegistration = context.registerService(INeutronLoadBalancerListenerCRUD.class, neutronLoadBalancerListenerInterface, null);
- if(neutronLoadBalancerListenerInterfaceRegistration != null) {
- registrations.add(neutronLoadBalancerListenerInterfaceRegistration);
- }
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.crud.impl;
-
-import com.google.common.collect.ImmutableBiMap;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancerPool;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancer_SessionPersistence;
-import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_ID;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronLoadBalancerPoolCRUD;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolBase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolHttp;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolHttps;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolTcp;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.lbaasv2.rev150712.lbaas.attributes.Pools;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.lbaasv2.rev150712.lbaas.attributes.pools.Pool;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.lbaasv2.rev150712.lbaas.attributes.pools.PoolBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.lbaasv2.rev150712.pool.attributes.SessionPersistenceBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * TODO: Migrate this to consume the MD-SAL data store, so that it can read all the data from data store.
- * No need to worry about the write/update related methods here. OVSDB net-virt will use these CRUD Interface
- * only for reading. We will cleanup these interface/methods later.
- */
-
-public class NeutronLoadBalancerPoolInterface extends AbstractNeutronInterface<Pool, NeutronLoadBalancerPool> implements INeutronLoadBalancerPoolCRUD {
- private static final Logger LOG = LoggerFactory.getLogger(NeutronLoadBalancerPoolInterface.class);
- private ConcurrentMap<String, NeutronLoadBalancerPool> loadBalancerPoolDB = new ConcurrentHashMap<>();
-
- private static final ImmutableBiMap<Class<? extends ProtocolBase>,String> PROTOCOL_MAP
- = new ImmutableBiMap.Builder<Class<? extends ProtocolBase>,String>()
- .put(ProtocolHttp.class,"HTTP")
- .put(ProtocolHttps.class,"HTTPS")
- .put(ProtocolTcp.class,"TCP")
- .build();
-
- NeutronLoadBalancerPoolInterface(final DataBroker dataBroker) {
- super(dataBroker);
- }
-
- @Override
- public boolean neutronLoadBalancerPoolExists(String uuid) {
- return loadBalancerPoolDB.containsKey(uuid);
- }
-
- @Override
- public NeutronLoadBalancerPool getNeutronLoadBalancerPool(String uuid) {
- if (!neutronLoadBalancerPoolExists(uuid)) {
- LOG.debug("No LoadBalancerPool has Been Defined");
- return null;
- }
- return loadBalancerPoolDB.get(uuid);
- }
-
- @Override
- public List<NeutronLoadBalancerPool> getAllNeutronLoadBalancerPools() {
- Set<NeutronLoadBalancerPool> allLoadBalancerPools = new HashSet<>();
- for (Entry<String, NeutronLoadBalancerPool> entry : loadBalancerPoolDB.entrySet()) {
- NeutronLoadBalancerPool loadBalancerPool = entry.getValue();
- allLoadBalancerPools.add(loadBalancerPool);
- }
- LOG.debug("Exiting getLoadBalancerPools, Found {} OpenStackLoadBalancerPool", allLoadBalancerPools.size());
- List<NeutronLoadBalancerPool> ans = new ArrayList<>();
- ans.addAll(allLoadBalancerPools);
- return ans;
- }
-
- @Override
- public boolean addNeutronLoadBalancerPool(NeutronLoadBalancerPool input) {
- if (neutronLoadBalancerPoolExists(input.getID())) {
- return false;
- }
- loadBalancerPoolDB.putIfAbsent(input.getID(), input);
- //TODO: add code to find INeutronLoadBalancerPoolAware services and call newtorkCreated on them
- return true;
- }
-
- @Override
- public boolean removeNeutronLoadBalancerPool(String uuid) {
- if (!neutronLoadBalancerPoolExists(uuid)) {
- return false;
- }
- loadBalancerPoolDB.remove(uuid);
- //TODO: add code to find INeutronLoadBalancerPoolAware services and call newtorkDeleted on them
- return true;
- }
-
- @Override
- public boolean updateNeutronLoadBalancerPool(String uuid, NeutronLoadBalancerPool delta) {
- if (!neutronLoadBalancerPoolExists(uuid)) {
- return false;
- }
- NeutronLoadBalancerPool target = loadBalancerPoolDB.get(uuid);
- return overwrite(target, delta);
- }
-
- @Override
- public boolean neutronLoadBalancerPoolInUse(String loadBalancerPoolUUID) {
- return !neutronLoadBalancerPoolExists(loadBalancerPoolUUID);
- }
-
- @Override
- protected Pool toMd(String uuid) {
- PoolBuilder poolsBuilder = new PoolBuilder();
- poolsBuilder.setUuid(toUuid(uuid));
- return poolsBuilder.build();
- }
-
- @Override
- protected InstanceIdentifier<Pool> createInstanceIdentifier(Pool pools) {
- return InstanceIdentifier.create(Neutron.class)
- .child(Pools.class)
- .child(Pool.class, pools.getKey());
- }
-
- @Override
- protected Pool toMd(NeutronLoadBalancerPool pool) {
- PoolBuilder poolBuilder = new PoolBuilder();
- poolBuilder.setAdminStateUp(pool.getLoadBalancerPoolAdminIsStateIsUp());
- if (pool.getNeutronLoadBalancerPoolHealthMonitorID() != null) {
- poolBuilder.setHealthmonitorId(toUuid(pool.getNeutronLoadBalancerPoolHealthMonitorID()));
- }
- if (pool.getLoadBalancerPoolLbAlgorithm() != null) {
- poolBuilder.setLbAlgorithm(pool.getLoadBalancerPoolLbAlgorithm());
- }
- if (pool.getLoadBalancerPoolListeners() != null) {
- List<Uuid> listListener = new ArrayList<>();
- for (Neutron_ID neutron_id : pool.getLoadBalancerPoolListeners()) {
- listListener.add(toUuid(neutron_id.getID()));
- }
- poolBuilder.setListeners(listListener);
- }
- // because members are another container, we don't want to copy
- // it over, so just skip it here
- if (pool.getLoadBalancerPoolName() != null) {
- poolBuilder.setName(pool.getLoadBalancerPoolName());
- }
- if (pool.getLoadBalancerPoolProtocol() != null) {
- ImmutableBiMap<String, Class<? extends ProtocolBase>> mapper =
- PROTOCOL_MAP.inverse();
- poolBuilder.setProtocol(mapper.get(pool.getLoadBalancerPoolProtocol()));
- }
- if (pool.getLoadBalancerPoolSessionPersistence() != null) {
- NeutronLoadBalancer_SessionPersistence sessionPersistence = pool.getLoadBalancerPoolSessionPersistence();
- SessionPersistenceBuilder sessionPersistenceBuilder = new SessionPersistenceBuilder();
- sessionPersistenceBuilder.setCookieName(sessionPersistence.getCookieName());
- sessionPersistenceBuilder.setType(sessionPersistence.getType());
- poolBuilder.setSessionPersistence(sessionPersistenceBuilder.build());
- }
- if (pool.getLoadBalancerPoolTenantID() != null) {
- poolBuilder.setTenantId(toUuid(pool.getLoadBalancerPoolTenantID()));
- }
- if (pool.getID() != null) {
- poolBuilder.setUuid(toUuid(pool.getID()));
- } else {
- LOG.warn("Attempting to write neutron load balancer pool without UUID");
- }
- return poolBuilder.build();
- }
-
- public static void registerNewInterface(BundleContext context,
- final DataBroker dataBroker,
- List<ServiceRegistration<?>> registrations) {
- NeutronLoadBalancerPoolInterface neutronLoadBalancerPoolInterface = new NeutronLoadBalancerPoolInterface(dataBroker);
- ServiceRegistration<INeutronLoadBalancerPoolCRUD> neutronLoadBalancerPoolInterfaceRegistration = context.registerService(INeutronLoadBalancerPoolCRUD.class, neutronLoadBalancerPoolInterface, null);
- if(neutronLoadBalancerPoolInterfaceRegistration != null) {
- registrations.add(neutronLoadBalancerPoolInterfaceRegistration);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.crud.impl;
-
-import java.util.List;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancerPoolMember;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronLoadBalancerPoolMemberCRUD;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.lbaasv2.rev150712.lbaas.attributes.pools.pool.Members;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
-
-public class NeutronLoadBalancerPoolMemberInterface extends
- AbstractNeutronInterface<Members, NeutronLoadBalancerPoolMember> implements INeutronLoadBalancerPoolMemberCRUD {
-
- NeutronLoadBalancerPoolMemberInterface(final DataBroker dataBroker) {
- super(dataBroker);
- }
-
- @Override
- public boolean neutronLoadBalancerPoolMemberExists(String uuid) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public NeutronLoadBalancerPoolMember getNeutronLoadBalancerPoolMember(
- String uuid) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public List<NeutronLoadBalancerPoolMember> getAllNeutronLoadBalancerPoolMembers() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public boolean addNeutronLoadBalancerPoolMember(
- NeutronLoadBalancerPoolMember input) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public boolean removeNeutronLoadBalancerPoolMember(String uuid) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public boolean updateNeutronLoadBalancerPoolMember(String uuid,
- NeutronLoadBalancerPoolMember delta) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public boolean neutronLoadBalancerPoolMemberInUse(String uuid) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- protected InstanceIdentifier<Members> createInstanceIdentifier(Members item) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- protected Members toMd(NeutronLoadBalancerPoolMember neutronObject) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- protected Members toMd(String uuid) {
- // TODO Auto-generated method stub
- return null;
- }
-
- public static void registerNewInterface(BundleContext context,
- final DataBroker dataBroker,
- List<ServiceRegistration<?>> registrations) {
- NeutronLoadBalancerPoolMemberInterface neutronLoadBalancerPoolMemberInterface = new NeutronLoadBalancerPoolMemberInterface(dataBroker);
- ServiceRegistration<INeutronLoadBalancerPoolMemberCRUD> neutronLoadBalancerPoolMemberInterfaceRegistration = context.registerService(INeutronLoadBalancerPoolMemberCRUD.class, neutronLoadBalancerPoolMemberInterface, null);
- if(neutronLoadBalancerPoolMemberInterfaceRegistration != null) {
- registrations.add(neutronLoadBalancerPoolMemberInterfaceRegistration);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 IBM Corporation 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.netvirt.openstack.netvirt.translator.crud.impl;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.ProviderContext;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronNetworkCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork_Segment;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.ext.rev150712.NetworkL3Extension;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.ext.rev150712.NetworkL3ExtensionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeBase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeFlat;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeGre;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeVlan;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeVxlan;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.Networks;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.networks.Network;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.networks.NetworkBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.provider.ext.rev150712.NetworkProviderExtension;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.provider.ext.rev150712.NetworkProviderExtensionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.provider.ext.rev150712.neutron.networks.network.Segments;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.provider.ext.rev150712.neutron.networks.network.SegmentsBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.ImmutableBiMap;
-
-public class NeutronNetworkInterface extends AbstractNeutronInterface<Network,NeutronNetwork> implements INeutronNetworkCRUD {
- private static final Logger LOG = LoggerFactory.getLogger(NeutronNetworkInterface.class);
-
- private static final ImmutableBiMap<Class<? extends NetworkTypeBase>,String> NETWORK_MAP
- = new ImmutableBiMap.Builder<Class<? extends NetworkTypeBase>,String>()
- .put(NetworkTypeFlat.class,"flat")
- .put(NetworkTypeGre.class,"gre")
- .put(NetworkTypeVlan.class,"vlan")
- .put(NetworkTypeVxlan.class,"vxlan")
- .build();
-
- static private String getNetworkTypeString(Class<? extends NetworkTypeBase> type) {
- String ret = NETWORK_MAP.get(type);
- if (ret == null) {
- ret = "flat";
- }
- return ret;
- }
-
- NeutronNetworkInterface(final DataBroker dataBroker) {
- super(dataBroker);
- }
-
- // IfNBNetworkCRUD methods
-
- @Override
- public boolean networkExists(String uuid) {
- return readMd(createInstanceIdentifier(toMd(uuid))) != null;
- }
-
- @Override
- public NeutronNetwork getNetwork(String uuid) {
- Network network = readMd(createInstanceIdentifier(toMd(uuid)));
- if (network == null) {
- return null;
- }
- return fromMd(network);
- }
-
- @Override
- public List<NeutronNetwork> getAllNetworks() {
- Set<NeutronNetwork> allNetworks = new HashSet<>();
- Networks networks = readMd(createInstanceIdentifier());
- if (networks != null) {
- for (Network network: networks.getNetwork()) {
- allNetworks.add(fromMd(network));
- }
- }
- LOG.debug("Exiting getAllNetworks, Found {} OpenStackNetworks", allNetworks.size());
- List<NeutronNetwork> ans = new ArrayList<>();
- ans.addAll(allNetworks);
- return ans;
- }
-
- @Override
- public boolean addNetwork(NeutronNetwork input) {
- if (networkExists(input.getID())) {
- return false;
- }
- addMd(input);
- return true;
- }
-
- @Override
- public boolean removeNetwork(String uuid) {
- if (!networkExists(uuid)) {
- return false;
- }
- return removeMd(toMd(uuid));
- }
-
- @Override
- public boolean updateNetwork(String uuid, NeutronNetwork delta) {
- if (!networkExists(uuid)) {
- return false;
- }
-/* note: because what we get is *not* a delta but (at this point) the updated
- * object, this is much simpler - just replace the value and update the mdsal
- * with it */
- updateMd(delta);
- return true;
- }
-
- @Override
- public boolean networkInUse(String netUUID) {
- return !networkExists(netUUID);
- }
-
- protected NeutronNetwork fromMd(Network network) {
- NeutronNetwork result = new NeutronNetwork();
- result.setAdminStateUp(network.isAdminStateUp());
- result.setNetworkName(network.getName());
- result.setShared(network.isShared());
- result.setStatus(network.getStatus());
-// todo remove '-' chars as tenant id doesn't use them
- result.setTenantID(network.getTenantId().getValue());
- result.setID(network.getUuid().getValue());
-
- NetworkL3Extension l3Extension = network.getAugmentation(NetworkL3Extension.class);
- result.setRouterExternal(l3Extension.isExternal());
-
- NetworkProviderExtension providerExtension = network.getAugmentation(NetworkProviderExtension.class);
- result.setProviderPhysicalNetwork(providerExtension.getPhysicalNetwork());
- result.setProviderSegmentationID(providerExtension.getSegmentationId());
- result.setProviderNetworkType(getNetworkTypeString(providerExtension.getNetworkType()));
- List<NeutronNetwork_Segment> segments = new ArrayList<>();
- if (providerExtension.getSegments() != null) {
- for (Segments segment: providerExtension.getSegments()) {
- NeutronNetwork_Segment neutronSegment = new NeutronNetwork_Segment();
- neutronSegment.setProviderPhysicalNetwork(segment.getPhysicalNetwork());
- neutronSegment.setProviderSegmentationID(segment.getSegmentationId());
- neutronSegment.setProviderNetworkType(getNetworkTypeString(segment.getNetworkType()));
- segments.add(neutronSegment);
- }
- }
- result.setSegments(segments);
- return result;
- }
-
- private void fillExtensions(NetworkBuilder networkBuilder,
- NeutronNetwork network) {
- NetworkL3ExtensionBuilder l3ExtensionBuilder = new NetworkL3ExtensionBuilder();
- if (network.getRouterExternal() != null) {
- l3ExtensionBuilder.setExternal(network.getRouterExternal());
- }
-
- NetworkProviderExtensionBuilder providerExtensionBuilder = new NetworkProviderExtensionBuilder();
- if (network.getProviderPhysicalNetwork() != null) {
- providerExtensionBuilder.setPhysicalNetwork(network.getProviderPhysicalNetwork());
- }
- if (network.getProviderSegmentationID() != null) {
- providerExtensionBuilder.setSegmentationId(network.getProviderSegmentationID());
- }
- if (network.getProviderNetworkType() != null) {
- ImmutableBiMap<String, Class<? extends NetworkTypeBase>> mapper =
- NETWORK_MAP.inverse();
- providerExtensionBuilder.setNetworkType(mapper.get(network.getProviderNetworkType()));
- }
- if (network.getSegments() != null) {
- List<Segments> segments = new ArrayList<>();
- long count = 0;
- for( NeutronNetwork_Segment segment : network.getSegments()) {
- count++;
- SegmentsBuilder segmentsBuilder = new SegmentsBuilder();
- if (segment.getProviderPhysicalNetwork() != null) {
- segmentsBuilder.setPhysicalNetwork(segment.getProviderPhysicalNetwork());
- }
- if (segment.getProviderSegmentationID() != null) {
- segmentsBuilder.setSegmentationId(segment.getProviderSegmentationID());
- }
- if (segment.getProviderNetworkType() != null) {
- ImmutableBiMap<String, Class<? extends NetworkTypeBase>> mapper =
- NETWORK_MAP.inverse();
- segmentsBuilder.setNetworkType(mapper.get(segment.getProviderNetworkType()));
- }
- segmentsBuilder.setSegmentationIndex(count);
- segments.add(segmentsBuilder.build());
- }
- providerExtensionBuilder.setSegments(segments);
- }
- if (network.getProviderSegmentationID() != null) {
- providerExtensionBuilder.setSegmentationId(network.getProviderSegmentationID());
- }
-
- networkBuilder.addAugmentation(NetworkL3Extension.class,
- l3ExtensionBuilder.build());
- networkBuilder.addAugmentation(NetworkProviderExtension.class,
- providerExtensionBuilder.build());
- }
-
- protected Network toMd(NeutronNetwork network) {
- NetworkBuilder networkBuilder = new NetworkBuilder();
- fillExtensions(networkBuilder, network);
-
- networkBuilder.setAdminStateUp(network.getAdminStateUp());
- if (network.getNetworkName() != null) {
- networkBuilder.setName(network.getNetworkName());
- }
- if (network.getShared() != null) {
- networkBuilder.setShared(network.getShared());
- }
- if (network.getStatus() != null) {
- networkBuilder.setStatus(network.getStatus());
- }
- if (network.getTenantID() != null) {
- networkBuilder.setTenantId(toUuid(network.getTenantID()));
- }
- if (network.getNetworkUUID() != null) {
- networkBuilder.setUuid(toUuid(network.getNetworkUUID()));
- } else {
- LOG.warn("Attempting to write neutron network without UUID");
- }
- return networkBuilder.build();
- }
-
- protected Network toMd(String uuid) {
- NetworkBuilder networkBuilder = new NetworkBuilder();
- networkBuilder.setUuid(toUuid(uuid));
- return networkBuilder.build();
- }
-
- @Override
- protected InstanceIdentifier<Network> createInstanceIdentifier(Network network) {
- return InstanceIdentifier.create(Neutron.class)
- .child(Networks.class)
- .child(Network.class,network.getKey());
- }
-
- protected InstanceIdentifier<Networks> createInstanceIdentifier() {
- return InstanceIdentifier.create(Neutron.class)
- .child(Networks.class);
- }
-
- public static void registerNewInterface(BundleContext context,
- final DataBroker dataBroker,
- List<ServiceRegistration<?>> registrations) {
- NeutronNetworkInterface neutronNetworkInterface = new NeutronNetworkInterface(dataBroker);
- ServiceRegistration<INeutronNetworkCRUD> neutronNetworkInterfaceRegistration = context.registerService(INeutronNetworkCRUD.class, neutronNetworkInterface, null);
- if(neutronNetworkInterfaceRegistration != null) {
- registrations.add(neutronNetworkInterfaceRegistration);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 IBM Corporation 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.netvirt.openstack.netvirt.translator.crud.impl;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort_AllowedAddressPairs;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort_ExtraDHCPOption;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityGroup;
-import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronPortCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSecurityGroupCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.NeutronCRUDInterfaces;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.binding.rev150712.PortBindingExtension;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.binding.rev150712.PortBindingExtensionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.binding.rev150712.binding.attributes.VifDetails;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.binding.rev150712.binding.attributes.VifDetailsBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.AllowedAddressPairs;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.AllowedAddressPairsBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.ExtraDhcpOpts;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.ExtraDhcpOptsBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.FixedIps;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.FixedIpsBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.Ports;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.PortBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.portsecurity.rev150712.PortSecurityExtension;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.portsecurity.rev150712.PortSecurityExtensionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.types.rev160517.IpPrefixOrAddress;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class NeutronPortInterface extends AbstractNeutronInterface<Port, NeutronPort> implements INeutronPortCRUD {
- private static final Logger LOG = LoggerFactory.getLogger(NeutronPortInterface.class);
-
- NeutronPortInterface(final DataBroker dataBroker) {
- super(dataBroker);
- }
-
- // IfNBPortCRUD methods
-
- @Override
- public boolean portExists(String uuid) {
- Port port = readMd(createInstanceIdentifier(toMd(uuid)));
- return port != null;
- }
-
- @Override
- public NeutronPort getPort(String uuid) {
- Port port = readMd(createInstanceIdentifier(toMd(uuid)));
- if (port == null) {
- return null;
- }
- return fromMd(port);
- }
-
- @Override
- public List<NeutronPort> getAllPorts() {
- Set<NeutronPort> allPorts = new HashSet<>();
- Ports ports = readMd(createInstanceIdentifier());
- if (ports != null) {
- for (Port port : ports.getPort()) {
- allPorts.add(fromMd(port));
- }
- }
- LOG.debug("Exiting getAllPorts, Found {} OpenStackPorts", allPorts.size());
- List<NeutronPort> ans = new ArrayList<>();
- ans.addAll(allPorts);
- return ans;
- }
-
- @Override
- public boolean addPort(NeutronPort input) {
- if (portExists(input.getID())) {
- return false;
- }
- addMd(input);
- return true;
- }
-
- @Override
- public boolean removePort(String uuid) {
- if (!portExists(uuid)) {
- return false;
- }
- return removeMd(toMd(uuid));
- }
-
- @Override
- public boolean updatePort(String uuid, NeutronPort delta) {
- if (!portExists(uuid)) {
- return false;
- }
- updateMd(delta);
- return true;
- }
-
- // @deprecated, will be removed in Boron
- @Override
- public boolean macInUse(String macAddress) {
- return false;
- }
-
- // @deprecated, will be removed in Boron
- @Override
- public NeutronPort getGatewayPort(String subnetUUID) {
- return null;
- }
-
- @Override
- protected InstanceIdentifier<Port> createInstanceIdentifier(Port port) {
- return InstanceIdentifier.create(Neutron.class)
- .child(Ports.class)
- .child(Port.class, port.getKey());
- }
-
- protected InstanceIdentifier<Ports> createInstanceIdentifier() {
- return InstanceIdentifier.create(Neutron.class)
- .child(Ports.class);
- }
-
- protected void addExtensions(Port port, NeutronPort result) {
- PortBindingExtension binding = port.getAugmentation(PortBindingExtension.class);
- result.setBindinghostID(binding.getHostId());
- if (binding.getVifDetails() != null) {
- final Map<String, String> details = new HashMap<>(binding.getVifDetails().size());
- for (final VifDetails vifDetail : binding.getVifDetails()) {
- details.put(vifDetail.getDetailsKey(), vifDetail.getValue());
- }
- result.setVIFDetails(details);
- }
- result.setBindingvifType(binding.getVifType());
- result.setBindingvnicType(binding.getVnicType());
- }
-
- private void portSecurityExtension(Port port, NeutronPort result) {
- PortSecurityExtension portSecurity = port.getAugmentation(PortSecurityExtension.class);
- if(portSecurity != null && portSecurity.isPortSecurityEnabled() != null) {
- result.setPortSecurityEnabled(portSecurity.isPortSecurityEnabled());
- }
- }
-
- protected NeutronPort fromMd(Port port) {
- NeutronPort result = new NeutronPort();
- result.setAdminStateUp(port.isAdminStateUp());
- if (port.getAllowedAddressPairs() != null) {
- List<NeutronPort_AllowedAddressPairs> pairs = new ArrayList<>();
- for (AllowedAddressPairs mdPair : port.getAllowedAddressPairs()) {
- NeutronPort_AllowedAddressPairs pair = new NeutronPort_AllowedAddressPairs();
- pair.setIpAddress(String.valueOf(mdPair.getIpAddress().getValue()));
- pair.setMacAddress(mdPair.getMacAddress().getValue());
- pairs.add(pair);
- }
- result.setAllowedAddressPairs(pairs);
- }
- result.setDeviceID(port.getDeviceId());
- result.setDeviceOwner(port.getDeviceOwner());
- if (port.getExtraDhcpOpts() != null) {
- List<NeutronPort_ExtraDHCPOption> options = new ArrayList<>();
- for (ExtraDhcpOpts opt : port.getExtraDhcpOpts()) {
- NeutronPort_ExtraDHCPOption arg = new NeutronPort_ExtraDHCPOption();
- arg.setName(opt.getOptName());
- arg.setValue(opt.getOptValue());
- options.add(arg);
- }
- result.setExtraDHCPOptions(options);
- }
- if (port.getFixedIps() != null) {
- List<Neutron_IPs> ips = new ArrayList<>();
- for (FixedIps mdIP : port.getFixedIps()) {
- Neutron_IPs ip = new Neutron_IPs();
- ip.setIpAddress(String.valueOf(mdIP.getIpAddress().getValue()));
- ip.setSubnetUUID(mdIP.getSubnetId().getValue());
- ips.add(ip);
- }
- result.setFixedIPs(ips);
- }
- result.setMacAddress(port.getMacAddress().getValue());
- result.setName(port.getName());
- result.setNetworkUUID(String.valueOf(port.getNetworkId().getValue()));
- if (port.getSecurityGroups() != null) {
- Set<NeutronSecurityGroup> allGroups = new HashSet<>();
- NeutronCRUDInterfaces interfaces = new NeutronCRUDInterfaces().fetchINeutronSecurityGroupCRUD(this);
- INeutronSecurityGroupCRUD sgIf = interfaces.getSecurityGroupInterface();
- for (Uuid sgUuid : port.getSecurityGroups()) {
- NeutronSecurityGroup secGroup = sgIf.getNeutronSecurityGroup(sgUuid.getValue());
- if (secGroup != null) {
- allGroups.add(sgIf.getNeutronSecurityGroup(sgUuid.getValue()));
- }
- }
- List<NeutronSecurityGroup> groups = new ArrayList<>();
- groups.addAll(allGroups);
- result.setSecurityGroups(groups);
- }
- result.setStatus(port.getStatus());
- if (port.getTenantId() != null) {
- result.setTenantID(String.valueOf(port.getTenantId().getValue()).replace("-", ""));
- }
- result.setPortUUID(String.valueOf(port.getUuid().getValue()));
- addExtensions(port, result);
- portSecurityExtension(port, result);
- return result;
- }
-
- @Override
- protected Port toMd(NeutronPort neutronPort) {
- PortBindingExtensionBuilder bindingBuilder = new PortBindingExtensionBuilder();
- if (neutronPort.getBindinghostID() != null) {
- bindingBuilder.setHostId(neutronPort.getBindinghostID());
- }
- if (neutronPort.getVIFDetails() != null) {
- final Map<String, String> vifDetails = neutronPort.getVIFDetails();
- final List<VifDetails> listVifDetail = new ArrayList<>(vifDetails.size());
- for (final Map.Entry<String, String> vifDetail : vifDetails.entrySet()) {
- final VifDetailsBuilder vifDetailsBuilder = new VifDetailsBuilder();
- if (vifDetail.getKey() != null) {
- vifDetailsBuilder.setDetailsKey(vifDetail.getKey());
- }
- if (vifDetail.getValue() != null) {
- vifDetailsBuilder.setValue(vifDetail.getValue());
- }
- listVifDetail.add(vifDetailsBuilder.build());
- }
- bindingBuilder.setVifDetails(listVifDetail);
- }
- if (neutronPort.getBindingvifType() != null) {
- bindingBuilder.setVifType(neutronPort.getBindingvifType());
- }
- if (neutronPort.getBindingvnicType() != null) {
- bindingBuilder.setVnicType(neutronPort.getBindingvnicType());
- }
-
- PortSecurityExtensionBuilder portSecurityBuilder = new PortSecurityExtensionBuilder();
- if (neutronPort.getPortSecurityEnabled() != null) {
- portSecurityBuilder.setPortSecurityEnabled(neutronPort.getPortSecurityEnabled());
- }
- PortBuilder portBuilder = new PortBuilder();
- portBuilder.addAugmentation(PortBindingExtension.class,
- bindingBuilder.build());
- portBuilder.addAugmentation(PortSecurityExtension.class, portSecurityBuilder.build());
- portBuilder.setAdminStateUp(neutronPort.isAdminStateUp());
- if(neutronPort.getAllowedAddressPairs() != null) {
- List<AllowedAddressPairs> listAllowedAddressPairs = new ArrayList<>();
- for (NeutronPort_AllowedAddressPairs allowedAddressPairs : neutronPort.getAllowedAddressPairs()) {
- AllowedAddressPairsBuilder allowedAddressPairsBuilder = new AllowedAddressPairsBuilder();
- allowedAddressPairsBuilder.setIpAddress(new IpPrefixOrAddress(allowedAddressPairs.getIpAddress().toCharArray()));
- allowedAddressPairsBuilder.setMacAddress(new MacAddress(allowedAddressPairs.getMacAddress()));
- listAllowedAddressPairs.add(allowedAddressPairsBuilder.build());
- }
- portBuilder.setAllowedAddressPairs(listAllowedAddressPairs);
- }
- if (neutronPort.getDeviceID() != null) {
- portBuilder.setDeviceId(neutronPort.getDeviceID());
- }
- if (neutronPort.getDeviceOwner() != null) {
- portBuilder.setDeviceOwner(neutronPort.getDeviceOwner());
- }
- if (neutronPort.getExtraDHCPOptions() != null) {
- List<ExtraDhcpOpts> listExtraDHCPOptions = new ArrayList<>();
- for (NeutronPort_ExtraDHCPOption extraDHCPOption : neutronPort.getExtraDHCPOptions()) {
- ExtraDhcpOptsBuilder extraDHCPOptsBuilder = new ExtraDhcpOptsBuilder();
- extraDHCPOptsBuilder.setOptName(extraDHCPOption.getName());
- extraDHCPOptsBuilder.setOptValue(extraDHCPOption.getValue());
- listExtraDHCPOptions.add(extraDHCPOptsBuilder.build());
- }
- portBuilder.setExtraDhcpOpts(listExtraDHCPOptions);
- }
- if (neutronPort.getFixedIPs() != null) {
- List<FixedIps> listNeutronIPs = new ArrayList<>();
- for (Neutron_IPs neutron_IPs : neutronPort.getFixedIPs()) {
- FixedIpsBuilder fixedIpsBuilder = new FixedIpsBuilder();
- fixedIpsBuilder.setIpAddress(new IpAddress(neutron_IPs.getIpAddress().toCharArray()));
- fixedIpsBuilder.setSubnetId(toUuid(neutron_IPs.getSubnetUUID()));
- listNeutronIPs.add(fixedIpsBuilder.build());
- }
- portBuilder.setFixedIps(listNeutronIPs);
- }
- if (neutronPort.getMacAddress() != null) {
- portBuilder.setMacAddress(new MacAddress(neutronPort.getMacAddress()));
- }
- if (neutronPort.getName() != null) {
- portBuilder.setName(neutronPort.getName());
- }
- if (neutronPort.getNetworkUUID() != null) {
- portBuilder.setNetworkId(toUuid(neutronPort.getNetworkUUID()));
- }
- if (neutronPort.getSecurityGroups() != null) {
- List<Uuid> listSecurityGroups = new ArrayList<>();
- for (NeutronSecurityGroup neutronSecurityGroup : neutronPort.getSecurityGroups()) {
- listSecurityGroups.add(toUuid(neutronSecurityGroup.getID()));
- }
- portBuilder.setSecurityGroups(listSecurityGroups);
- }
- if (neutronPort.getStatus() != null) {
- portBuilder.setStatus(neutronPort.getStatus());
- }
- if (neutronPort.getTenantID() != null) {
- portBuilder.setTenantId(toUuid(neutronPort.getTenantID()));
- }
- if (neutronPort.getPortUUID() != null) {
- portBuilder.setUuid(toUuid(neutronPort.getPortUUID()));
- } else {
- LOG.warn("Attempting to write neutron port without UUID");
- }
- return portBuilder.build();
- }
-
- @Override
- protected Port toMd(String uuid) {
- PortBuilder portBuilder = new PortBuilder();
- portBuilder.setUuid(toUuid(uuid));
- return portBuilder.build();
- }
-
- public static void registerNewInterface(BundleContext context,
- final DataBroker dataBroker,
- List<ServiceRegistration<?>> registrations) {
- NeutronPortInterface neutronPortInterface = new NeutronPortInterface(dataBroker);
- ServiceRegistration<INeutronPortCRUD> neutronPortInterfaceRegistration = context.registerService(INeutronPortCRUD.class, neutronPortInterface, null);
- if(neutronPortInterfaceRegistration != null) {
- registrations.add(neutronPortInterfaceRegistration);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 IBM Corporation 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.netvirt.openstack.netvirt.translator.crud.impl;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronRouterCRUD;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronRouter;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronRouter_NetworkReference;
-import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.l3.attributes.Routes;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.Routers;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.routers.Router;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.routers.RouterBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.routers.router.ExternalGatewayInfo;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.routers.router.ExternalGatewayInfoBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.routers.router.external_gateway_info.ExternalFixedIps;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.routers.router.external_gateway_info.ExternalFixedIpsBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class NeutronRouterInterface extends AbstractNeutronInterface<Router, NeutronRouter> implements INeutronRouterCRUD {
- private static final Logger LOG = LoggerFactory.getLogger(NeutronRouterInterface.class);
- // methods needed for creating caches
-
-
- NeutronRouterInterface(final DataBroker dataBroker) {
- super(dataBroker);
- }
-
-
- // IfNBRouterCRUD Interface methods
-
- @Override
- public boolean routerExists(String uuid) {
- Router router = readMd(createInstanceIdentifier(toMd(uuid)));
- return router != null;
- }
-
- @Override
- public NeutronRouter getRouter(String uuid) {
- Router router = readMd(createInstanceIdentifier(toMd(uuid)));
- if (router == null) {
- return null;
- }
- return fromMd(router);
- }
-
- @Override
- public List<NeutronRouter> getAllRouters() {
- Set<NeutronRouter> allRouters = new HashSet<>();
- Routers routers = readMd(createInstanceIdentifier());
- if (routers != null) {
- for (Router router: routers.getRouter()) {
- allRouters.add(fromMd(router));
- }
- }
- LOG.debug("Exiting getAllRouters, Found {} Routers", allRouters.size());
- List<NeutronRouter> ans = new ArrayList<>();
- ans.addAll(allRouters);
- return ans;
- }
-
- @Override
- public boolean addRouter(NeutronRouter input) {
- if (routerExists(input.getID())) {
- return false;
- }
- addMd(input);
- return true;
- }
-
- @Override
- public boolean removeRouter(String uuid) {
- if (!routerExists(uuid)) {
- return false;
- }
- return removeMd(toMd(uuid));
- }
-
- @Override
- public boolean updateRouter(String uuid, NeutronRouter delta) {
- if (!routerExists(uuid)) {
- return false;
- }
- updateMd(delta);
- return true;
- }
-
- @Override
- public boolean routerInUse(String routerUUID) {
- return !routerExists(routerUUID);
- }
-
- @Override
- protected Router toMd(NeutronRouter router) {
-
- RouterBuilder routerBuilder = new RouterBuilder();
-
- if (router.getRouterUUID() != null) {
- routerBuilder.setUuid(toUuid(router.getRouterUUID()));
- }
- if (router.getName() != null) {
- routerBuilder.setName(router.getName());
- }
- if (router.getTenantID() != null && !router.getTenantID().isEmpty()) {
- routerBuilder.setTenantId(toUuid(router.getTenantID()));
- }
- if (router.getStatus() != null) {
- routerBuilder.setStatus(router.getStatus());
- }
- if (router.getGatewayPortId() != null && !router.getGatewayPortId().isEmpty()) {
- routerBuilder.setGatewayPortId(toUuid(router.getGatewayPortId()));
- }
- routerBuilder.setAdminStateUp(router.getAdminStateUp());
- routerBuilder.setDistributed(router.getDistributed());
- if (router.getRoutes() != null) {
- List<Routes> routes = new ArrayList<>();
- for (Routes route : router.getRoutes()) {
- routes.add(route);
- }
- routerBuilder.setRoutes(routes);
- }
- if (router.getExternalGatewayInfo() != null) {
- ExternalGatewayInfo externalGatewayInfo = null;
- List<NeutronRouter_NetworkReference> neutronRouter_NetworkReferences = new ArrayList<>();
- neutronRouter_NetworkReferences.add(router.getExternalGatewayInfo());
- for (NeutronRouter_NetworkReference externalGatewayInfos : neutronRouter_NetworkReferences) {
- ExternalGatewayInfoBuilder builder = new ExternalGatewayInfoBuilder();
- builder.setEnableSnat(externalGatewayInfos.getEnableSNAT());
- builder.setExternalNetworkId(toUuid(externalGatewayInfos.getNetworkID()));
- if (externalGatewayInfos.getExternalFixedIPs() != null) {
- List<ExternalFixedIps> externalFixedIps = new ArrayList<>();
- for (Neutron_IPs eIP : externalGatewayInfos.getExternalFixedIPs()) {
- ExternalFixedIpsBuilder eFixedIpBuilder = new ExternalFixedIpsBuilder();
- eFixedIpBuilder.setIpAddress(new IpAddress(eIP.getIpAddress().toCharArray()));
- eFixedIpBuilder.setSubnetId(toUuid(eIP.getSubnetUUID()));
- externalFixedIps.add(eFixedIpBuilder.build());
- }
- builder.setExternalFixedIps(externalFixedIps);
- }
- externalGatewayInfo = builder.build();
- }
- routerBuilder.setExternalGatewayInfo(externalGatewayInfo);
- }
- if (router.getID() != null) {
- routerBuilder.setUuid(toUuid(router.getID()));
- } else {
- LOG.warn("Attempting to write neutron router without UUID");
- }
- return routerBuilder.build();
- }
-
- @Override
- protected InstanceIdentifier<Router> createInstanceIdentifier(Router router) {
- return InstanceIdentifier.create(Neutron.class)
- .child(Routers.class)
- .child(Router.class, router.getKey());
- }
-
- protected InstanceIdentifier<Routers> createInstanceIdentifier() {
- return InstanceIdentifier.create(Neutron.class).child(Routers.class);
- }
-
- @Override
- protected Router toMd(String uuid) {
- RouterBuilder routerBuilder = new RouterBuilder();
- routerBuilder.setUuid(toUuid(uuid));
- return routerBuilder.build();
- }
-
- public NeutronRouter fromMd(Router router) {
- NeutronRouter result = new NeutronRouter();
- result.setID(String.valueOf(router.getUuid().getValue()));
- result.setName(router.getName());
- result.setTenantID(String.valueOf(router.getTenantId().getValue()));
- result.setAdminStateUp(router.isAdminStateUp());
- result.setStatus(router.getStatus());
- result.setDistributed(router.isDistributed());
- if (router.getGatewayPortId() != null) {
- result.setGatewayPortId(String.valueOf(router.getGatewayPortId().getValue()));
- }
- if (router.getRoutes() != null) {
- List<Routes> routes = new ArrayList<>();
- for (Routes route : router.getRoutes()) {
- routes.add(route);
- }
- result.setRoutes(routes);
- }
-
- if (router.getExternalGatewayInfo() != null) {
- NeutronRouter_NetworkReference extGwInfo = new NeutronRouter_NetworkReference();
- extGwInfo.setNetworkID(String.valueOf(router.getExternalGatewayInfo().getExternalNetworkId().getValue()));
- extGwInfo.setEnableSNAT(router.getExternalGatewayInfo().isEnableSnat());
- if (router.getExternalGatewayInfo().getExternalFixedIps() != null) {
- List<Neutron_IPs> fixedIPs = new ArrayList<>();
- for (ExternalFixedIps mdFixedIP : router.getExternalGatewayInfo().getExternalFixedIps()) {
- Neutron_IPs fixedIP = new Neutron_IPs();
- fixedIP.setSubnetUUID(String.valueOf(mdFixedIP.getSubnetId().getValue()));
- fixedIP.setIpAddress(String.valueOf(mdFixedIP.getIpAddress().getValue()));
- fixedIPs.add(fixedIP);
- }
- extGwInfo.setExternalFixedIPs(fixedIPs);
- }
- result.setExternalGatewayInfo(extGwInfo);
- }
-
- return result;
- }
-
- public static void registerNewInterface(BundleContext context,
- final DataBroker dataBroker,
- List<ServiceRegistration<?>> registrations) {
- NeutronRouterInterface neutronRouterInterface = new NeutronRouterInterface(dataBroker);
- ServiceRegistration<INeutronRouterCRUD> neutronRouterInterfaceRegistration = context
- .registerService(INeutronRouterCRUD.class,neutronRouterInterface, null);
- if (neutronRouterInterfaceRegistration != null) {
- registrations.add(neutronRouterInterfaceRegistration);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.crud.impl;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityGroup;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityRule;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSecurityGroupCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSecurityRuleCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.NeutronCRUDInterfaces;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.SecurityGroups;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.security.groups.SecurityGroup;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.security.groups.SecurityGroupBuilder;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-
-public class NeutronSecurityGroupInterface extends AbstractNeutronInterface<SecurityGroup,NeutronSecurityGroup> implements INeutronSecurityGroupCRUD {
-
- private static final Logger LOG = LoggerFactory.getLogger(NeutronSecurityGroupInterface.class);
-
- NeutronSecurityGroupInterface(final DataBroker dataBroker) {
- super(dataBroker);
- }
-
- @Override
- public boolean neutronSecurityGroupExists(String uuid) {
- return readMd(createInstanceIdentifier(toMd(uuid))) != null;
- }
-
- @Override
- public NeutronSecurityGroup getNeutronSecurityGroup(String uuid) {
- SecurityGroup group = readMd(createInstanceIdentifier(toMd(uuid)));
- if (group == null) {
- return null;
- }
- return fromMd(group);
- }
-
- @Override
- public List<NeutronSecurityGroup> getAllNeutronSecurityGroups() {
- Set<NeutronSecurityGroup> allSecurityGroups = new HashSet<>();
- SecurityGroups groups = readMd(createInstanceIdentifier());
- if (groups != null) {
- for (SecurityGroup group: groups.getSecurityGroup()) {
- allSecurityGroups.add(fromMd(group));
- }
- }
- LOG.debug("Exiting getSecurityGroups, Found {} OpenStackSecurityGroup", allSecurityGroups.size());
- List<NeutronSecurityGroup> ans = new ArrayList<>();
- ans.addAll(allSecurityGroups);
- return ans;
- }
-
- @Override
- public boolean addNeutronSecurityGroup(NeutronSecurityGroup input) {
- if (neutronSecurityGroupExists(input.getID())) {
- return false;
- }
- addMd(input);
- return true;
- }
-
- @Override
- public boolean removeNeutronSecurityGroup(String uuid) {
- if (!neutronSecurityGroupExists(uuid)) {
- return false;
- }
- removeMd(toMd(uuid));
- return true;
- }
-
- @Override
- public boolean updateNeutronSecurityGroup(String uuid, NeutronSecurityGroup delta) {
- if (!neutronSecurityGroupExists(uuid)) {
- return false;
- }
- updateMd(delta);
- return true;
- }
-
- @Override
- public boolean neutronSecurityGroupInUse(String securityGroupUUID) {
- return !neutronSecurityGroupExists(securityGroupUUID);
- }
-
- protected NeutronSecurityGroup fromMd(SecurityGroup group) {
- NeutronSecurityGroup answer = new NeutronSecurityGroup();
- if (group.getName() != null) {
- answer.setSecurityGroupName(group.getName());
- }
- if (group.getTenantId() != null) {
- answer.setSecurityGroupTenantID(group.getTenantId().getValue().replace("-",""));
- }
- if (group.getUuid() != null) {
- answer.setID(group.getUuid().getValue());
- }
- return answer;
- }
-
- @Override
- protected SecurityGroup toMd(NeutronSecurityGroup securityGroup) {
- SecurityGroupBuilder securityGroupBuilder = new SecurityGroupBuilder();
- if (securityGroup.getSecurityGroupName() != null) {
- securityGroupBuilder.setName(securityGroup.getSecurityGroupName());
- }
- if (securityGroup.getSecurityGroupTenantID() != null) {
- securityGroupBuilder.setTenantId(toUuid(securityGroup.getSecurityGroupTenantID()));
- }
- if (securityGroup.getID() != null) {
- securityGroupBuilder.setUuid(toUuid(securityGroup.getID()));
- } else {
- LOG.warn("Attempting to write neutron securityGroup without UUID");
- }
-
- return securityGroupBuilder.build();
- }
-
- @Override
- protected InstanceIdentifier<SecurityGroup> createInstanceIdentifier(SecurityGroup securityGroup) {
- return InstanceIdentifier.create(Neutron.class)
- .child(SecurityGroups.class).child(SecurityGroup.class,
- securityGroup.getKey());
- }
-
- protected InstanceIdentifier<SecurityGroups> createInstanceIdentifier() {
- return InstanceIdentifier.create(Neutron.class)
- .child(SecurityGroups.class);
- }
-
- @Override
- protected SecurityGroup toMd(String uuid) {
- SecurityGroupBuilder securityGroupBuilder = new SecurityGroupBuilder();
- securityGroupBuilder.setUuid(toUuid(uuid));
- return securityGroupBuilder.build();
- }
-
- public static void registerNewInterface(BundleContext context,
- final DataBroker dataBroker,
- List<ServiceRegistration<?>> registrations) {
- NeutronSecurityGroupInterface neutronSecurityGroupInterface = new NeutronSecurityGroupInterface(dataBroker);
- ServiceRegistration<INeutronSecurityGroupCRUD> neutronSecurityGroupInterfaceRegistration = context.registerService(INeutronSecurityGroupCRUD.class, neutronSecurityGroupInterface, null);
- if(neutronSecurityGroupInterfaceRegistration != null) {
- registrations.add(neutronSecurityGroupInterfaceRegistration);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.crud.impl;
-
-import com.google.common.collect.ImmutableBiMap;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityGroup;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityRule;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSecurityGroupCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSecurityRuleCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.NeutronCRUDInterfaces;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpPrefix;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionBase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionEgress;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionIngress;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeBase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeV4;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeV6;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolBase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolIcmp;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolIcmpV6;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolTcp;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolUdp;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.NeutronUtils;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.SecurityRuleAttributes;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.SecurityRules;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRule;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRuleBuilder;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-
-public class NeutronSecurityRuleInterface extends AbstractNeutronInterface<SecurityRule, NeutronSecurityRule> implements INeutronSecurityRuleCRUD {
-
- private static final Logger LOG = LoggerFactory.getLogger(NeutronSecurityRuleInterface.class);
-
- private static final ImmutableBiMap<Class<? extends DirectionBase>, String> DIRECTION_MAP = ImmutableBiMap.of(
- DirectionEgress.class, NeutronSecurityRule.DIRECTION_EGRESS,
- DirectionIngress.class, NeutronSecurityRule.DIRECTION_INGRESS);
- private static final ImmutableBiMap<Class<? extends ProtocolBase>, String> PROTOCOL_MAP = ImmutableBiMap.of(
- ProtocolIcmp.class, NeutronSecurityRule.PROTOCOL_ICMP,
- ProtocolTcp.class, NeutronSecurityRule.PROTOCOL_TCP,
- ProtocolUdp.class, NeutronSecurityRule.PROTOCOL_UDP,
- ProtocolIcmpV6.class, NeutronSecurityRule.PROTOCOL_ICMPV6);
- private static final ImmutableBiMap<Class<? extends EthertypeBase>,String> ETHERTYPE_MAP = ImmutableBiMap.of(
- EthertypeV4.class, NeutronSecurityRule.ETHERTYPE_IPV4,
- EthertypeV6.class, NeutronSecurityRule.ETHERTYPE_IPV6);
-
- NeutronSecurityRuleInterface(final DataBroker dataBroker) {
- super(dataBroker);
- }
-
- @Override
- public boolean neutronSecurityRuleExists(String uuid) {
- SecurityRule rule = readMd(createInstanceIdentifier(toMd(uuid)));
- return rule != null;
- }
-
- @Override
- public NeutronSecurityRule getNeutronSecurityRule(String uuid) {
- SecurityRule rule = readMd(createInstanceIdentifier(toMd(uuid)));
- if (rule == null) {
- return null;
- }
- return fromMd(rule);
- }
-
- @Override
- public List<NeutronSecurityRule> getAllNeutronSecurityRules() {
- Set<NeutronSecurityRule> allSecurityRules = new HashSet<>();
- SecurityRules rules = readMd(createInstanceIdentifier());
- if (rules != null) {
- for (SecurityRule rule: rules.getSecurityRule()) {
- allSecurityRules.add(fromMd(rule));
- }
- }
- LOG.debug("Exiting getSecurityRule, Found {} OpenStackSecurityRule", allSecurityRules.size());
- return new ArrayList<>(allSecurityRules);
- }
-
- @Override
- public boolean addNeutronSecurityRule(NeutronSecurityRule input) {
- if (neutronSecurityRuleExists(input.getID())) {
- return false;
- }
- addMd(input);
- return true;
- }
-
- @Override
- public boolean removeNeutronSecurityRule(String uuid) {
- if (!neutronSecurityRuleExists(uuid)) {
- return false;
- }
- removeMd(toMd(uuid));
- return true;
- }
-
- @Override
- public boolean updateNeutronSecurityRule(String uuid, NeutronSecurityRule delta) {
- if (!neutronSecurityRuleExists(uuid)) {
- return false;
- }
- updateMd(delta);
- return true;
- }
-
- @Override
- public boolean neutronSecurityRuleInUse(String securityRuleUUID) {
- return !neutronSecurityRuleExists(securityRuleUUID);
- }
-
- protected NeutronSecurityRule fromMd(SecurityRule rule) {
- NeutronSecurityRule answer = new NeutronSecurityRule();
- if (rule.getTenantId() != null) {
- answer.setSecurityRuleTenantID(rule.getTenantId().getValue().replace("-",""));
- }
- if (rule.getDirection() != null) {
- answer.setSecurityRuleDirection(DIRECTION_MAP.get(rule.getDirection()));
- }
- if (rule.getSecurityGroupId() != null) {
- answer.setSecurityRuleGroupID(rule.getSecurityGroupId().getValue());
- }
- if (rule.getRemoteGroupId() != null) {
- answer.setSecurityRemoteGroupID(rule.getRemoteGroupId().getValue());
- }
- if (rule.getRemoteIpPrefix() != null) {
- answer.setSecurityRuleRemoteIpPrefix(rule.getRemoteIpPrefix().getIpv4Prefix() != null?
- rule.getRemoteIpPrefix().getIpv4Prefix().getValue():rule.getRemoteIpPrefix().getIpv6Prefix().getValue());
- }
- if (rule.getProtocol() != null) {
- SecurityRuleAttributes.Protocol protocol = rule.getProtocol();
- if (protocol.getUint8() != null) {
- // uint8
- answer.setSecurityRuleProtocol(protocol.getUint8().toString());
- } else {
- // symbolic protocol name
- answer.setSecurityRuleProtocol(NeutronUtils.ProtocolMapper.getName(protocol.getIdentityref()));
- }
- }
- if (rule.getEthertype() != null) {
- answer.setSecurityRuleEthertype(ETHERTYPE_MAP.get(rule.getEthertype()));
- }
- if (rule.getPortRangeMin() != null) {
- answer.setSecurityRulePortMin(rule.getPortRangeMin());
- }
- if (rule.getPortRangeMax() != null) {
- answer.setSecurityRulePortMax(rule.getPortRangeMax());
- }
- if (rule.getUuid() != null) {
- answer.setID(rule.getUuid().getValue());
- }
- return answer;
- }
-
- @Override
- protected SecurityRule toMd(NeutronSecurityRule securityRule) {
- SecurityRuleBuilder securityRuleBuilder = new SecurityRuleBuilder();
-
- if (securityRule.getSecurityRuleTenantID() != null) {
- securityRuleBuilder.setTenantId(toUuid(securityRule.getSecurityRuleTenantID()));
- }
- if (securityRule.getSecurityRuleDirection() != null) {
- ImmutableBiMap<String, Class<? extends DirectionBase>> mapper =
- DIRECTION_MAP.inverse();
- securityRuleBuilder.setDirection(mapper.get(securityRule.getSecurityRuleDirection()));
- }
- if (securityRule.getSecurityRuleGroupID() != null) {
- securityRuleBuilder.setSecurityGroupId(toUuid(securityRule.getSecurityRuleGroupID()));
- }
- if (securityRule.getSecurityRemoteGroupID() != null) {
- securityRuleBuilder.setRemoteGroupId(toUuid(securityRule.getSecurityRemoteGroupID()));
- }
- if (securityRule.getSecurityRuleRemoteIpPrefix() != null) {
- securityRuleBuilder.setRemoteIpPrefix(new IpPrefix(securityRule.getSecurityRuleRemoteIpPrefix().toCharArray()));
- }
- if (securityRule.getSecurityRuleProtocol() != null) {
- String protocolString = securityRule.getSecurityRuleProtocol();
- SecurityRuleAttributes.Protocol protocol = new SecurityRuleAttributes.Protocol(protocolString.toCharArray());
- securityRuleBuilder.setProtocol(protocol);
- }
- if (securityRule.getSecurityRuleEthertype() != null) {
- ImmutableBiMap<String, Class<? extends EthertypeBase>> mapper =
- ETHERTYPE_MAP.inverse();
- securityRuleBuilder.setEthertype(mapper.get(securityRule.getSecurityRuleEthertype()));
- }
- if (securityRule.getSecurityRulePortMin() != null) {
- securityRuleBuilder.setPortRangeMin(securityRule.getSecurityRulePortMin());
- }
- if (securityRule.getSecurityRulePortMax() != null) {
- securityRuleBuilder.setPortRangeMax(securityRule.getSecurityRulePortMax());
- }
- if (securityRule.getID() != null) {
- securityRuleBuilder.setUuid(toUuid(securityRule.getID()));
- } else {
- LOG.warn("Attempting to write neutron securityRule without UUID");
- }
- return securityRuleBuilder.build();
- }
-
- @Override
- protected InstanceIdentifier<SecurityRule> createInstanceIdentifier(SecurityRule securityRule) {
- return InstanceIdentifier.create(Neutron.class)
- .child(SecurityRules.class).child(SecurityRule.class,
- securityRule.getKey());
- }
-
- protected InstanceIdentifier<SecurityRules> createInstanceIdentifier() {
- return InstanceIdentifier.create(Neutron.class)
- .child(SecurityRules.class);
- }
-
- @Override
- protected SecurityRule toMd(String uuid) {
- SecurityRuleBuilder securityRuleBuilder = new SecurityRuleBuilder();
- securityRuleBuilder.setUuid(toUuid(uuid));
- return securityRuleBuilder.build();
- }
-
- public static void registerNewInterface(BundleContext context,
- final DataBroker dataBroker,
- List<ServiceRegistration<?>> registrations) {
- NeutronSecurityRuleInterface neutronSecurityRuleInterface = new NeutronSecurityRuleInterface(dataBroker);
- ServiceRegistration<INeutronSecurityRuleCRUD> neutronSecurityRuleInterfaceRegistration = context.registerService(INeutronSecurityRuleCRUD.class, neutronSecurityRuleInterface, null);
- if(neutronSecurityRuleInterfaceRegistration != null) {
- registrations.add(neutronSecurityRuleInterfaceRegistration);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 IBM Corporation 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.netvirt.openstack.netvirt.translator.crud.impl;
-
-import com.google.common.collect.ImmutableBiMap;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSubnet;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSubnetIPAllocationPool;
-import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronPortCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSubnetCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.NeutronCRUDInterfaces;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpPrefix;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.Dhcpv6Base;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.Dhcpv6Off;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.Dhcpv6Slaac;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.Dhcpv6Stateful;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.Dhcpv6Stateless;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.IpVersionBase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.IpVersionV4;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.IpVersionV6;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnet.attributes.AllocationPools;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnet.attributes.AllocationPoolsBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.Subnets;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.SubnetBuilder;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class NeutronSubnetInterface extends AbstractNeutronInterface<Subnet, NeutronSubnet> implements INeutronSubnetCRUD {
- private static final Logger LOG = LoggerFactory.getLogger(NeutronSubnetInterface.class);
-
- private static final ImmutableBiMap<Class<? extends IpVersionBase>,Integer> IPV_MAP
- = new ImmutableBiMap.Builder<Class<? extends IpVersionBase>,Integer>()
- .put(IpVersionV4.class, 4)
- .put(IpVersionV6.class, 6)
- .build();
-
- private static final ImmutableBiMap<Class<? extends Dhcpv6Base>,String> DHCPV6_MAP
- = new ImmutableBiMap.Builder<Class<? extends Dhcpv6Base>,String>()
- .put(Dhcpv6Off.class,"off")
- .put(Dhcpv6Stateful.class,"dhcpv6-stateful")
- .put(Dhcpv6Slaac.class,"slaac")
- .put(Dhcpv6Stateless.class,"dhcpv6-stateless")
- .build();
-
- NeutronSubnetInterface(final DataBroker dataBroker) {
- super(dataBroker);
- }
-
- // IfNBSubnetCRUD methods
-
- @Override
- public boolean subnetExists(String uuid) {
- return readMd(createInstanceIdentifier(toMd(uuid))) != null;
- }
-
- @Override
- public NeutronSubnet getSubnet(String uuid) {
- Subnet subnet = readMd(createInstanceIdentifier(toMd(uuid)));
- if (subnet == null) {
- return null;
- }
- return fromMd(subnet);
- }
-
- @Override
- public List<NeutronSubnet> getAllSubnets() {
- Set<NeutronSubnet> allSubnets = new HashSet<>();
- Subnets subnets = readMd(createInstanceIdentifier());
- if (subnets != null) {
- for (Subnet subnet: subnets.getSubnet()) {
- allSubnets.add(fromMd(subnet));
- }
- }
- LOG.debug("Exiting getAllSubnets, Found {} OpenStackSubnets", allSubnets.size());
- List<NeutronSubnet> ans = new ArrayList<>();
- ans.addAll(allSubnets);
- return ans;
- }
-
- @Override
- public boolean addSubnet(NeutronSubnet input) {
- String id = input.getID();
- if (subnetExists(id)) {
- return false;
- }
- addMd(input);
- return true;
- }
-
- @Override
- public boolean removeSubnet(String uuid) {
- NeutronSubnet target = getSubnet(uuid);
- if (target == null) {
- return false;
- }
- removeMd(toMd(uuid));
- return true;
- }
-
- @Override
- public boolean updateSubnet(String uuid, NeutronSubnet delta) {
- if (!subnetExists(uuid)) {
- return false;
- }
-/* note: because what we get is *not* a delta but (at this point) the updated
- * object, this is much simpler - just replace the value and update the mdsal
- * with it */
- updateMd(delta);
- return true;
- }
-
-// note: this is being set to false in preparation for deprecation and removal
- @Override
- public boolean subnetInUse(String subnetUUID) {
- return false;
- }
-
- protected NeutronSubnet fromMd(Subnet subnet) {
- NeutronSubnet result = new NeutronSubnet();
- result.setName(subnet.getName());
- result.setTenantID(String.valueOf(subnet.getTenantId().getValue()).replace("-",""));
- result.setNetworkUUID(subnet.getNetworkId().getValue());
- result.setIpVersion(IPV_MAP.get(subnet.getIpVersion()));
- result.setCidr(String.valueOf(subnet.getCidr().getValue()));
- result.setIpV6RaMode(DHCPV6_MAP.get(subnet.getIpv6RaMode()));
- result.setIpV6AddressMode(DHCPV6_MAP.get(subnet.getIpv6AddressMode()));
- result.setEnableDHCP(subnet.isEnableDhcp());
- if (subnet.getAllocationPools() != null) {
- List<NeutronSubnetIPAllocationPool> allocationPools = new ArrayList<>();
- for (AllocationPools allocationPool : subnet.getAllocationPools()) {
- NeutronSubnetIPAllocationPool pool = new NeutronSubnetIPAllocationPool();
- pool.setPoolStart(String.valueOf(allocationPool.getStart().getValue()));
- pool.setPoolEnd(String.valueOf(allocationPool.getEnd().getValue()));
- allocationPools.add(pool);
- }
- result.setAllocationPools(allocationPools);
- }
- if (subnet.getDnsNameservers() != null) {
- List<String> dnsNameServers = new ArrayList<>();
- for (IpAddress dnsNameServer : subnet.getDnsNameservers()) {
- dnsNameServers.add(String.valueOf(dnsNameServer.getValue()));
- }
- result.setDnsNameservers(dnsNameServers);
- }
- result.setID(subnet.getUuid().getValue());
-// read through the ports and put the ones in this subnet into the internal
-// myPorts object.
-// @deprecated and will be removed in Boron
- Set<NeutronPort> allPorts = new HashSet<>();
- NeutronCRUDInterfaces interfaces = new NeutronCRUDInterfaces()
- .fetchINeutronPortCRUD(this);
- INeutronPortCRUD portIf = interfaces.getPortInterface();
- for (NeutronPort port : portIf.getAllPorts()) {
- if (port.getDeviceOwner().equalsIgnoreCase("network:router_interface") ||
- port.getDeviceOwner().equalsIgnoreCase("network:router_gateway")) {
- if (subnet.getGatewayIp() != null) {
- result.setGatewayIP(String.valueOf(subnet.getGatewayIp().getValue()));
- }
- }
- if (port.getFixedIPs() != null) {
- for (Neutron_IPs ip : port.getFixedIPs()) {
- if (ip.getSubnetUUID().equals(result.getID())) {
- allPorts.add(port);
- }
- }
- }
- }
- List<NeutronPort> ports = new ArrayList<>();
- ports.addAll(allPorts);
- result.setPorts(ports);
- return result;
- }
-
- protected Subnet toMd(NeutronSubnet subnet) {
- SubnetBuilder subnetBuilder = new SubnetBuilder();
- if (subnet.getName() != null) {
- subnetBuilder.setName(subnet.getName());
- }
- if (subnet.getTenantID() != null) {
- subnetBuilder.setTenantId(toUuid(subnet.getTenantID()));
- }
- if (subnet.getNetworkUUID() != null) {
- subnetBuilder.setNetworkId(toUuid(subnet.getNetworkUUID()));
- }
- if (subnet.getIpVersion() != null) {
- ImmutableBiMap<Integer, Class<? extends IpVersionBase>> mapper =
- IPV_MAP.inverse();
- subnetBuilder.setIpVersion(mapper.get(subnet
- .getIpVersion()));
- }
- if (subnet.getCidr() != null) {
- IpPrefix ipPrefix = new IpPrefix(subnet.getCidr().toCharArray());
- subnetBuilder.setCidr(ipPrefix);
- }
- if (subnet.getGatewayIP() != null) {
- IpAddress ipAddress = new IpAddress(subnet.getGatewayIP()
- .toCharArray());
- subnetBuilder.setGatewayIp(ipAddress);
- }
- if (subnet.getIpV6RaMode() != null) {
- ImmutableBiMap<String, Class<? extends Dhcpv6Base>> mapper =
- DHCPV6_MAP.inverse();
- subnetBuilder.setIpv6RaMode(mapper.get(subnet.getIpV6RaMode()));
- }
- if (subnet.getIpV6AddressMode() != null) {
- ImmutableBiMap<String, Class<? extends Dhcpv6Base>> mapper =
- DHCPV6_MAP.inverse();
- subnetBuilder.setIpv6AddressMode(mapper.get(subnet.getIpV6AddressMode()));
- }
- subnetBuilder.setEnableDhcp(subnet.getEnableDHCP());
- if (subnet.getAllocationPools() != null) {
- List<AllocationPools> allocationPools = new ArrayList<>();
- for (NeutronSubnetIPAllocationPool allocationPool : subnet
- .getAllocationPools()) {
- AllocationPoolsBuilder builder = new AllocationPoolsBuilder();
- builder.setStart(new IpAddress(allocationPool.getPoolStart().toCharArray()));
- builder.setEnd(new IpAddress(allocationPool.getPoolEnd().toCharArray()));
- AllocationPools temp = builder.build();
- allocationPools.add(temp);
- }
- subnetBuilder.setAllocationPools(allocationPools);
- }
- if (subnet.getDnsNameservers() != null) {
- List<IpAddress> dnsNameServers = new ArrayList<>();
- for (String dnsNameServer : subnet.getDnsNameservers()) {
- IpAddress ipAddress = new IpAddress(dnsNameServer.toCharArray());
- dnsNameServers.add(ipAddress);
- }
- subnetBuilder.setDnsNameservers(dnsNameServers);
- }
- if (subnet.getID() != null) {
- subnetBuilder.setUuid(toUuid(subnet.getID()));
- } else {
- LOG.warn("Attempting to write neutron subnet without UUID");
- }
- return subnetBuilder.build();
- }
-
- @Override
- protected InstanceIdentifier<Subnet> createInstanceIdentifier(Subnet subnet) {
- return InstanceIdentifier.create(Neutron.class).child(Subnets.class)
- .child(Subnet.class, subnet.getKey());
- }
-
- protected InstanceIdentifier<Subnets> createInstanceIdentifier() {
- return InstanceIdentifier.create(Neutron.class)
- .child(Subnets.class);
- }
-
- @Override
- protected Subnet toMd(String uuid) {
- SubnetBuilder subnetBuilder = new SubnetBuilder();
- subnetBuilder.setUuid(toUuid(uuid));
- return subnetBuilder.build();
- }
-
- public static void registerNewInterface(BundleContext context,
- final DataBroker dataBroker,
- List<ServiceRegistration<?>> registrations) {
- NeutronSubnetInterface neutronSubnetInterface = new NeutronSubnetInterface(dataBroker);
- ServiceRegistration<INeutronSubnetCRUD> neutronSubnetInterfaceRegistration = context.registerService(INeutronSubnetCRUD.class, neutronSubnetInterface, null);
- if(neutronSubnetInterfaceRegistration != null) {
- registrations.add(neutronSubnetInterfaceRegistration);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.iaware;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronFirewall;
-
-/**
- * This interface defines the methods a service that wishes to be aware of Firewall Rules needs to implement
- *
- */
-
-public interface INeutronFirewallAware {
-
- /**
- * Services provide this interface method to indicate if the specified firewall can be created
- *
- * @param firewall
- * instance of proposed new Firewall object
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the create operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canCreateNeutronFirewall(NeutronFirewall firewall);
-
- /**
- * Services provide this interface method for taking action after a firewall has been created
- *
- * @param firewall
- * instance of new Firewall object
- */
- void neutronFirewallCreated(NeutronFirewall firewall);
-
- /**
- * Services provide this interface method to indicate if the specified firewall can be changed using the specified
- * delta
- *
- * @param delta
- * updates to the firewall object using patch semantics
- * @param original
- * instance of the Firewall object to be updated
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the update operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canUpdateNeutronFirewall(NeutronFirewall delta, NeutronFirewall original);
-
- /**
- * Services provide this interface method for taking action after a firewall has been updated
- *
- * @param firewall
- * instance of modified Firewall object
- */
- void neutronFirewallUpdated(NeutronFirewall firewall);
-
- /**
- * Services provide this interface method to indicate if the specified firewall can be deleted
- *
- * @param firewall
- * instance of the Firewall object to be deleted
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the delete operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canDeleteNeutronFirewall(NeutronFirewall firewall);
-
- /**
- * Services provide this interface method for taking action after a firewall has been deleted
- *
- * @param firewall
- * instance of deleted Firewall object
- */
- void neutronFirewallDeleted(NeutronFirewall firewall);
-}
+++ /dev/null
-/*
- * Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.iaware;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronFirewallPolicy;
-
-/**
- * This interface defines the methods a service that wishes to be aware of Firewall Policys needs to implement
- *
- */
-
-public interface INeutronFirewallPolicyAware {
-
- /**
- * Services provide this interface method to indicate if the specified firewallPolicy can be created
- *
- * @param firewallPolicy
- * instance of proposed new Firewall Policy object
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the create operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canCreateNeutronFirewallPolicy(NeutronFirewallPolicy firewallPolicy);
-
- /**
- * Services provide this interface method for taking action after a firewallPolicy has been created
- *
- * @param firewallPolicy
- * instance of new Firewall Policy object
- */
- void neutronFirewallPolicyCreated(NeutronFirewallPolicy firewallPolicy);
-
- /**
- * Services provide this interface method to indicate if the specified firewallPolicy can be changed using the specified
- * delta
- *
- * @param delta
- * updates to the firewallPolicy object using patch semantics
- * @param original
- * instance of the Firewall Policy object to be updated
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the update operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canUpdateNeutronFirewallPolicy(NeutronFirewallPolicy delta, NeutronFirewallPolicy original);
-
- /**
- * Services provide this interface method for taking action after a firewallPolicy has been updated
- *
- * @param firewallPolicy
- * instance of modified Firewall Policy object
- */
- void neutronFirewallPolicyUpdated(NeutronFirewallPolicy firewallPolicy);
-
- /**
- * Services provide this interface method to indicate if the specified firewallPolicy can be deleted
- *
- * @param firewallPolicy
- * instance of the Firewall Policy object to be deleted
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the delete operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canDeleteNeutronFirewallPolicy(NeutronFirewallPolicy firewallPolicy);
-
- /**
- * Services provide this interface method for taking action after a firewallPolicy has been deleted
- *
- * @param firewallPolicy
- * instance of deleted Firewall Policy object
- */
- void neutronFirewallPolicyDeleted(NeutronFirewallPolicy firewallPolicy);
-}
+++ /dev/null
-/*
- * Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.iaware;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronFirewallRule;
-
-/**
- * This interface defines the methods a service that wishes to be aware of Firewall Rules needs to implement
- *
- */
-
-public interface INeutronFirewallRuleAware {
-
- /**
- * Services provide this interface method to indicate if the specified firewallRule can be created
- *
- * @param firewallRule
- * instance of proposed new Firewall Rule object
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the create operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canCreateNeutronFirewallRule(NeutronFirewallRule firewallRule);
-
- /**
- * Services provide this interface method for taking action after a firewallRule has been created
- *
- * @param firewallRule
- * instance of new Firewall Rule object
- */
- void neutronFirewallRuleCreated(NeutronFirewallRule firewallRule);
-
- /**
- * Services provide this interface method to indicate if the specified firewallRule can be changed using the specified
- * delta
- *
- * @param delta
- * updates to the firewallRule object using patch semantics
- * @param original
- * instance of the Firewall Rule object to be updated
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the update operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canUpdateNeutronFirewallRule(NeutronFirewallRule delta, NeutronFirewallRule original);
-
- /**
- * Services provide this interface method for taking action after a firewallRule has been updated
- *
- * @param firewallRule
- * instance of modified Firewall Rule object
- */
- void neutronFirewallRuleUpdated(NeutronFirewallRule firewallRule);
-
- /**
- * Services provide this interface method to indicate if the specified firewallRule can be deleted
- *
- * @param firewallRule
- * instance of the Firewall Rule object to be deleted
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the delete operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canDeleteNeutronFirewallRule(NeutronFirewallRule firewallRule);
-
- /**
- * Services provide this interface method for taking action after a firewallRule has been deleted
- *
- * @param firewallRule
- * instance of deleted Firewall Rule object
- */
- void neutronFirewallRuleDeleted(NeutronFirewallRule firewallRule);
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 IBM Corporation 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.netvirt.openstack.netvirt.translator.iaware;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronFloatingIP;
-
-/**
- * This interface defines the methods a service that wishes to be aware of Neutron FloatingIPs needs to implement
- *
- */
-
-public interface INeutronFloatingIPAware {
-
- /**
- * Services provide this interface method to indicate if the specified floatingIP can be created
- *
- * @param floatingIP
- * instance of proposed new Neutron FloatingIP object
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the create operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canCreateFloatingIP(NeutronFloatingIP floatingIP);
-
- /**
- * Services provide this interface method for taking action after a floatingIP has been created
- *
- * @param floatingIP
- * instance of new Neutron FloatingIP object
- */
- void neutronFloatingIPCreated(NeutronFloatingIP floatingIP);
-
- /**
- * Services provide this interface method to indicate if the specified floatingIP can be changed using the specified
- * delta
- *
- * @param delta
- * updates to the floatingIP object using patch semantics
- * @param original
- * instance of the Neutron FloatingIP object to be updated
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the update operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canUpdateFloatingIP(NeutronFloatingIP delta, NeutronFloatingIP original);
-
- /**
- * Services provide this interface method for taking action after a floatingIP has been updated
- *
- * @param floatingIP
- * instance of modified Neutron FloatingIP object
- */
- void neutronFloatingIPUpdated(NeutronFloatingIP floatingIP);
-
- /**
- * Services provide this interface method to indicate if the specified floatingIP can be deleted
- *
- * @param floatingIP
- * instance of the Neutron FloatingIP object to be deleted
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the delete operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canDeleteFloatingIP(NeutronFloatingIP floatingIP);
-
- /**
- * Services provide this interface method for taking action after a floatingIP has been deleted
- *
- * @param floatingIP
- * instance of deleted Neutron FloatingIP object
- */
- void neutronFloatingIPDeleted(NeutronFloatingIP floatingIP);
-}
+++ /dev/null
-/*
- * Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.iaware;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancer;
-
-/**
- * This interface defines the methods a service that wishes to be aware of LoadBalancer Rules needs to implement
- *
- */
-
-public interface INeutronLoadBalancerAware {
-
- /**
- * Services provide this interface method to indicate if the specified loadBalancer can be created
- *
- * @param loadBalancer
- * instance of proposed new LoadBalancer object
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the create operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canCreateNeutronLoadBalancer(NeutronLoadBalancer loadBalancer);
-
- /**
- * Services provide this interface method for taking action after a loadBalancer has been created
- *
- * @param loadBalancer
- * instance of new LoadBalancer object
- */
- void neutronLoadBalancerCreated(NeutronLoadBalancer loadBalancer);
-
- /**
- * Services provide this interface method to indicate if the
- * specified loadBalancer can be changed using the specified
- * delta
- *
- * @param delta
- * updates to the loadBalancer object using patch semantics
- * @param original
- * instance of the LoadBalancer object to be updated
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the update operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canUpdateNeutronLoadBalancer(NeutronLoadBalancer delta, NeutronLoadBalancer original);
-
- /**
- * Services provide this interface method for taking action after a loadBalancer has been updated
- *
- * @param loadBalancer
- * instance of modified LoadBalancer object
- */
- void neutronLoadBalancerUpdated(NeutronLoadBalancer loadBalancer);
-
- /**
- * Services provide this interface method to indicate if the specified loadBalancer can be deleted
- *
- * @param loadBalancer
- * instance of the LoadBalancer object to be deleted
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the delete operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canDeleteNeutronLoadBalancer(NeutronLoadBalancer loadBalancer);
-
- /**
- * Services provide this interface method for taking action after a loadBalancer has been deleted
- *
- * @param loadBalancer
- * instance of deleted LoadBalancer object
- */
- void neutronLoadBalancerDeleted(NeutronLoadBalancer loadBalancer);
-}
+++ /dev/null
-/*
- * Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.iaware;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancerHealthMonitor;
-
-/**
- * This interface defines the methods a service that wishes to be aware of LoadBalancerHealthMonitor Rules needs to implement
- *
- */
-
-public interface INeutronLoadBalancerHealthMonitorAware {
-
- /**
- * Services provide this interface method to indicate if the specified loadBalancerHealthMonitor can be created
- *
- * @param loadBalancerHealthMonitor
- * instance of proposed new LoadBalancerHealthMonitor object
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the create operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canCreateNeutronLoadBalancerHealthMonitor(NeutronLoadBalancerHealthMonitor loadBalancerHealthMonitor);
-
- /**
- * Services provide this interface method for taking action after a loadBalancerHealthMonitor has been created
- *
- * @param loadBalancerHealthMonitor
- * instance of new LoadBalancerHealthMonitor object
- */
- void neutronLoadBalancerHealthMonitorCreated(NeutronLoadBalancerHealthMonitor loadBalancerHealthMonitor);
-
- /**
- * Services provide this interface method to indicate if the specified loadBalancerHealthMonitor can be changed using the specified
- * delta
- *
- * @param delta
- * updates to the loadBalancerHealthMonitor object using patch semantics
- * @param original
- * instance of the LoadBalancerHealthMonitor object to be updated
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the update operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canUpdateNeutronLoadBalancerHealthMonitor(NeutronLoadBalancerHealthMonitor delta,
- NeutronLoadBalancerHealthMonitor original);
-
- /**
- * Services provide this interface method for taking action after a loadBalancerHealthMonitor has been updated
- *
- * @param loadBalancerHealthMonitor
- * instance of modified LoadBalancerHealthMonitor object
- */
- void neutronLoadBalancerHealthMonitorUpdated(NeutronLoadBalancerHealthMonitor loadBalancerHealthMonitor);
-
- /**
- * Services provide this interface method to indicate if the specified loadBalancerHealthMonitor can be deleted
- *
- * @param loadBalancerHealthMonitor
- * instance of the LoadBalancerHealthMonitor object to be deleted
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the delete operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canDeleteNeutronLoadBalancerHealthMonitor(NeutronLoadBalancerHealthMonitor loadBalancerHealthMonitor);
-
- /**
- * Services provide this interface method for taking action after a loadBalancerHealthMonitor has been deleted
- *
- * @param loadBalancerHealthMonitor
- * instance of deleted LoadBalancerHealthMonitor object
- */
- void neutronLoadBalancerHealthMonitorDeleted(NeutronLoadBalancerHealthMonitor loadBalancerHealthMonitor);
-}
+++ /dev/null
-/*
- * Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.iaware;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancerListener;
-
-/**
- * This interface defines the methods a service that wishes to be aware of LoadBalancerListener Rules needs to implement
- *
- */
-
-public interface INeutronLoadBalancerListenerAware {
-
- /**
- * Services provide this interface method to indicate if the specified loadBalancerListener can be created
- *
- * @param loadBalancerListener
- * instance of proposed new LoadBalancerListener object
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the create operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canCreateNeutronLoadBalancerListener(NeutronLoadBalancerListener loadBalancerListener);
-
- /**
- * Services provide this interface method for taking action after a loadBalancerListener has been created
- *
- * @param loadBalancerListener
- * instance of new LoadBalancerListener object
- */
- void neutronLoadBalancerListenerCreated(NeutronLoadBalancerListener loadBalancerListener);
-
- /**
- * Services provide this interface method to indicate if the specified loadBalancerListener can be changed using the specified
- * delta
- *
- * @param delta
- * updates to the loadBalancerListener object using patch semantics
- * @param original
- * instance of the LoadBalancerListener object to be updated
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the update operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canUpdateNeutronLoadBalancerListener(NeutronLoadBalancerListener delta,
- NeutronLoadBalancerListener original);
-
- /**
- * Services provide this interface method for taking action after a loadBalancerListener has been updated
- *
- * @param loadBalancerListener
- * instance of modified LoadBalancerListener object
- */
- void neutronLoadBalancerListenerUpdated(NeutronLoadBalancerListener loadBalancerListener);
-
- /**
- * Services provide this interface method to indicate if the specified loadBalancerListener can be deleted
- *
- * @param loadBalancerListener
- * instance of the LoadBalancerListener object to be deleted
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the delete operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canDeleteNeutronLoadBalancerListener(NeutronLoadBalancerListener loadBalancerListener);
-
- /**
- * Services provide this interface method for taking action after a loadBalancerListener has been deleted
- *
- * @param loadBalancerListener
- * instance of deleted LoadBalancerListener object
- */
- void neutronLoadBalancerListenerDeleted(NeutronLoadBalancerListener loadBalancerListener);
-}
+++ /dev/null
-/*
- * Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.iaware;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancerPool;
-
-/**
- * This interface defines the methods a service that wishes to be aware of LoadBalancerPool Rules needs to implement
- *
- */
-
-public interface INeutronLoadBalancerPoolAware {
-
- /**
- * Services provide this interface method to indicate if the specified loadBalancerPool can be created
- *
- * @param loadBalancerPool
- * instance of proposed new LoadBalancerPool object
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the create operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canCreateNeutronLoadBalancerPool(NeutronLoadBalancerPool loadBalancerPool);
-
- /**
- * Services provide this interface method for taking action after a loadBalancerPool has been created
- *
- * @param loadBalancerPool
- * instance of new LoadBalancerPool object
- */
- void neutronLoadBalancerPoolCreated(NeutronLoadBalancerPool loadBalancerPool);
-
- /**
- * Services provide this interface method to indicate if the
- * specified loadBalancerPool can be changed using the specified
- * delta
- *
- * @param delta
- * updates to the loadBalancerPool object using patch semantics
- * @param original
- * instance of the LoadBalancerPool object to be updated
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the update operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canUpdateNeutronLoadBalancerPool(NeutronLoadBalancerPool delta, NeutronLoadBalancerPool original);
-
- /**
- * Services provide this interface method for taking action after a loadBalancerPool has been updated
- *
- * @param loadBalancerPool
- * instance of modified LoadBalancerPool object
- */
- void neutronLoadBalancerPoolUpdated(NeutronLoadBalancerPool loadBalancerPool);
-
- /**
- * Services provide this interface method to indicate if the specified loadBalancerPool can be deleted
- *
- * @param loadBalancerPool
- * instance of the LoadBalancerPool object to be deleted
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the delete operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canDeleteNeutronLoadBalancerPool(NeutronLoadBalancerPool loadBalancerPool);
-
- /**
- * Services provide this interface method for taking action after a loadBalancerPool has been deleted
- *
- * @param loadBalancerPool
- * instance of deleted LoadBalancerPool object
- */
- void neutronLoadBalancerPoolDeleted(NeutronLoadBalancerPool loadBalancerPool);
-}
+++ /dev/null
-/*
- * Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt.translator.iaware;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancerPoolMember;
-
-public interface INeutronLoadBalancerPoolMemberAware {
-
-
- /**
- * Services provide this interface method to indicate if the specified loadBalancerPoolMember can be created
- *
- * @param loadBalancerPoolMember
- * instance of proposed new LoadBalancerPool object
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the create operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canCreateNeutronLoadBalancerPoolMember(NeutronLoadBalancerPoolMember loadBalancerPoolMember);
-
- /**
- * Services provide this interface method for taking action after a loadBalancerPoolMember has been created
- *
- * @param loadBalancerPoolMember
- * instance of new LoadBalancerPool object
- */
- void neutronLoadBalancerPoolMemberCreated(NeutronLoadBalancerPoolMember loadBalancerPoolMember);
-
- /**
- * Services provide this interface method to indicate if the specified loadBalancerPoolMember can be changed using the specified
- * delta
- *
- * @param delta
- * updates to the loadBalancerPoolMember object using patch semantics
- * @param original
- * instance of the LoadBalancerPool object to be updated
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the update operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canUpdateNeutronLoadBalancerPoolMember(NeutronLoadBalancerPoolMember delta,
- NeutronLoadBalancerPoolMember original);
-
- /**
- * Services provide this interface method for taking action after a loadBalancerPoolMember has been updated
- *
- * @param loadBalancerPoolMember
- * instance of modified LoadBalancerPool object
- */
- void neutronLoadBalancerPoolMemberUpdated(NeutronLoadBalancerPoolMember loadBalancerPoolMember);
-
- /**
- * Services provide this interface method to indicate if the specified loadBalancerPoolMember can be deleted
- *
- * @param loadBalancerPoolMember
- * instance of the LoadBalancerPool object to be deleted
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the delete operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canDeleteNeutronLoadBalancerPoolMember(NeutronLoadBalancerPoolMember loadBalancerPoolMember);
-
- /**
- * Services provide this interface method for taking action after a loadBalancerPoolMember has been deleted
- *
- * @param loadBalancerPoolMember
- * instance of deleted LoadBalancerPool object
- */
- void neutronLoadBalancerPoolMemberDeleted(NeutronLoadBalancerPoolMember loadBalancerPoolMember);
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 IBM Corporation 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.netvirt.openstack.netvirt.translator.iaware;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-
-/**
- * This interface defines the methods a service that wishes to be aware of Neutron Networks needs to implement
- *
- */
-
-public interface INeutronNetworkAware {
-
- /**
- * Services provide this interface method to indicate if the specified network can be created
- *
- * @param network
- * instance of proposed new Neutron Network object
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the create operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canCreateNetwork(NeutronNetwork network);
-
- /**
- * Services provide this interface method for taking action after a network has been created
- *
- * @param network
- * instance of new Neutron Network object
- */
- void neutronNetworkCreated(NeutronNetwork network);
-
- /**
- * Services provide this interface method to indicate if the specified network can be changed using the specified
- * delta
- *
- * @param delta
- * updates to the network object using patch semantics
- * @param original
- * instance of the Neutron Network object to be updated
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the update operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canUpdateNetwork(NeutronNetwork delta, NeutronNetwork original);
-
- /**
- * Services provide this interface method for taking action after a network has been updated
- *
- * @param network
- * instance of modified Neutron Network object
- */
- void neutronNetworkUpdated(NeutronNetwork network);
-
- /**
- * Services provide this interface method to indicate if the specified network can be deleted
- *
- * @param network
- * instance of the Neutron Network object to be deleted
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the delete operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canDeleteNetwork(NeutronNetwork network);
-
- /**
- * Services provide this interface method for taking action after a network has been deleted
- *
- * @param network
- * instance of deleted Neutron Network object
- */
- void neutronNetworkDeleted(NeutronNetwork network);
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 IBM Corporation 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.netvirt.openstack.netvirt.translator.iaware;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-
-/**
- * This interface defines the methods a service that wishes to be aware of Neutron Ports needs to implement
- *
- */
-
-public interface INeutronPortAware {
-
- /**
- * Services provide this interface method to indicate if the specified port can be created
- *
- * @param port
- * instance of proposed new Neutron Port object
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the create operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canCreatePort(NeutronPort port);
-
- /**
- * Services provide this interface method for taking action after a port has been created
- *
- * @param port
- * instance of new Neutron Port object
- */
- void neutronPortCreated(NeutronPort port);
-
- /**
- * Services provide this interface method to indicate if the specified port can be changed using the specified
- * delta
- *
- * @param delta
- * updates to the port object using patch semantics
- * @param original
- * instance of the Neutron Port object to be updated
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the update operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canUpdatePort(NeutronPort delta, NeutronPort original);
-
- /**
- * Services provide this interface method for taking action after a port has been updated
- *
- * @param port
- * instance of modified Neutron Port object
- */
- void neutronPortUpdated(NeutronPort port);
-
- /**
- * Services provide this interface method to indicate if the specified port can be deleted
- *
- * @param port
- * instance of the Neutron Port object to be deleted
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the delete operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canDeletePort(NeutronPort port);
-
- /**
- * Services provide this interface method for taking action after a port has been deleted
- *
- * @param port
- * instance of deleted Port Network object
- */
- void neutronPortDeleted(NeutronPort port);
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 IBM Corporation 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.netvirt.openstack.netvirt.translator.iaware;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronRouter;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronRouter_Interface;
-
-/**
- * This interface defines the methods a service that wishes to be aware of Neutron Routers needs to implement
- *
- */
-
-public interface INeutronRouterAware {
-
- /**
- * Services provide this interface method to indicate if the specified router can be created
- *
- * @param router
- * instance of proposed new Neutron Router object
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the create operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canCreateRouter(NeutronRouter router);
-
- /**
- * Services provide this interface method for taking action after a router has been created
- *
- * @param router
- * instance of new Neutron Router object
- */
- void neutronRouterCreated(NeutronRouter router);
-
- /**
- * Services provide this interface method to indicate if the specified router can be changed using the specified
- * delta
- *
- * @param delta
- * updates to the router object using patch semantics
- * @param original
- * instance of the Neutron Router object to be updated
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the update operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canUpdateRouter(NeutronRouter delta, NeutronRouter original);
-
- /**
- * Services provide this interface method for taking action after a router has been updated
- *
- * @param router
- * instance of modified Neutron Router object
- */
- void neutronRouterUpdated(NeutronRouter router);
-
- /**
- * Services provide this interface method to indicate if the specified router can be deleted
- *
- * @param router
- * instance of the Neutron Router object to be deleted
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the delete operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canDeleteRouter(NeutronRouter router);
-
- /**
- * Services provide this interface method for taking action after a router has been deleted
- *
- * @param router
- * instance of deleted Router Network object
- */
- void neutronRouterDeleted(NeutronRouter router);
-
- /**
- * Services provide this interface method to indicate if the
- * specified interface can be attached to the specified router
- *
- * @param router
- * instance of the base Neutron Router object
- * @param routerInterface
- * instance of the NeutronRouter_Interface to be attached to the router
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the attach operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canAttachInterface(NeutronRouter router, NeutronRouter_Interface routerInterface);
-
- /**
- * Services provide this interface method for taking action
- * after an interface has been added to a router
- *
- * @param router
- * instance of the base Neutron Router object
- * @param routerInterface
- * instance of the NeutronRouter_Interface being attached to the router
- */
- void neutronRouterInterfaceAttached(NeutronRouter router, NeutronRouter_Interface routerInterface);
-
- /**
- * Services provide this interface method to indicate if the
- * specified interface can be detached from the specified router
- *
- * @param router
- * instance of the base Neutron Router object
- * @param routerInterface
- * instance of the NeutronRouter_Interface to be detached to the router
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the detach operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canDetachInterface(NeutronRouter router, NeutronRouter_Interface routerInterface);
-
- /**
- * Services provide this interface method for taking action after an interface has been removed from a router
- *
- * @param router
- * instance of the base Neutron Router object
- * @param routerInterface
- * instance of the NeutronRouter_Interface being detached from the router
- */
- void neutronRouterInterfaceDetached(NeutronRouter router, NeutronRouter_Interface routerInterface);
-}
+++ /dev/null
-/*
- * Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.iaware;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityGroup;
-
-/**
- * This interface defines the methods a service that wishes to be aware of Neutron Security Groups needs to implement
- */
-
-public interface INeutronSecurityGroupAware {
-
- /**
- * Services provide this interface method to indicate if the specified security group can be created
- *
- * @param securityGroup instance of proposed new Neutron Security Group object
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the create operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canCreateNeutronSecurityGroup(NeutronSecurityGroup securityGroup);
-
- /**
- * Services provide this interface method for taking action after a security group has been created
- *
- * @param securityGroup instance of new Neutron Security Group object
- */
- void neutronSecurityGroupCreated(NeutronSecurityGroup securityGroup);
-
- /**
- * Services provide this interface method to indicate if the specified security group can be changed using the specified
- * delta
- *
- * @param delta updates to the security group object using patch semantics
- * @param original instance of the Neutron Security Group object to be updated
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the update operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canUpdateNeutronSecurityGroup(NeutronSecurityGroup delta, NeutronSecurityGroup original);
-
- /**
- * Services provide this interface method for taking action after a security group has been updated
- *
- * @param securityGroup instance of modified Neutron Security Group object
- */
- void neutronSecurityGroupUpdated(NeutronSecurityGroup securityGroup);
-
- /**
- * Services provide this interface method to indicate if the specified security group can be deleted
- *
- * @param securityGroup instance of the Neutron Security Group object to be deleted
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the delete operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canDeleteNeutronSecurityGroup(NeutronSecurityGroup securityGroup);
-
- /**
- * Services provide this interface method for taking action after a security group has been deleted
- *
- * @param securityGroup instance of deleted Neutron Security Group object
- */
- void neutronSecurityGroupDeleted(NeutronSecurityGroup securityGroup);
-}
+++ /dev/null
-/*
- * Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.iaware;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityRule;
-
-/**
- * This interface defines the methods required to be aware of Neutron Security Rules
- */
-
-public interface INeutronSecurityRuleAware {
-
- /**
- * Services provide this interface method to indicate if the specified security rule can be created
- *
- * @param securityRule instance of proposed new Neutron Security Rule object
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the create operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canCreateNeutronSecurityRule(NeutronSecurityRule securityRule);
-
- /**
- * Services provide this interface method for taking action after a security rule has been created
- *
- * @param securityRule instance of new Neutron Security Rule object
- */
- void neutronSecurityRuleCreated(NeutronSecurityRule securityRule);
-
- /**
- * Services provide this interface method to indicate if the specified security rule can be changed using the specified
- * delta
- *
- * @param delta updates to the security rule object using patch semantics
- * @param original instance of the Neutron Security Rule object to be updated
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the update operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canUpdateNeutronSecurityRule(NeutronSecurityRule delta, NeutronSecurityRule original);
-
- /**
- * Services provide this interface method for taking action after a security rule has been updated
- *
- * @param securityRule instance of modified Neutron Security Rule object
- */
- void neutronSecurityRuleUpdated(NeutronSecurityRule securityRule);
-
- /**
- * Services provide this interface method to indicate if the specified security rule can be deleted
- *
- * @param securityRule instance of the Neutron Security Rule object to be deleted
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the delete operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canDeleteNeutronSecurityRule(NeutronSecurityRule securityRule);
-
- /**
- * Services provide this interface method for taking action after a security rule has been deleted
- *
- * @param securityRule instance of deleted Neutron Security Rule object
- */
- void neutronSecurityRuleDeleted(NeutronSecurityRule securityRule);
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 IBM Corporation 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.netvirt.openstack.netvirt.translator.iaware;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSubnet;
-
-/**
- * This interface defines the methods a service that wishes to be aware of Neutron Subnets needs to implement
- *
- */
-
-public interface INeutronSubnetAware {
-
- /**
- * Services provide this interface method to indicate if the specified subnet can be created
- *
- * @param subnet
- * instance of proposed new Neutron Subnet object
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the create operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canCreateSubnet(NeutronSubnet subnet);
-
- /**
- * Services provide this interface method for taking action after a subnet has been created
- *
- * @param subnet
- * instance of new Neutron Subnet object
- */
- void neutronSubnetCreated(NeutronSubnet subnet);
-
- /**
- * Services provide this interface method to indicate if the specified subnet can be changed using the specified
- * delta
- *
- * @param delta
- * updates to the subnet object using patch semantics
- * @param original
- * instance of the Neutron Subnet object to be updated
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the update operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canUpdateSubnet(NeutronSubnet delta, NeutronSubnet original);
-
- /**
- * Services provide this interface method for taking action after a subnet has been updated
- *
- * @param subnet
- * instance of modified Neutron Subnet object
- */
- void neutronSubnetUpdated(NeutronSubnet subnet);
-
- /**
- * Services provide this interface method to indicate if the specified subnet can be deleted
- *
- * @param subnet
- * instance of the Subnet Router object to be deleted
- * @return integer
- * the return value is understood to be a HTTP status code. A return value outside of 200 through 299
- * results in the delete operation being interrupted and the returned status value reflected in the
- * HTTP response.
- */
- int canDeleteSubnet(NeutronSubnet subnet);
-
- /**
- * Services provide this interface method for taking action after a subnet has been deleted
- *
- * @param subnet
- * instance of deleted Router Subnet object
- */
- void neutronSubnetDeleted(NeutronSubnet subnet);
-
-}
+++ /dev/null
-/*
- * Copyright © 2015, 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt.translator.iaware.impl;
-
-import java.util.Collection;
-import javax.annotation.Nonnull;
-import javax.annotation.PostConstruct;
-import org.opendaylight.controller.md.sal.binding.api.ClusteredDataTreeChangeListener;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.DataTreeChangeListener;
-import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
-import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronFloatingIP;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronFloatingIPAware;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.floatingips.attributes.Floatingips;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.floatingips.attributes.floatingips.Floatingip;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class NeutronFloatingIPDataTreeChangeListener
- implements ClusteredDataTreeChangeListener<Floatingip>, AutoCloseable {
- private static final Logger LOG = LoggerFactory.getLogger(NeutronFloatingIPDataTreeChangeListener.class);
-
- private final DataBroker dataBroker;
- private ListenerRegistration<DataTreeChangeListener<Floatingip>> registration;
-
- public NeutronFloatingIPDataTreeChangeListener(DataBroker dataBroker) {
- this.dataBroker = dataBroker;
- }
-
- @PostConstruct
- public void init() {
- InstanceIdentifier<Floatingip> path = InstanceIdentifier
- .create(Neutron.class)
- .child(Floatingips.class)
- .child(Floatingip.class);
- LOG.debug("Register listener for Neutron FloatingIp model data changes");
- registration = dataBroker.registerDataTreeChangeListener(
- new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION, path), this);
- }
-
- @Override
- public void onDataTreeChanged(@Nonnull Collection<DataTreeModification<Floatingip>> changes) {
- LOG.trace("Data changes : {}", changes);
-
- Object[] subscribers = NeutronIAwareUtil.getInstances(INeutronFloatingIPAware.class, this);
- createFloatingIP(changes, subscribers);
- updateFloatingIP(changes, subscribers);
- deleteFloatingIP(changes, subscribers);
- }
-
- private void createFloatingIP(
- @Nonnull Collection<DataTreeModification<Floatingip>> changes,
- Object[] subscribers) {
- for (DataTreeModification<Floatingip> change : changes) {
- if (change.getRootNode().getDataAfter() != null && change.getRootNode().getDataBefore() == null) {
- NeutronFloatingIP floatingIp = fromMd(change.getRootNode().getDataAfter());
- for (Object entry : subscribers) {
- INeutronFloatingIPAware subscriber = (INeutronFloatingIPAware) entry;
- subscriber.neutronFloatingIPCreated(floatingIp);
- }
- }
- }
- }
-
- private void updateFloatingIP(
- @Nonnull Collection<DataTreeModification<Floatingip>> changes,
- Object[] subscribers) {
- for (DataTreeModification<Floatingip> change : changes) {
- if (change.getRootNode().getDataAfter() != null && change.getRootNode().getDataBefore() != null) {
- NeutronFloatingIP floatingIp = fromMd(change.getRootNode().getDataAfter());
- for (Object entry : subscribers) {
- INeutronFloatingIPAware subscriber = (INeutronFloatingIPAware) entry;
- subscriber.neutronFloatingIPUpdated(floatingIp);
- }
- }
- }
- }
-
- private void deleteFloatingIP(
- @Nonnull Collection<DataTreeModification<Floatingip>> changes,
- Object[] subscribers) {
- for (DataTreeModification<Floatingip> change : changes) {
- if (change.getRootNode().getDataAfter() == null && change.getRootNode().getDataBefore() != null) {
- NeutronFloatingIP floatingIp = fromMd(change.getRootNode().getDataBefore());
- for (Object entry : subscribers) {
- INeutronFloatingIPAware subscriber = (INeutronFloatingIPAware) entry;
- subscriber.neutronFloatingIPDeleted(floatingIp);
- }
- }
- }
- }
-
- /*
- * This method is borrowed from NeutronFloatingIPInterface.java class of Neutron Northbound class.
- * We will be utilizing similar code from other classes from the same package of neutron project.
- */
- private NeutronFloatingIP fromMd(Floatingip fip) {
- NeutronFloatingIP result = new NeutronFloatingIP();
- result.setID(fip.getUuid().getValue());
- if (fip.getFloatingNetworkId() != null) {
- result.setFloatingNetworkUUID(fip.getFloatingNetworkId().getValue());
- }
- if (fip.getPortId() != null) {
- result.setPortUUID(fip.getPortId().getValue());
- }
- if (fip.getFixedIpAddress() != null) {
- result.setFixedIPAddress(String.valueOf(fip.getFixedIpAddress().getValue()));
- }
- if (fip.getFloatingIpAddress() != null) {
- result.setFloatingIPAddress(String.valueOf(fip.getFloatingIpAddress().getValue()));
- }
- if (fip.getTenantId() != null) {
- result.setTenantUUID(fip.getTenantId().getValue());
- }
- if (fip.getRouterId() != null) {
- result.setRouterUUID(fip.getRouterId().getValue());
- }
- result.setStatus(fip.getStatus());
- return result;
- }
-
- @Override
- public void close() {
- registration.close();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.iaware.impl;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronRouter_Interface;
-import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.FixedIps;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.FrameworkUtil;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class NeutronIAwareUtil {
- private static final Logger LOGGER = LoggerFactory
- .getLogger(NeutronIAwareUtil.class);
-
- private NeutronIAwareUtil() {
- }
-
- public static Object[] getInstances(Class<?> clazz,Object bundle) {
- Object instances[] = null;
- try {
- BundleContext bCtx = FrameworkUtil.getBundle(bundle.getClass())
- .getBundleContext();
-
- ServiceReference<?>[] services = null;
- services = bCtx.getServiceReferences(clazz.getName(),
- null);
- if (services != null) {
- instances = new Object[services.length];
- for (int i = 0; i < services.length; i++) {
- instances[i] = bCtx.getService(services[i]);
- }
- }
- } catch (Exception e) {
- LOGGER.error("Instance reference is NULL", e);
- }
- return instances;
- }
-
- public static List<Neutron_IPs> convertMDSalIpToNeutronIp(List<FixedIps> fixedIps) {
- List<Neutron_IPs> ips = null;
- if (fixedIps != null) {
- ips = new ArrayList<>();
- for (FixedIps mdIP : fixedIps) {
- Neutron_IPs ip = new Neutron_IPs();
- ip.setIpAddress(String.valueOf(mdIP.getIpAddress().getValue()));
- ip.setSubnetUUID(mdIP.getSubnetId().getValue());
- ips.add(ip);
- }
- }
- return ips;
- }
-
- public static NeutronRouter_Interface convertMDSalInterfaceToNeutronRouterInterface(
- Port routerInterface) {
- NeutronRouter_Interface neutronInterface = new NeutronRouter_Interface();
- String id = String.valueOf(routerInterface.getUuid().getValue());
- neutronInterface.setID(id);
- if (routerInterface.getTenantId() != null) {
- neutronInterface.setTenantID(routerInterface.getTenantId().getValue());
- }
- neutronInterface.setSubnetUUID(routerInterface.getFixedIps().get(0).getSubnetId().getValue());
- neutronInterface.setPortUUID(routerInterface.getUuid().getValue());
- return neutronInterface;
- }
-
-
-
-}
+++ /dev/null
-/*
- * Copyright (C) 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.iaware.impl;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map.Entry;
-
-import org.opendaylight.controller.md.sal.binding.api.ClusteredDataChangeListener;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancerPool;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancerPoolMember;
-import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_ID;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronLoadBalancerPoolAware;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancer_SessionPersistence;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolBase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolHttp;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolHttps;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolIcmp;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolTcp;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.lbaasv2.rev150712.lbaas.attributes.Pools;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.lbaasv2.rev150712.lbaas.attributes.pools.Pool;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.lbaasv2.rev150712.lbaas.attributes.pools.pool.members.Member;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.ImmutableBiMap;
-
-public class NeutronLoadBalancerPoolChangeListener implements ClusteredDataChangeListener, AutoCloseable {
- private static final Logger LOG = LoggerFactory.getLogger(NeutronLoadBalancerPoolChangeListener.class);
-
- private static final ImmutableBiMap<Class<? extends ProtocolBase>,String> PROTOCOL_MAP
- = new ImmutableBiMap.Builder<Class<? extends ProtocolBase>,String>()
- .put(ProtocolHttp.class, "HTTP")
- .put(ProtocolHttps.class, "HTTPS")
- .put(ProtocolIcmp.class, "ICMP")
- .put(ProtocolTcp.class,"TCP")
- .build();
-
- private ListenerRegistration<DataChangeListener> registration;
- private DataBroker db;
-
- public NeutronLoadBalancerPoolChangeListener(DataBroker db){
- this.db = db;
- InstanceIdentifier<Pool> path = InstanceIdentifier
- .create(Neutron.class)
- .child(Pools.class)
- .child(Pool.class);
- LOG.debug("Register listener for Neutron Load Balancer Pool model data changes");
- registration =
- this.db.registerDataChangeListener(LogicalDatastoreType.CONFIGURATION, path, this, AsyncDataBroker.DataChangeScope.ONE);
- }
-
- @Override
- public void close() throws Exception {
- registration.close();
- }
-
- @Override
- public void onDataChanged(AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes) {
- LOG.trace("Data changes : {}", changes);
-
- Object[] subscribers = NeutronIAwareUtil.getInstances(INeutronLoadBalancerPoolAware.class, this);
- createPool(changes, subscribers);
- updatePool(changes, subscribers);
- deletePool(changes, subscribers);
- }
-
- private void createPool(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes,
- Object[] subscribers) {
- for (Entry<InstanceIdentifier<?>, DataObject> newPool : changes.getCreatedData().entrySet()) {
- if(newPool.getValue() instanceof Pool){
- NeutronLoadBalancerPool loadBalancerPool = fromMd((Pool) newPool.getValue());
- for (Object entry : subscribers) {
- INeutronLoadBalancerPoolAware subscriber = (INeutronLoadBalancerPoolAware) entry;
- subscriber.neutronLoadBalancerPoolCreated(loadBalancerPool);
- }
- }
- }
- }
- private void updatePool(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes,
- Object[] subscribers) {
- for (Entry<InstanceIdentifier<?>, DataObject> updatePool : changes.getUpdatedData().entrySet()) {
- if(updatePool.getValue() instanceof Pool){
- NeutronLoadBalancerPool loadBalancerPool = fromMd((Pool)updatePool.getValue());
- for(Object entry: subscribers){
- INeutronLoadBalancerPoolAware subscriber = (INeutronLoadBalancerPoolAware) entry;
- subscriber.neutronLoadBalancerPoolUpdated(loadBalancerPool);
- }
- }
- }
- }
- private void deletePool(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes,
- Object[] subscribers) {
- for (InstanceIdentifier<?> deletedPoolPath : changes.getRemovedPaths()) {
- if(deletedPoolPath.getTargetType().equals(Pool.class)){
- NeutronLoadBalancerPool loadBalancerPool = fromMd((Pool)changes.getOriginalData().get(deletedPoolPath));
- for(Object entry: subscribers){
- INeutronLoadBalancerPoolAware subscriber = (INeutronLoadBalancerPoolAware) entry;
- subscriber.neutronLoadBalancerPoolDeleted(loadBalancerPool);
- }
- }
- }
- }
-
- /*
- * This method is borrowed from NeutronLoadBalancerPool.java class of Neutron Northbound class.
- * in the original location, this method is called extractFields.
- * We will be utilizing similar code from other classes from the same package of neutron project.
- */
- private NeutronLoadBalancerPool fromMd(Pool pool) {
- NeutronLoadBalancerPool result = new NeutronLoadBalancerPool();
-
- result.setID(pool.getUuid().getValue());
- if (pool.getTenantId() != null) {
- result.setLoadBalancerPoolTenantID(pool.getTenantId().getValue());
- }
- if (pool.getName() != null) {
- result.setLoadBalancerPoolName(pool.getName());
- }
- if (pool.getProtocol() != null) {
- result.setLoadBalancerPoolProtocol(PROTOCOL_MAP.get(pool.getProtocol()));
- }
- if (pool.getLbAlgorithm() != null) {
- result.setLoadBalancerPoolLbAlgorithm(pool.getLbAlgorithm());
- }
-
- // TODO: setNeutronLoadBalancerPoolHealthMonitorID is a list? Fill in, when its needed.
- if (pool.getHealthmonitorId() != null) {
- result.setNeutronLoadBalancerPoolHealthMonitorID(pool.getHealthmonitorId().getValue());
- }
-
- if (pool.isAdminStateUp() != null) {
- result.setLoadBalancerPoolAdminStateIsUp(pool.isAdminStateUp());
- }
-
- List<Neutron_ID> listeners = new ArrayList();
- if (pool.getListeners() != null) {
- for (Uuid listenerUuid : pool.getListeners()) {
- listeners.add(new Neutron_ID(listenerUuid.getValue()));
- }
- }
- result.setLoadBalancerPoolListeners(listeners);
-
- if (pool.getSessionPersistence() != null) {
- NeutronLoadBalancer_SessionPersistence sessionPersistence = new NeutronLoadBalancer_SessionPersistence();
- sessionPersistence.setCookieName(pool.getSessionPersistence().getCookieName());
- sessionPersistence.setType(pool.getSessionPersistence().getType());
- result.setLoadBalancerSessionPersistence(sessionPersistence);
- }
-
- List<NeutronLoadBalancerPoolMember> loadBalancerPoolMembers = new ArrayList();
- if (pool.getMembers() != null) {
- for (Member member : pool.getMembers().getMember()) {
- NeutronLoadBalancerPoolMember neutronMember = new NeutronLoadBalancerPoolMember();
-
- neutronMember.setPoolID(pool.getUuid().getValue());
- neutronMember.setPoolMemberID(member.getUuid().getValue());
-
- // TODO: locate and populate remainder attributes, when its needed
- // member.setPoolMemberAddress(xxx);
- // member.setPoolMemberAdminStateIsUp(xxx);
- // member.setPoolMemberProtoPort(xxx);
- // member.setPoolMemberSubnetID(xxx);
- // member.setPoolMemberTenantID(xxx);
- // member.setPoolMemberWeight(xxx);
-
- loadBalancerPoolMembers.add(neutronMember);
- }
- }
- result.setLoadBalancerPoolMembers(loadBalancerPoolMembers);
-
- return result;
- }
-}
+++ /dev/null
-/*
- * Copyright (C) 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.netvirt.translator.iaware.impl;
-
-import java.util.Map.Entry;
-
-import org.opendaylight.controller.md.sal.binding.api.ClusteredDataChangeListener;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancerPoolMember;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronLoadBalancerPoolMemberAware;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.lbaasv2.rev150712.lbaas.attributes.Pools;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.lbaasv2.rev150712.lbaas.attributes.pools.Pool;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.lbaasv2.rev150712.lbaas.attributes.pools.PoolKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.lbaasv2.rev150712.lbaas.attributes.pools.pool.Members;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.lbaasv2.rev150712.lbaas.attributes.pools.pool.members.Member;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class NeutronLoadBalancerPoolMemberChangeListener implements ClusteredDataChangeListener, AutoCloseable {
- private static final Logger LOG = LoggerFactory.getLogger(NeutronLoadBalancerPoolMemberChangeListener.class);
-
- private ListenerRegistration<DataChangeListener> registration;
- private DataBroker db;
-
- public NeutronLoadBalancerPoolMemberChangeListener(DataBroker db){
- this.db = db;
- InstanceIdentifier<Member> path = InstanceIdentifier
- .create(Neutron.class)
- .child(Pools.class)
- .child(Pool.class)
- .child(Members.class)
- .child(Member.class);
- LOG.debug("Register listener for Neutron Load Balancer Pool Member model data changes");
- registration =
- this.db.registerDataChangeListener(LogicalDatastoreType.CONFIGURATION, path, this,
- AsyncDataBroker.DataChangeScope.ONE);
- }
-
- @Override
- public void close() throws Exception {
- registration.close();
- }
-
- @Override
- public void onDataChanged(AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes) {
- LOG.trace("Data changes : {}", changes);
-
- Object[] subscribers = NeutronIAwareUtil.getInstances(INeutronLoadBalancerPoolMemberAware.class, this);
- createPoolMember(changes, subscribers);
- updatePoolMember(changes, subscribers);
- deletePoolMember(changes, subscribers);
- }
-
- private void createPoolMember(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes,
- Object[] subscribers) {
- for (Entry<InstanceIdentifier<?>, DataObject> newPoolMember : changes.getCreatedData().entrySet()) {
- if(newPoolMember.getValue() instanceof Member){
- NeutronLoadBalancerPoolMember neutronLBPoolMember = fromMd(newPoolMember.getKey(), (Member) newPoolMember.getValue());
- for (Object entry : subscribers) {
- INeutronLoadBalancerPoolMemberAware subscriber = (INeutronLoadBalancerPoolMemberAware) entry;
- subscriber.neutronLoadBalancerPoolMemberCreated(neutronLBPoolMember);
- }
- }
- }
- }
- private void updatePoolMember(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes,
- Object[] subscribers) {
- for (Entry<InstanceIdentifier<?>, DataObject> updatePoolMember : changes.getUpdatedData().entrySet()) {
- if(updatePoolMember.getValue() instanceof Member){
- NeutronLoadBalancerPoolMember neutronLBPoolMember =
- fromMd(updatePoolMember.getKey(), (Member) updatePoolMember.getValue());
- for(Object entry: subscribers){
- INeutronLoadBalancerPoolMemberAware subscriber = (INeutronLoadBalancerPoolMemberAware) entry;
- subscriber.neutronLoadBalancerPoolMemberUpdated(neutronLBPoolMember);
- }
- }
- }
- }
- private void deletePoolMember(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes,
- Object[] subscribers) {
- for (InstanceIdentifier<?> deletedPoolMemberPath : changes.getRemovedPaths()) {
- if(deletedPoolMemberPath.getTargetType().equals(Member.class)){
- NeutronLoadBalancerPoolMember neutronLBPoolMember =
- fromMd(deletedPoolMemberPath, (Member) changes.getOriginalData().get(deletedPoolMemberPath));
- for(Object entry: subscribers){
- INeutronLoadBalancerPoolMemberAware subscriber = (INeutronLoadBalancerPoolMemberAware) entry;
- subscriber.neutronLoadBalancerPoolMemberDeleted(neutronLBPoolMember);
- }
- }
- }
- }
-
- /*
- * This method is borrowed from NeutronLoadBalancerPoolMember.java class of Neutron Northbound class.
- * in the original location, this method is called extractFields.
- * We will be utilizing similar code from other classes from the same package of neutron project.
- */
- private NeutronLoadBalancerPoolMember fromMd(InstanceIdentifier<?> iid, Member member) {
- NeutronLoadBalancerPoolMember result = new NeutronLoadBalancerPoolMember();
-
- final PoolKey poolsKey = iid.firstKeyOf(Pool.class, PoolKey.class);
- if (poolsKey != null) {
- result.setPoolID(poolsKey.getUuid().getValue());
- }
-
- result.setID(member.getUuid().getValue());
- if (member.isAdminStateUp() != null) {
- result.setPoolMemberAdminStateIsUp(member.isAdminStateUp());
- }
-
- final IpAddress memberIpAddress = member.getAddress();
- if (memberIpAddress != null) {
- if (memberIpAddress.getIpv4Address() != null) {
- result.setPoolMemberAddress(memberIpAddress.getIpv4Address().getValue());
- } else if (memberIpAddress.getIpv6Address() != null) {
- result.setPoolMemberAddress(memberIpAddress.getIpv6Address().getValue());
- }
- }
-
- if (member.getProtocolPort() != null) {
- result.setPoolMemberProtoPort(member.getProtocolPort());
- }
- if (member.getSubnetId() != null) {
- result.setPoolMemberSubnetID(member.getSubnetId().getValue());
- }
- if (member.getTenantId() != null) {
- result.setPoolMemberTenantID(member.getTenantId().getValue());
- }
- if (member.getWeight() != null) {
- result.setPoolMemberWeight(member.getWeight());
- }
-
- return result;
- }
-}
-
+++ /dev/null
-/*
- * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt.translator.iaware.impl;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map.Entry;
-
-import org.opendaylight.controller.md.sal.binding.api.ClusteredDataChangeListener;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronNetworkAware;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork_Segment;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.ext.rev150712.NetworkL3Extension;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeBase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeFlat;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeGre;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeVlan;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeVxlan;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.Networks;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.networks.Network;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.provider.ext.rev150712.NetworkProviderExtension;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.provider.ext.rev150712.neutron.networks.network.Segments;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.ImmutableBiMap;
-
-public class NeutronNetworkChangeListener implements ClusteredDataChangeListener, AutoCloseable {
- private static final Logger LOG = LoggerFactory.getLogger(NeutronNetworkChangeListener.class);
-
- private static final ImmutableBiMap<Class<? extends NetworkTypeBase>,String> NETWORK_MAP
- = new ImmutableBiMap.Builder<Class<? extends NetworkTypeBase>,String>()
- .put(NetworkTypeFlat.class,"flat")
- .put(NetworkTypeGre.class,"gre")
- .put(NetworkTypeVlan.class,"vlan")
- .put(NetworkTypeVxlan.class,"vxlan")
- .build();
-
- static private String getNetworkTypeString(Class<? extends NetworkTypeBase> type) {
- String ret = NETWORK_MAP.get(type);
- if (ret == null) {
- ret = "flat";
- }
- return ret;
- }
-
- private ListenerRegistration<DataChangeListener> registration;
- private DataBroker db;
-
- public NeutronNetworkChangeListener(DataBroker db){
- this.db = db;
- InstanceIdentifier<Network> path = InstanceIdentifier
- .create(Neutron.class)
- .child(Networks.class)
- .child(Network.class);
- LOG.debug("Register listener for Neutron Network model data changes");
- registration =
- this.db.registerDataChangeListener(LogicalDatastoreType.CONFIGURATION, path, this, DataChangeScope.ONE);
-
- }
-
- @Override
- public void onDataChanged(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes) {
- LOG.trace("Data changes : {}",changes);
-
- Object[] subscribers = NeutronIAwareUtil.getInstances(INeutronNetworkAware.class, this);
- createNetwork(changes, subscribers);
- updateNetwork(changes, subscribers);
- deleteNetwork(changes, subscribers);
- }
-
- private void createNetwork(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes,
- Object[] subscribers) {
- for (Entry<InstanceIdentifier<?>, DataObject> newNetwork : changes.getCreatedData().entrySet()) {
- if(newNetwork.getValue() instanceof Network){
- NeutronNetwork network = fromMd((Network)newNetwork.getValue());
- for(Object entry: subscribers){
- INeutronNetworkAware subscriber = (INeutronNetworkAware)entry;
- subscriber.neutronNetworkCreated(network);
- }
- }
- }
- }
-
- private void updateNetwork(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes,
- Object[] subscribers) {
- for (Entry<InstanceIdentifier<?>, DataObject> updateNetwork : changes.getUpdatedData().entrySet()) {
- if(updateNetwork.getValue() instanceof Network){
- NeutronNetwork network = fromMd((Network)updateNetwork.getValue());
- for(Object entry: subscribers){
- INeutronNetworkAware subscriber = (INeutronNetworkAware)entry;
- subscriber.neutronNetworkUpdated(network);
- }
- }
- }
- }
-
- private void deleteNetwork(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes,
- Object[] subscribers) {
- for (InstanceIdentifier<?> deletedNetworkPath : changes.getRemovedPaths()) {
- if(deletedNetworkPath.getTargetType().equals(Network.class)){
- NeutronNetwork network = fromMd((Network)changes.getOriginalData().get(deletedNetworkPath));
- for(Object entry: subscribers){
- INeutronNetworkAware subscriber = (INeutronNetworkAware)entry;
- subscriber.neutronNetworkDeleted(network);
- }
- }
- }
- }
-
- /*
- * This method is borrowed from NeutronNetworkInterface.java class of Neutron Northbound class.
- * We will be utilizing similar code from other classes from the same package of neutron project.
- */
- private NeutronNetwork fromMd(Network network) {
- NeutronNetwork result = new NeutronNetwork();
- result.setAdminStateUp(network.isAdminStateUp());
- result.setNetworkName(network.getName());
- result.setShared(network.isShared());
- result.setStatus(network.getStatus());
-
- // todo remove '-' chars as tenant id doesn't use them
- if (network.getTenantId() != null) {
- result.setTenantID(network.getTenantId().getValue());
- }
- result.setID(network.getUuid().getValue());
-
- NetworkL3Extension l3Extension = network.getAugmentation(NetworkL3Extension.class);
- result.setRouterExternal(l3Extension.isExternal());
-
- NetworkProviderExtension providerExtension = network.getAugmentation(NetworkProviderExtension.class);
- result.setProviderPhysicalNetwork(providerExtension.getPhysicalNetwork());
- result.setProviderSegmentationID(providerExtension.getSegmentationId());
- result.setProviderNetworkType(getNetworkTypeString(providerExtension.getNetworkType()));
- List<NeutronNetwork_Segment> segments = new ArrayList<>();
- if (providerExtension.getSegments() != null) {
- for (Segments segment: providerExtension.getSegments()) {
- NeutronNetwork_Segment neutronSegment = new NeutronNetwork_Segment();
- neutronSegment.setProviderPhysicalNetwork(segment.getPhysicalNetwork());
- neutronSegment.setProviderSegmentationID(segment.getSegmentationId());
- neutronSegment.setProviderNetworkType(getNetworkTypeString(segment.getNetworkType()));
- segments.add(neutronSegment);
- }
- }
- result.setSegments(segments);
- return result;
- }
-
- @Override
- public void close() throws Exception {
- registration.close();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt.translator.iaware.impl;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import org.opendaylight.controller.md.sal.binding.api.ClusteredDataChangeListener;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort_AllowedAddressPairs;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort_ExtraDHCPOption;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityGroup;
-import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSecurityGroupCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.NeutronCRUDInterfaces;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronPortAware;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.binding.rev150712.PortBindingExtension;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.binding.rev150712.binding.attributes.VifDetails;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.AllowedAddressPairs;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.ExtraDhcpOpts;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.FixedIps;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.Ports;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.portsecurity.rev150712.PortSecurityExtension;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class NeutronPortChangeListener implements ClusteredDataChangeListener, AutoCloseable{
- private static final Logger LOG = LoggerFactory.getLogger(NeutronPortChangeListener.class);
-
- private ListenerRegistration<DataChangeListener> registration;
- private DataBroker db;
-
- public NeutronPortChangeListener(DataBroker db){
- this.db = db;
- InstanceIdentifier<Port> path = InstanceIdentifier
- .create(Neutron.class)
- .child(Ports.class)
- .child(Port.class);
- LOG.debug("Register listener for Neutron Port model data changes");
- registration =
- this.db.registerDataChangeListener(LogicalDatastoreType.CONFIGURATION, path, this, DataChangeScope.ONE);
-
- }
-
- @Override
- public void onDataChanged(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes) {
- LOG.trace("Data changes : {}",changes);
-
- Object[] subscribers = NeutronIAwareUtil.getInstances(INeutronPortAware.class, this);
- createPort(changes, subscribers);
- updatePort(changes, subscribers);
- deletePort(changes, subscribers);
- }
-
- private void createPort(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes,
- Object[] subscribers) {
- for (Entry<InstanceIdentifier<?>, DataObject> newPort : changes.getCreatedData().entrySet()) {
- if(newPort.getValue() instanceof Port){
- NeutronPort port = fromMd((Port)newPort.getValue());
- for(Object entry: subscribers){
- INeutronPortAware subscriber = (INeutronPortAware)entry;
- subscriber.neutronPortCreated(port);
- }
- }
- }
- }
-
- private void updatePort(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes,
- Object[] subscribers) {
- Map<String, NeutronPort> originalPortMap = getChangedPorts(changes.getOriginalData());
- for (Entry<InstanceIdentifier<?>, DataObject> updatePort : changes.getUpdatedData().entrySet()) {
- if (updatePort.getValue() instanceof Port) {
- NeutronPort port = fromMd((Port)updatePort.getValue());
- NeutronPort originalPort = originalPortMap.get(port.getID());
- if (originalPort != null) {
- port.setOriginalPort(originalPort);
- } else {
- LOG.warn("Original Port data is missing");
- }
- for (Object entry: subscribers) {
- INeutronPortAware subscriber = (INeutronPortAware)entry;
- subscriber.neutronPortUpdated(port);
- }
- }
- }
- }
-
- private void deletePort(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes,
- Object[] subscribers) {
- for (InstanceIdentifier<?> deletedPortPath : changes.getRemovedPaths()) {
- if(deletedPortPath.getTargetType().equals(Port.class)){
- NeutronPort port = fromMd((Port)changes.getOriginalData().get(deletedPortPath));
- for(Object entry: subscribers){
- INeutronPortAware subscriber = (INeutronPortAware)entry;
- subscriber.neutronPortDeleted(port);
- }
- }
- }
- }
-
- /*
- * This method is borrowed from NeutronPortInterface.java class of Neutron Northbound class.
- * We will be utilizing similar code from other classes from the same package of neutron project.
- */
- private NeutronPort fromMd(Port port) {
-
- NeutronPort result = new NeutronPort();
- result.setAdminStateUp(port.isAdminStateUp());
- if (port.getAllowedAddressPairs() != null) {
- List<NeutronPort_AllowedAddressPairs> pairs = new ArrayList<>();
- for (AllowedAddressPairs mdPair : port.getAllowedAddressPairs()) {
- NeutronPort_AllowedAddressPairs pair = new NeutronPort_AllowedAddressPairs();
- pair.setIpAddress(String.valueOf(mdPair.getIpAddress().getValue()));
- pair.setMacAddress(mdPair.getMacAddress().getValue());
- pairs.add(pair);
- }
- result.setAllowedAddressPairs(pairs);
- }
- result.setDeviceID(port.getDeviceId());
- result.setDeviceOwner(port.getDeviceOwner());
- if (port.getExtraDhcpOpts() != null) {
- List<NeutronPort_ExtraDHCPOption> options = new ArrayList<>();
- for (ExtraDhcpOpts opt : port.getExtraDhcpOpts()) {
- NeutronPort_ExtraDHCPOption arg = new NeutronPort_ExtraDHCPOption();
- arg.setName(opt.getOptName());
- arg.setValue(opt.getOptValue());
- options.add(arg);
- }
- result.setExtraDHCPOptions(options);
- }
- if (port.getFixedIps() != null) {
- List<Neutron_IPs> ips = new ArrayList<>();
- for (FixedIps mdIP : port.getFixedIps()) {
- Neutron_IPs ip = new Neutron_IPs();
- ip.setIpAddress(String.valueOf(mdIP.getIpAddress().getValue()));
- ip.setSubnetUUID(mdIP.getSubnetId().getValue());
- ips.add(ip);
- }
- result.setFixedIPs(ips);
- }
- result.setMacAddress(port.getMacAddress().getValue());
- result.setName(port.getName());
- result.setNetworkUUID(String.valueOf(port.getNetworkId().getValue()));
- if (port.getSecurityGroups() != null) {
- Set<NeutronSecurityGroup> allGroups = new HashSet<>();
- NeutronCRUDInterfaces interfaces = new NeutronCRUDInterfaces().fetchINeutronSecurityGroupCRUD(this);
- INeutronSecurityGroupCRUD sgIf = interfaces.getSecurityGroupInterface();
- for (Uuid sgUuid : port.getSecurityGroups()) {
- NeutronSecurityGroup secGroup = sgIf.getNeutronSecurityGroup(sgUuid.getValue());
- if (secGroup != null) {
- allGroups.add(sgIf.getNeutronSecurityGroup(sgUuid.getValue()));
- }
- }
- List<NeutronSecurityGroup> groups = new ArrayList<>();
- groups.addAll(allGroups);
- result.setSecurityGroups(groups);
- }
- result.setStatus(port.getStatus());
- if (port.getTenantId() != null) {
- result.setTenantID(String.valueOf(port.getTenantId().getValue()).replace("-", ""));
- }
- result.setPortUUID(String.valueOf(port.getUuid().getValue()));
- addExtensions(port, result);
- return result;
- }
-
- protected void addExtensions(Port port, NeutronPort result) {
- PortBindingExtension binding = port.getAugmentation(PortBindingExtension.class);
- result.setBindinghostID(binding.getHostId());
- if (binding.getVifDetails() != null) {
- final Map<String, String> details = new HashMap<>(binding.getVifDetails().size());
- for (final VifDetails vifDetail : binding.getVifDetails()) {
- details.put(vifDetail.getDetailsKey(), vifDetail.getValue());
- }
- result.setVIFDetails(details);
- }
- result.setBindingvifType(binding.getVifType());
- result.setBindingvnicType(binding.getVnicType());
- PortSecurityExtension portSecurity = port.getAugmentation(PortSecurityExtension.class);
- if (portSecurity != null && portSecurity.isPortSecurityEnabled() != null) {
- result.setPortSecurityEnabled(portSecurity.isPortSecurityEnabled());
- }
- }
-
- private Map<String,NeutronPort> getChangedPorts(Map<InstanceIdentifier<?>, DataObject> changedData) {
- LOG.trace("getChangedPorts:" + changedData);
- Map<String,NeutronPort> portMap = new HashMap<>();
- for (Map.Entry<InstanceIdentifier<?>, DataObject> changed : changedData.entrySet()) {
- if (changed.getValue() instanceof Port) {
- NeutronPort port = fromMd((Port)changed.getValue());
- portMap.put(port.getID(), port);
- }
- }
- return portMap;
- }
-
- @Override
- public void close() throws Exception {
- registration.close();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt.translator.iaware.impl;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.opendaylight.controller.md.sal.binding.api.ClusteredDataChangeListener;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronRouter;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronRouter_NetworkReference;
-import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronRouterAware;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.l3.attributes.Routes;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.Routers;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.routers.Router;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.routers.router.external_gateway_info.ExternalFixedIps;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class NeutronRouterChangeListener implements ClusteredDataChangeListener, AutoCloseable{
- private static final Logger LOG = LoggerFactory.getLogger(NeutronRouterChangeListener.class);
-
- private ListenerRegistration<DataChangeListener> registration;
- private DataBroker db;
-
- public NeutronRouterChangeListener(DataBroker db){
- this.db = db;
- InstanceIdentifier<Router> path = InstanceIdentifier
- .create(Neutron.class)
- .child(Routers.class)
- .child(Router.class);
- LOG.debug("Register listener for Neutron Router model data changes");
- registration =
- this.db.registerDataChangeListener(LogicalDatastoreType.CONFIGURATION, path, this, DataChangeScope.ONE);
-
- }
-
- @Override
- public void onDataChanged(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes) {
- LOG.trace("Data changes : {}",changes);
-
- Object[] subscribers = NeutronIAwareUtil.getInstances(INeutronRouterAware.class, this);
- createRouter(changes, subscribers);
- updateRouter(changes, subscribers);
- deleteRouter(changes, subscribers);
- }
-
- private void createRouter(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes,
- Object[] subscribers) {
- for (Entry<InstanceIdentifier<?>, DataObject> newRouter : changes.getCreatedData().entrySet()) {
- if(newRouter.getValue() instanceof Router){
- NeutronRouter router = fromMd((Router)newRouter.getValue());
- for(Object entry: subscribers){
- INeutronRouterAware subscriber = (INeutronRouterAware)entry;
- subscriber.neutronRouterCreated(router);
- }
- }
- }
-
- }
-
- private void updateRouter(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes,
- Object[] subscribers) {
- for (Entry<InstanceIdentifier<?>, DataObject> updateRouter : changes.getUpdatedData().entrySet()) {
- if(updateRouter.getValue() instanceof Router){
- NeutronRouter router = fromMd((Router)updateRouter.getValue());
- for(Object entry: subscribers){
- INeutronRouterAware subscriber = (INeutronRouterAware)entry;
- subscriber.neutronRouterUpdated(router);
- }
- }
- }
- }
-
- private void deleteRouter(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes,
- Object[] subscribers) {
- for (InstanceIdentifier<?> deletedRouterPath : changes.getRemovedPaths()) {
- if(deletedRouterPath.getTargetType().equals(Router.class)){
- NeutronRouter router = fromMd((Router)changes.getOriginalData().get(deletedRouterPath));
- for(Object entry: subscribers){
- INeutronRouterAware subscriber = (INeutronRouterAware)entry;
- subscriber.neutronRouterDeleted(router);
- }
- }
- }
- }
-
- /*
- * This method is borrowed from NeutronRouterInterface.java class of Neutron Northbound class.
- * We will be utilizing similar code from other classes from the same package of neutron project.
- */
- private NeutronRouter fromMd(Router router) {
- NeutronRouter result = new NeutronRouter();
- result.setID(String.valueOf(router.getUuid().getValue()));
- result.setName(router.getName());
- if (router.getTenantId() != null) {
- result.setTenantID(String.valueOf(router.getTenantId().getValue()));
- }
- result.setAdminStateUp(router.isAdminStateUp());
- result.setStatus(router.getStatus());
- result.setDistributed(router.isDistributed());
- if (router.getGatewayPortId() != null) {
- result.setGatewayPortId(String.valueOf(router.getGatewayPortId().getValue()));
- }
- if (router.getRoutes() != null) {
- List<Routes> routes = new ArrayList<>();
- for (Routes route : router.getRoutes()) {
- routes.add(route);
- }
- result.setRoutes(routes);
- }
-
- if (router.getExternalGatewayInfo() != null) {
- NeutronRouter_NetworkReference extGwInfo = new NeutronRouter_NetworkReference();
- extGwInfo.setNetworkID(String.valueOf(router.getExternalGatewayInfo().getExternalNetworkId().getValue()));
- extGwInfo.setEnableSNAT(router.getExternalGatewayInfo().isEnableSnat());
- if (router.getExternalGatewayInfo().getExternalFixedIps() != null) {
- List<Neutron_IPs> fixedIPs = new ArrayList<>();
- for (ExternalFixedIps mdFixedIP : router.getExternalGatewayInfo().getExternalFixedIps()) {
- Neutron_IPs fixedIP = new Neutron_IPs();
- fixedIP.setSubnetUUID(String.valueOf(mdFixedIP.getSubnetId().getValue()));
- fixedIP.setIpAddress(String.valueOf(mdFixedIP.getIpAddress().getValue()));
- fixedIPs.add(fixedIP);
- }
- extGwInfo.setExternalFixedIPs(fixedIPs);
- }
- result.setExternalGatewayInfo(extGwInfo);
- }
-
- return result;
- }
-
- @Override
- public void close() throws Exception {
- registration.close();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt.translator.iaware.impl;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map.Entry;
-
-import org.opendaylight.controller.md.sal.binding.api.ClusteredDataChangeListener;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSecurityRuleCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityGroup;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityRule;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.NeutronCRUDInterfaces;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronSecurityGroupAware;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.SecurityGroups;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.security.groups.SecurityGroup;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class NeutronSecurityGroupDataChangeListener implements ClusteredDataChangeListener, AutoCloseable {
- private static final Logger LOG = LoggerFactory
- .getLogger(NeutronSecurityGroupDataChangeListener.class);
-
- private ListenerRegistration<DataChangeListener> registration;
- private DataBroker db;
-
- public NeutronSecurityGroupDataChangeListener(DataBroker db) {
- this.db = db;
- InstanceIdentifier<SecurityGroup> path = InstanceIdentifier
- .create(Neutron.class).child(SecurityGroups.class)
- .child(SecurityGroup.class);
- LOG.debug("Register listener for Neutron Secutiry group model data changes");
- registration = this.db.registerDataChangeListener(
- LogicalDatastoreType.CONFIGURATION, path, this,
- DataChangeScope.ONE);
-
- }
-
- @Override
- public void onDataChanged(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes) {
- LOG.trace("Data changes : {}", changes);
-
- Object[] subscribers = NeutronIAwareUtil.getInstances(
- INeutronSecurityGroupAware.class, this);
- createSecurityGroup(changes, subscribers);
- updateSecurityGroup(changes, subscribers);
- deleteSecurityGroup(changes, subscribers);
- }
-
- private void createSecurityGroup(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes,
- Object[] subscribers) {
- for (Entry<InstanceIdentifier<?>, DataObject> newSecutiryGroup : changes
- .getCreatedData().entrySet()) {
- if (newSecutiryGroup.getValue() instanceof SecurityGroup) {
- NeutronSecurityGroup secutiryGroup = fromMd((SecurityGroup) newSecutiryGroup
- .getValue());
- for (Object entry : subscribers) {
- INeutronSecurityGroupAware subscriber = (INeutronSecurityGroupAware) entry;
- subscriber.neutronSecurityGroupCreated(secutiryGroup);
- }
- }
- }
-
- }
-
- private void updateSecurityGroup(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes,
- Object[] subscribers) {
- for (Entry<InstanceIdentifier<?>, DataObject> updateSecurityGroup : changes
- .getUpdatedData().entrySet()) {
- if (updateSecurityGroup.getValue() instanceof SecurityGroup) {
- NeutronSecurityGroup securityGroup = fromMd((SecurityGroup) updateSecurityGroup
- .getValue());
- for (Object entry : subscribers) {
- INeutronSecurityGroupAware subscriber = (INeutronSecurityGroupAware) entry;
- subscriber.neutronSecurityGroupUpdated(securityGroup);
- }
- }
- }
- }
-
- private void deleteSecurityGroup(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes,
- Object[] subscribers) {
- for (InstanceIdentifier<?> deletedSecurityGroup : changes
- .getRemovedPaths()) {
- if (deletedSecurityGroup.getTargetType()
- .equals(SecurityGroup.class)) {
- NeutronSecurityGroup securityGroup = fromMd((SecurityGroup) changes
- .getOriginalData().get(deletedSecurityGroup));
- for (Object entry : subscribers) {
- INeutronSecurityGroupAware subscriber = (INeutronSecurityGroupAware) entry;
- subscriber.neutronSecurityGroupDeleted(securityGroup);
- }
- }
- }
- }
-
- private NeutronSecurityGroup fromMd(SecurityGroup group) {
- NeutronSecurityGroup answer = new NeutronSecurityGroup();
- if (group.getName() != null) {
- answer.setSecurityGroupName(group.getName());
- }
- if (group.getTenantId() != null) {
- answer.setSecurityGroupTenantID(group.getTenantId().getValue()
- .replace("-", ""));
- }
- if (group.getUuid() != null) {
- answer.setID(group.getUuid().getValue());
- }
- return answer;
- }
-
- @Override
- public void close() throws Exception {
- registration.close();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt.translator.iaware.impl;
-
-import java.util.Map.Entry;
-
-import org.opendaylight.controller.md.sal.binding.api.ClusteredDataChangeListener;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronSecurityRuleAware;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityRule;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionBase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionEgress;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionIngress;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeBase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeV4;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeV6;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolBase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolIcmp;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolIcmpV6;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolTcp;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolUdp;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.SecurityRuleAttributes;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.SecurityRules;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRule;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.ImmutableBiMap;
-
-public class NeutronSecurityRuleDataChangeListener implements ClusteredDataChangeListener, AutoCloseable {
-
- private static final Logger LOG = LoggerFactory.getLogger(NeutronSecurityRuleDataChangeListener.class);
-
- private static final ImmutableBiMap<Class<? extends DirectionBase>, String> DIRECTION_MAP = ImmutableBiMap.of(
- DirectionEgress.class, NeutronSecurityRule.DIRECTION_EGRESS,
- DirectionIngress.class, NeutronSecurityRule.DIRECTION_INGRESS);
- private static final ImmutableBiMap<Class<? extends ProtocolBase>, String> PROTOCOL_MAP = ImmutableBiMap.of(
- ProtocolIcmp.class, NeutronSecurityRule.PROTOCOL_ICMP,
- ProtocolTcp.class, NeutronSecurityRule.PROTOCOL_TCP,
- ProtocolUdp.class, NeutronSecurityRule.PROTOCOL_UDP,
- ProtocolIcmpV6.class, NeutronSecurityRule.PROTOCOL_ICMPV6);
- private static final ImmutableBiMap<Class<? extends EthertypeBase>,String> ETHERTYPE_MAP = ImmutableBiMap.of(
- EthertypeV4.class, NeutronSecurityRule.ETHERTYPE_IPV4,
- EthertypeV6.class, NeutronSecurityRule.ETHERTYPE_IPV6);
-
- private ListenerRegistration<DataChangeListener> registration;
-
- public NeutronSecurityRuleDataChangeListener(DataBroker db) {
- InstanceIdentifier<SecurityRule> path = InstanceIdentifier
- .create(Neutron.class).child(SecurityRules.class)
- .child(SecurityRule.class);
- LOG.debug("Register listener for Neutron Secutiry rules model data changes");
- registration = db.registerDataChangeListener(
- LogicalDatastoreType.CONFIGURATION, path, this,
- DataChangeScope.ONE);
-
- }
-
- @Override
- public void onDataChanged(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes) {
- LOG.trace("Data changes : {}", changes);
-
- Object[] subscribers = NeutronIAwareUtil.getInstances(
- INeutronSecurityRuleAware.class, this);
- createSecurityRule(changes, subscribers);
- updateSecurityRule(changes, subscribers);
- deleteSecurityRule(changes, subscribers);
- }
-
- private void createSecurityRule(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes,
- Object[] subscribers) {
- for (Entry<InstanceIdentifier<?>, DataObject> newSecutiryRule : changes
- .getCreatedData().entrySet()) {
- if (newSecutiryRule.getValue() instanceof SecurityRule) {
- NeutronSecurityRule secutiryRule = fromMd((SecurityRule) newSecutiryRule
- .getValue());
- for (Object entry : subscribers) {
- INeutronSecurityRuleAware subscriber = (INeutronSecurityRuleAware) entry;
- subscriber.neutronSecurityRuleCreated(secutiryRule);
- }
- }
- }
-
- }
-
- private void updateSecurityRule(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes,
- Object[] subscribers) {
- for (Entry<InstanceIdentifier<?>, DataObject> updateSecurityRule : changes
- .getUpdatedData().entrySet()) {
- if (updateSecurityRule.getValue() instanceof SecurityRule) {
- NeutronSecurityRule securityRule = fromMd((SecurityRule) updateSecurityRule
- .getValue());
- for (Object entry : subscribers) {
- INeutronSecurityRuleAware subscriber = (INeutronSecurityRuleAware) entry;
- subscriber.neutronSecurityRuleUpdated(securityRule);
- }
- }
- }
- }
-
- private void deleteSecurityRule(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes,
- Object[] subscribers) {
- for (InstanceIdentifier<?> deletedSecurityRule : changes
- .getRemovedPaths()) {
- if (deletedSecurityRule.getTargetType().equals(SecurityRule.class)) {
- NeutronSecurityRule securityRule = fromMd((SecurityRule) changes
- .getOriginalData().get(deletedSecurityRule));
- for (Object entry : subscribers) {
- INeutronSecurityRuleAware subscriber = (INeutronSecurityRuleAware) entry;
- subscriber.neutronSecurityRuleDeleted(securityRule);
- }
- }
- }
- }
-
- private NeutronSecurityRule fromMd(SecurityRule rule) {
- NeutronSecurityRule answer = new NeutronSecurityRule();
- if (rule.getTenantId() != null) {
- answer.setSecurityRuleTenantID(rule.getTenantId().getValue()
- .replace("-", ""));
- }
- if (rule.getDirection() != null) {
- answer.setSecurityRuleDirection(DIRECTION_MAP.get(rule
- .getDirection()));
- }
- if (rule.getSecurityGroupId() != null) {
- answer.setSecurityRuleGroupID(rule.getSecurityGroupId().getValue());
- }
- if (rule.getRemoteGroupId() != null) {
- answer.setSecurityRemoteGroupID(rule.getRemoteGroupId().getValue());
- }
- if (rule.getRemoteIpPrefix() != null) {
- answer.setSecurityRuleRemoteIpPrefix(rule.getRemoteIpPrefix().getIpv4Prefix()!= null?
- rule.getRemoteIpPrefix().getIpv4Prefix().getValue():rule.getRemoteIpPrefix().getIpv6Prefix().getValue());
- }
- if (rule.getProtocol() != null) {
- SecurityRuleAttributes.Protocol protocol = rule.getProtocol();
- if (protocol.getUint8() != null) {
- // uint8
- answer.setSecurityRuleProtocol(protocol.getUint8().toString());
- } else {
- // symbolic protocol name
- answer.setSecurityRuleProtocol(PROTOCOL_MAP.get(rule.getProtocol().getIdentityref()));
- }
- }
- if (rule.getEthertype() != null) {
- answer.setSecurityRuleEthertype(ETHERTYPE_MAP.get(rule
- .getEthertype()));
- }
- if (rule.getPortRangeMin() != null) {
- answer.setSecurityRulePortMin(rule.getPortRangeMin());
- }
- if (rule.getPortRangeMax() != null) {
- answer.setSecurityRulePortMax(rule.getPortRangeMax());
- }
- if (rule.getUuid() != null) {
- answer.setID(rule.getUuid().getValue());
- }
- return answer;
- }
-
- @Override
- public void close() throws Exception {
- registration.close();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.netvirt.translator.iaware.impl;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map.Entry;
-import java.util.Set;
-
-import org.opendaylight.controller.md.sal.binding.api.ClusteredDataChangeListener;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSubnet;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSubnetIPAllocationPool;
-import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronPortCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.NeutronCRUDInterfaces;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.INeutronSubnetAware;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.Dhcpv6Base;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.Dhcpv6Off;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.Dhcpv6Slaac;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.Dhcpv6Stateful;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.Dhcpv6Stateless;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.IpVersionBase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.IpVersionV4;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.IpVersionV6;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnet.attributes.AllocationPools;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.Subnets;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.ImmutableBiMap;
-
-public class NeutronSubnetChangeListener implements ClusteredDataChangeListener, AutoCloseable{
- private static final Logger LOG = LoggerFactory.getLogger(NeutronSubnetChangeListener.class);
-
- private static final ImmutableBiMap<Class<? extends IpVersionBase>,Integer> IPV_MAP
- = new ImmutableBiMap.Builder<Class<? extends IpVersionBase>,Integer>()
- .put(IpVersionV4.class, 4)
- .put(IpVersionV6.class, 6)
- .build();
-
- private static final ImmutableBiMap<Class<? extends Dhcpv6Base>,String> DHCPV6_MAP
- = new ImmutableBiMap.Builder<Class<? extends Dhcpv6Base>,String>()
- .put(Dhcpv6Off.class,"off")
- .put(Dhcpv6Stateful.class,"dhcpv6-stateful")
- .put(Dhcpv6Slaac.class,"slaac")
- .put(Dhcpv6Stateless.class,"dhcpv6-stateless")
- .build();
-
- private ListenerRegistration<DataChangeListener> registration;
- private DataBroker db;
-
- public NeutronSubnetChangeListener(DataBroker db){
- this.db = db;
- InstanceIdentifier<Subnet> path = InstanceIdentifier
- .create(Neutron.class)
- .child(Subnets.class)
- .child(Subnet.class);
- LOG.debug("Register listener for Neutron Subnet model data changes");
- registration =
- this.db.registerDataChangeListener(LogicalDatastoreType.CONFIGURATION, path, this, DataChangeScope.ONE);
-
- }
-
- @Override
- public void onDataChanged(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes) {
- LOG.trace("Data changes : {}",changes);
-
- Object[] subscribers = NeutronIAwareUtil.getInstances(INeutronSubnetAware.class, this);
- createSubnet(changes, subscribers);
- updateSubnet(changes, subscribers);
- deleteSubnet(changes, subscribers);
- }
-
- private void createSubnet(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes,
- Object[] subscribers) {
- for (Entry<InstanceIdentifier<?>, DataObject> newSubnet : changes.getCreatedData().entrySet()) {
- if(newSubnet.getValue() instanceof Subnet){
- NeutronSubnet subnet = fromMd((Subnet)newSubnet.getValue());
- for(Object entry: subscribers){
- INeutronSubnetAware subscriber = (INeutronSubnetAware)entry;
- subscriber.neutronSubnetCreated(subnet);
- }
- }
- }
- }
-
- private void updateSubnet(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes,
- Object[] subscribers) {
- for (Entry<InstanceIdentifier<?>, DataObject> updateSubnet : changes.getUpdatedData().entrySet()) {
- if(updateSubnet.getValue() instanceof Subnet){
- NeutronSubnet subnet = fromMd((Subnet)updateSubnet.getValue());
- for(Object entry: subscribers){
- INeutronSubnetAware subscriber = (INeutronSubnetAware)entry;
- subscriber.neutronSubnetUpdated(subnet);
- }
- }
- }
- }
-
- private void deleteSubnet(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes,
- Object[] subscribers) {
- for (InstanceIdentifier<?> deletedSubnetPath : changes.getRemovedPaths()) {
- if(deletedSubnetPath.getTargetType().equals(Subnet.class)){
- NeutronSubnet subnet = fromMd((Subnet)changes.getOriginalData().get(deletedSubnetPath));
- for(Object entry: subscribers){
- INeutronSubnetAware subscriber = (INeutronSubnetAware)entry;
- subscriber.neutronSubnetDeleted(subnet);
- }
- }
- }
- }
-
- /*
- * This method is borrowed from NeutronSubnetInterface.java class of Neutron Northbound class.
- * We will be utilizing similar code from other classes from the same package of neutron project.
- */
- private NeutronSubnet fromMd(Subnet subnet) {
- NeutronSubnet result = new NeutronSubnet();
- result.setName(subnet.getName());
- if (subnet.getTenantId() != null) {
- result.setTenantID(String.valueOf(subnet.getTenantId().getValue()).replace("-",""));
- }
- result.setNetworkUUID(subnet.getNetworkId().getValue());
- result.setIpVersion(IPV_MAP.get(subnet.getIpVersion()));
- result.setCidr(String.valueOf(subnet.getCidr().getValue()));
- if (subnet.getGatewayIp() != null) {
- result.setGatewayIP(String.valueOf(subnet.getGatewayIp().getValue()));
- }
- if (subnet.getIpv6RaMode() != null) {
- result.setIpV6RaMode(DHCPV6_MAP.get(subnet.getIpv6RaMode()));
- }
- if (subnet.getIpv6AddressMode() != null) {
- result.setIpV6AddressMode(DHCPV6_MAP.get(subnet.getIpv6AddressMode()));
- }
- result.setEnableDHCP(subnet.isEnableDhcp());
- if (subnet.getAllocationPools() != null) {
- List<NeutronSubnetIPAllocationPool> allocationPools = new ArrayList<>();
- for (AllocationPools allocationPool : subnet.getAllocationPools()) {
- NeutronSubnetIPAllocationPool pool = new NeutronSubnetIPAllocationPool();
- pool.setPoolStart(String.valueOf(allocationPool.getStart().getValue()));
- pool.setPoolEnd(String.valueOf(allocationPool.getEnd().getValue()));
- allocationPools.add(pool);
- }
- result.setAllocationPools(allocationPools);
- }
- if (subnet.getDnsNameservers() != null) {
- List<String> dnsNameServers = new ArrayList<>();
- for (IpAddress dnsNameServer : subnet.getDnsNameservers()) {
- dnsNameServers.add(String.valueOf(dnsNameServer.getValue()));
- }
- result.setDnsNameservers(dnsNameServers);
- }
- result.setID(subnet.getUuid().getValue());
-
- // read through the ports and put the ones in this subnet into the internal
- // myPorts object.
- Set<NeutronPort> allPorts = new HashSet<>();
- NeutronCRUDInterfaces interfaces = new NeutronCRUDInterfaces()
- .fetchINeutronPortCRUD(this);
- INeutronPortCRUD portIf = interfaces.getPortInterface();
- for (NeutronPort port : portIf.getAllPorts()) {
- if (port.getFixedIPs() != null) {
- for (Neutron_IPs ip : port.getFixedIPs()) {
- if (ip.getSubnetUUID().equals(result.getID())) {
- allPorts.add(port);
- }
- }
- }
- }
- List<NeutronPort> ports = new ArrayList<>();
- ports.addAll(allPorts);
- result.setPorts(ports);
- return result;
- }
-
- @Override
- public void close() throws Exception {
- registration.close();
- }
-
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
- xmlns:odl="http://opendaylight.org/xmlns/blueprint/v1.0.0"
- odl:use-default-for-reference-types="true">
-
- <reference id="dataBroker"
- interface="org.opendaylight.controller.md.sal.binding.api.DataBroker" />
- <reference id="entityOwnershipService"
- interface="org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService" />
-
- <odl:clustered-app-config id="netvirtImplConfig"
- binding-class="org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.impl.config.rev160517.NetvirtImplConfig">
- </odl:clustered-app-config>
-
- <bean id="netvirtProvider"
- class="org.opendaylight.netvirt.openstack.netvirt.NetvirtProvider"
- init-method="start" destroy-method="close">
- <argument ref="dataBroker" />
- <argument ref="entityOwnershipService" />
- <argument>
- <bean factory-ref="netvirtImplConfig" factory-method="isConntrackEnabled" />
- </argument>
- <argument>
- <bean factory-ref="netvirtImplConfig" factory-method="isIntBridgeGenMac" />
- </argument>
- </bean>
-
-</blueprint>
\ No newline at end of file
+++ /dev/null
-module netvirt-impl-config {
- yang-version 1;
- namespace "urn:opendaylight:params:xml:ns:yang:netvirt:impl:config";
- prefix "netvirt-impl-config";
-
- description
- "Configuration for Netvirt Impl.";
-
- revision "2016-05-17" {
- description
- "Initial revision.";
- }
-
- container netvirt-impl-config {
- leaf conntrack-enabled {
- type boolean;
- default false;
- }
- leaf int-bridge-gen-mac {
- type boolean;
- default true;
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Inocybe 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.netvirt.openstack.netvirt;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.netvirt.openstack.netvirt.AbstractEvent.HandlerType;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-
-/**
- * Unit test for {@link AbstractEvent}
- */
-public class AbstractEventTest {
-
- private AbstractEventChild1 abstractEvent1;
- private AbstractEventChild2 abstractEvent2;
- private AbstractEventChild2 abstractEvent3;
-
- class AbstractEventChild1 extends AbstractEvent{
- protected AbstractEventChild1(HandlerType handlerType, Action action) {
- super(handlerType, action);
- }
-
- }
-
- class AbstractEventChild2 extends AbstractEvent{
- protected AbstractEventChild2(HandlerType handlerType, Action action) {
- super(handlerType, action);
- }
- }
-
-
- @Before
- public void setUp(){
- abstractEvent1 = new AbstractEventChild1(HandlerType.SOUTHBOUND, Action.DELETE);
- abstractEvent2 = new AbstractEventChild2(HandlerType.NEUTRON_FLOATING_IP, Action.ADD);
- abstractEvent3 = abstractEvent2;
- }
-
- @Test
- public void testAbstractEvent(){
- assertEquals("Error, getAction() did not return the correct value", Action.DELETE, abstractEvent1.getAction());
-
- assertEquals("Error, getHandlerType() did not return the correct value", HandlerType.SOUTHBOUND, abstractEvent1.getHandlerType());
-
- assertTrue("Error, equals() did not succeed", abstractEvent2.equals(abstractEvent3));
-
- assertNotNull("Error, hashCode() did not return any value", abstractEvent1.hashCode());
- assertEquals("Error, hashCode() is not consistent", abstractEvent2.hashCode(), abstractEvent3.hashCode());
-
- int transactionId = abstractEvent1.getTransactionId();
- assertEquals("Error, toString() did not return the correct value",
- "AbstractEvent [transactionId=" + transactionId + " handlerType=SOUTHBOUND action=DELETE]", abstractEvent1.toString());
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Inocybe 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.netvirt.openstack.netvirt;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import java.net.HttpURLConnection;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.netvirt.openstack.netvirt.api.StatusCode;
-import org.opendaylight.netvirt.openstack.netvirt.api.EventDispatcher;
-import org.opendaylight.netvirt.openstack.netvirt.api.Status;
-
-/**
- * Unit test for {@link AbstractHandler}
- */
-@RunWith(MockitoJUnitRunner.class)
-public class AbstractHandlerTest {
-
- @InjectMocks private AbstractHandler abstractHandler = mock(AbstractHandler.class, Mockito.CALLS_REAL_METHODS);
- @Mock private EventDispatcher eventDispatcher;
-
- @Test
- public void testGetException() {
- Status status = mock(Status.class);
-
- when(status.getCode())
- .thenReturn(StatusCode.BADREQUEST)
- .thenReturn(StatusCode.CONFLICT)
- .thenReturn(StatusCode.NOTACCEPTABLE)
- .thenReturn(StatusCode.NOTFOUND)
- .thenReturn(StatusCode.GONE);
-
- assertEquals(
- "Error, getException() did not return the correct neutron API service error",
- HttpURLConnection.HTTP_BAD_REQUEST,
- AbstractHandler.getException(status));
- assertEquals(
- "Error, getException() did not return the correct neutron API service error",
- HttpURLConnection.HTTP_CONFLICT,
- AbstractHandler.getException(status));
- assertEquals(
- "Error, getException() did not return the correct neutron API service error",
- HttpURLConnection.HTTP_NOT_ACCEPTABLE,
- AbstractHandler.getException(status));
- assertEquals(
- "Error, getException() did not return the correct neutron API service error",
- HttpURLConnection.HTTP_NOT_FOUND,
- AbstractHandler.getException(status));
- assertEquals(
- "Error, getException() did not return the correct neutron API service error",
- HttpURLConnection.HTTP_INTERNAL_ERROR,
- AbstractHandler.getException(status));
- }
-
- @Test
- public void testEnqueueEvent() throws Exception {
- abstractHandler.enqueueEvent(mock(AbstractEvent.class));
- verify(eventDispatcher, times(1)).enqueueEvent(any(AbstractEvent.class));
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2016 Inocybe 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.netvirt.openstack.netvirt;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyNoMoreInteractions;
-
-import java.net.HttpURLConnection;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.Mockito;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronFirewall;
-import org.opendaylight.netvirt.openstack.netvirt.api.EventDispatcher;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronFirewallPolicy;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronFirewallRule;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.osgi.framework.ServiceReference;
-
-
-/**
- * Unit test for {@link FWaasHandler}
- */
-@RunWith(MockitoJUnitRunner.class)
-public class FWaasHandlerTest {
-
- @InjectMocks FWaasHandler fwaasHandler;
-
- @Before
- public void setUp() {
- fwaasHandler = mock(FWaasHandler.class, Mockito.CALLS_REAL_METHODS);
- }
-
- @Test
- public void testCanCreateNeutronFirewall(){
- assertEquals("Error, canCreateNeutronFirewall() did not return the correct value ", HttpURLConnection.HTTP_CREATED, fwaasHandler.canCreateNeutronFirewall(any(NeutronFirewall.class)));
- }
-
- @Test
- public void testNeutronFirewallCreated(){
- verifyNoMoreInteractions(fwaasHandler);
- fwaasHandler.canCreateNeutronFirewall(mock(NeutronFirewall.class));
- verify(fwaasHandler, times(1)).canCreateNeutronFirewall(any(NeutronFirewall.class));
- }
-
- @Test
- public void testCanUpdateNeutronFirewall(){
- assertEquals("Error, canUpdateNeutronFirewall() did not return the correct value ", HttpURLConnection.HTTP_OK, fwaasHandler.canUpdateNeutronFirewall(any(NeutronFirewall.class), any(NeutronFirewall.class)));
- }
-
- @Test
- public void testCanDeleteNeutronFirewall(){
- assertEquals("Error, canDeleteNeutronFirewall() did not return the correct value ", HttpURLConnection.HTTP_OK, fwaasHandler.canDeleteNeutronFirewall(any(NeutronFirewall.class)));
- }
-
- @Test
- public void testNeutronFirewallDeleted(){
- verifyNoMoreInteractions(fwaasHandler);
- fwaasHandler.neutronFirewallDeleted(mock(NeutronFirewall.class));
- verify(fwaasHandler, times(1)).canDeleteNeutronFirewall(any(NeutronFirewall.class));
- }
-
- @Test
- public void testCanCreateNeutronFirewallRule(){
- assertEquals("Error, canCreateNeutronFirewallRule() did not return the correct value ", HttpURLConnection.HTTP_CREATED, fwaasHandler.canCreateNeutronFirewallRule(any(NeutronFirewallRule.class)));
- }
-
- @Test
- public void testNeutronFirewallRuleCreated(){
- verifyNoMoreInteractions(fwaasHandler);
- fwaasHandler.neutronFirewallRuleCreated(mock(NeutronFirewallRule.class));
- verify(fwaasHandler, times(1)).canCreateNeutronFirewallRule(any(NeutronFirewallRule.class));
- }
-
- @Test
- public void testCanUpdateNeutronFirewallRule(){
- assertEquals("Error, canUpdateNeutronFirewallRule() did not return the correct value ", HttpURLConnection.HTTP_OK, fwaasHandler.canUpdateNeutronFirewallRule(any(NeutronFirewallRule.class), any(NeutronFirewallRule.class)));
- }
-
- @Test
- public void testCanDeleteNeutronFirewallRule(){
- assertEquals("Error, canDeleteNeutronFirewallRule() did not return the correct value ", HttpURLConnection.HTTP_OK, fwaasHandler.canDeleteNeutronFirewallRule(any(NeutronFirewallRule.class)));
- }
-
- @Test
- public void testNeutronFirewallRuleDeleted(){
- verifyNoMoreInteractions(fwaasHandler);
- fwaasHandler.neutronFirewallRuleDeleted(mock(NeutronFirewallRule.class));
- verify(fwaasHandler, times(1)).canDeleteNeutronFirewallRule(any(NeutronFirewallRule.class));
- }
-
- @Test
- public void testCanCreateNeutronFirewallPolicy(){
- assertEquals("Error, canCreateNeutronFirewallPolicy() did not return the correct value ", HttpURLConnection.HTTP_CREATED, fwaasHandler.canCreateNeutronFirewallPolicy(any(NeutronFirewallPolicy.class)));
- }
-
- @Test
- public void testNeutronFirewallPolicyCreated(){
- verifyNoMoreInteractions(fwaasHandler);
- fwaasHandler.neutronFirewallPolicyCreated(mock(NeutronFirewallPolicy.class));
- verify(fwaasHandler, times(1)).canCreateNeutronFirewallPolicy(any(NeutronFirewallPolicy.class));
- }
-
- @Test
- public void testCanUpdateNeutronFirewallPolicy(){
- assertEquals("Error, canUpdateNeutronFirewallPolicy() did not return the correct value ", HttpURLConnection.HTTP_OK, fwaasHandler.canUpdateNeutronFirewallPolicy(any(NeutronFirewallPolicy.class), any(NeutronFirewallPolicy.class)));
- }
-
- @Test
- public void testCanDeleteNeutronFirewallPolicy(){
- assertEquals("Error, canDeleteNeutronFirewallPolicy() did not return the correct value ", HttpURLConnection.HTTP_OK, fwaasHandler.canDeleteNeutronFirewallPolicy(any(NeutronFirewallPolicy.class)));
- }
-
- @Test
- public void testNeutronFirewallPolicyDeleted(){
- verifyNoMoreInteractions(fwaasHandler);
- fwaasHandler.neutronFirewallPolicyDeleted(mock(NeutronFirewallPolicy.class));
- verify(fwaasHandler, times(1)).canDeleteNeutronFirewallPolicy(any(NeutronFirewallPolicy.class));
- }
-
- @Test
- public void testProcessEvent(){
- // TODO
- // no yet implemented
-// NorthboundEvent ev = mock(NorthboundEvent.class);
-// when(ev.getAction()).thenReturn(Action.ADD);
-// fwaasHandler.processEvent(ev);
- }
-
- @Test
- public void testSetDependencies() {
- EventDispatcher eventDispatcher = mock(EventDispatcher.class);
-
- ServiceHelper.overrideGlobalInstance(EventDispatcher.class, eventDispatcher);
-
- fwaasHandler.setDependencies(mock(ServiceReference.class));
-
- assertEquals("Error, did not return the correct object", fwaasHandler.eventDispatcher, eventDispatcher);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2016 Inocybe 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.netvirt.openstack.netvirt;
-
-import static org.junit.Assert.assertEquals;
-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;
-import java.net.HttpURLConnection;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronFloatingIP;
-import org.opendaylight.netvirt.openstack.netvirt.api.EventDispatcher;
-import org.opendaylight.netvirt.openstack.netvirt.impl.NeutronL3Adapter;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.osgi.framework.ServiceReference;
-
-/**
- * Unit test for {@link FloatingIPHandler}
- */
-@RunWith(MockitoJUnitRunner.class)
-public class FloatingIPHandlerTest {
-
- @InjectMocks FloatingIPHandler floatingHandler;
- @Mock NeutronL3Adapter neutronL3Adapter;
-
- @Test
- public void testCanCreateFloatingIP(){
- assertEquals("Error, did not return the correct HTTP status code", HttpURLConnection.HTTP_OK, floatingHandler.canCreateFloatingIP(mock(NeutronFloatingIP.class)));
- }
-
- @Test
- public void testCanUpdateFloatingIP(){
- assertEquals("Error, did not return the correct HTTP status code", HttpURLConnection.HTTP_OK, floatingHandler.canUpdateFloatingIP(mock(NeutronFloatingIP.class), mock(NeutronFloatingIP.class)));
- }
-
- @Test
- public void testCanDeleteFloatingIP(){
- assertEquals("Error, did not return the correct HTTP status code", HttpURLConnection.HTTP_OK, floatingHandler.canDeleteFloatingIP(mock(NeutronFloatingIP.class)));
- }
-
- @Test
- public void testProcessEvent(){
- NorthboundEvent ev = mock(NorthboundEvent.class);
-
- when(ev.getNeutronFloatingIP()).thenReturn(mock(NeutronFloatingIP.class));
-
- when(ev.getAction()).thenReturn(Action.UPDATE);
- floatingHandler.processEvent(ev);
- verify(neutronL3Adapter, times(1)).handleNeutronFloatingIPEvent(ev.getNeutronFloatingIP(), ev.getAction());
-
- when(ev.getAction()).thenReturn(Action.ADD);
- floatingHandler.processEvent(ev);
- verify(neutronL3Adapter, times(1)).handleNeutronFloatingIPEvent(ev.getNeutronFloatingIP(), ev.getAction());
-
- when(ev.getAction()).thenReturn(Action.DELETE);
- floatingHandler.processEvent(ev);
- verify(neutronL3Adapter, times(1)).handleNeutronFloatingIPEvent(ev.getNeutronFloatingIP(), ev.getAction());
- }
-
- @Test
- public void testSetDependencies() throws Exception {
- EventDispatcher eventDispatcher = mock(EventDispatcher.class);
- NeutronL3Adapter neutronL3Adapter = mock(NeutronL3Adapter.class);
-
- ServiceHelper.overrideGlobalInstance(EventDispatcher.class, eventDispatcher);
- ServiceHelper.overrideGlobalInstance(NeutronL3Adapter.class, neutronL3Adapter);
-
- floatingHandler.setDependencies(mock(ServiceReference.class));
-
- assertEquals("Error, did not return the correct object", eventDispatcher, floatingHandler.eventDispatcher);
- assertEquals("Error, did not return the correct object", neutronL3Adapter, getNeutronL3Adapter());
- }
-
- private NeutronL3Adapter getNeutronL3Adapter() throws Exception {
- Field field = FloatingIPHandler.class.getDeclaredField("neutronL3Adapter");
- field.setAccessible(true);
- return (NeutronL3Adapter) field.get(floatingHandler);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2016 Inocybe 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.netvirt.openstack.netvirt;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.same;
-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;
-import java.net.HttpURLConnection;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.EventDispatcher;
-import org.opendaylight.netvirt.openstack.netvirt.api.LoadBalancerConfiguration;
-import org.opendaylight.netvirt.openstack.netvirt.api.LoadBalancerProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheManager;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancer;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancerPool;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancerPoolMember;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronLoadBalancerCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronLoadBalancerPoolCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronNetworkCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronPortCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSubnet;
-import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSubnetCRUD;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology
- .Node;
-import org.osgi.framework.ServiceReference;
-
-/**
- * Unit test for {@link LBaaSHandler}
- */
-@RunWith(MockitoJUnitRunner.class)
-public class LBaaSHandlerTest {
-
- @InjectMocks private LBaaSHandler lbaasHandler;
- private LBaaSHandler lbaasHandlerSpy;
-
- @Mock private INeutronLoadBalancerCRUD neutronLBCache;
- @Mock private INeutronLoadBalancerPoolCRUD neutronLBPoolCache;
- @Mock private LoadBalancerProvider loadBalancerProvider;
- @Mock private NodeCacheManager nodeCacheManager;
- @Mock private NeutronLoadBalancer neutronLB;
- @Mock private INeutronSubnetCRUD neutronSubnetCache;
- @Mock private INeutronNetworkCRUD neutronNetworkCache;
- @Mock private INeutronPortCRUD neutronPortCache;
-
- @Before
- public void setUp(){
- NorthboundEvent ev = mock(NorthboundEvent.class);
- Map.Entry<String,String> providerInfo = mock(Entry.class);
- NeutronLoadBalancerPoolMember neutronLBPoolMember = mock(NeutronLoadBalancerPoolMember.class);
- NeutronLoadBalancerPool neutronLBPool = mock(NeutronLoadBalancerPool.class);
- List<NeutronLoadBalancerPoolMember> members = new ArrayList();
- List<NeutronLoadBalancerPool> list_neutronLBPool = new ArrayList();
- List<NeutronLoadBalancer> list_neutronLB = new ArrayList();
- List<Node> list_node = new ArrayList();
-
- lbaasHandlerSpy = Mockito.spy(lbaasHandler);
-
- neutronLB = mock(NeutronLoadBalancer.class);
- when(neutronLB.getLoadBalancerName()).thenReturn("load_balancer_name");
- when(neutronLB.getLoadBalancerVipAddress()).thenReturn("vip_address");
- when(neutronLB.getLoadBalancerVipSubnetID()).thenReturn("subnetID");
-
- when(ev.getLoadBalancer()).thenReturn(neutronLB);
-
- when(providerInfo.getKey()).thenReturn("key");
- when(providerInfo.getValue()).thenReturn("value");
-
- lbaasHandler.setDependencies(neutronPortCache);
- final NeutronPort neutronPort = new NeutronPort();
- final Neutron_IPs neutronIP1 = new Neutron_IPs();
- neutronIP1.setSubnetUUID("pool_member_subnetID");
- neutronIP1.setIpAddress("pool_member_address");
- final Neutron_IPs neutronIP2 = new Neutron_IPs();
- neutronIP2.setSubnetUUID("subnetID");
- neutronIP2.setIpAddress("vip_address");
- final Neutron_IPs neutronIP3 = new Neutron_IPs();
- neutronIP3.setSubnetUUID("subnetID");
- neutronIP3.setIpAddress("pool_member_address");
- final List<Neutron_IPs> neutronIPs = new ArrayList<>();
- neutronIPs.add(neutronIP1);
- neutronIPs.add(neutronIP2);
- neutronIPs.add(neutronIP3);
- neutronPort.setFixedIPs(neutronIPs);
- neutronPort.setMacAddress("mac_address");
- when(neutronPortCache.getAllPorts()).thenReturn(Collections.singletonList(neutronPort));
-
- lbaasHandler.setDependencies(neutronSubnetCache);
- final NeutronSubnet neutronSubnet1 = new NeutronSubnet();
- neutronSubnet1.setID("pool_member_subnetID");
- neutronSubnet1.setNetworkUUID("pool_member_networkUUID");
- final NeutronSubnet neutronSubnet2 = new NeutronSubnet();
- neutronSubnet2.setID("subnetID");
- neutronSubnet2.setNetworkUUID("pool_member_networkUUID");
- List<NeutronSubnet> neutronSubnets = new ArrayList<>();
- neutronSubnets.add(neutronSubnet1);
- neutronSubnets.add(neutronSubnet2);
- when(neutronSubnetCache.getAllSubnets()).thenReturn(neutronSubnets);
-
- lbaasHandler.setDependencies(neutronNetworkCache);
- final NeutronNetwork neutronNetwork = new NeutronNetwork();
- neutronNetwork.setNetworkUUID("pool_member_networkUUID");
- neutronNetwork.setProviderNetworkType("key");
- neutronNetwork.setProviderSegmentationID("value");
- when(neutronNetworkCache.getAllNetworks()).thenReturn(Collections.singletonList(neutronNetwork));
-
- when(neutronLBPoolMember.getPoolMemberAdminStateIsUp()).thenReturn(true);
- when(neutronLBPoolMember.getPoolMemberSubnetID()).thenReturn("subnetID");
- when(neutronLBPoolMember.getID()).thenReturn("pool_memberID");
- when(neutronLBPoolMember.getPoolMemberAddress()).thenReturn("pool_member_address");
- when(neutronLBPoolMember.getPoolMemberProtoPort()).thenReturn(1);
- members.add(neutronLBPoolMember);
-
- when(neutronLBPool.getLoadBalancerPoolMembers()).thenReturn(members);
- when(neutronLBPool.getLoadBalancerPoolProtocol()).thenReturn(LoadBalancerConfiguration.PROTOCOL_TCP);
- list_neutronLBPool.add(neutronLBPool);
- when(neutronLBPoolCache.getAllNeutronLoadBalancerPools()).thenReturn(list_neutronLBPool);
-
- list_neutronLB.add(neutronLB);
- when(neutronLBCache.getAllNeutronLoadBalancers()).thenReturn(list_neutronLB );
-
- list_node.add(mock(Node.class));
- when(nodeCacheManager.getBridgeNodes()).thenReturn(list_node);
- }
-
- @Test
- public void testCanCreateNeutronLoadBalancer(){
- assertEquals("Error, canCreateNeutronLoadBalancer() did not return the correct value ", HttpURLConnection.HTTP_OK, lbaasHandler.canCreateNeutronLoadBalancer(null));
- }
-
- @Test
- public void testCanUpdateNeutronLoadBalancer(){
- assertEquals("Error, canUpdateNeutronLoadBalancer() did not return the correct value ", HttpURLConnection.HTTP_OK, lbaasHandler.canUpdateNeutronLoadBalancer(null, null));
- }
-
- @Test
- public void testCanDeleteNeutronLoadBalancer(){
- assertEquals("Error, canDeleteNeutronLoadBalancer() did not return the correct value ", HttpURLConnection.HTTP_OK, lbaasHandler.canDeleteNeutronLoadBalancer(null));
- }
-
- /**
- * Test method {@link LBaaSHandler#processEvent(AbstractEvent)}
- */
- @Test
- public void testProcessEvent(){
- NorthboundEvent ev = mock(NorthboundEvent.class);
- when(ev.getLoadBalancer()).thenReturn(neutronLB);
-
- when(ev.getAction()).thenReturn(Action.ADD);
- lbaasHandlerSpy.processEvent(ev);
- verify(lbaasHandlerSpy, times(1)).extractLBConfiguration(any(NeutronLoadBalancer.class));
- verify(loadBalancerProvider, times(1)).programLoadBalancerRules(any(Node.class), any(LoadBalancerConfiguration.class), same(Action.ADD));
-
- when(ev.getAction()).thenReturn(Action.DELETE);
- lbaasHandlerSpy.processEvent(ev);
- verify(lbaasHandlerSpy, times(2)).extractLBConfiguration(any(NeutronLoadBalancer.class)); // 1 + 1 above
- verify(loadBalancerProvider, times(1)).programLoadBalancerRules(any(Node.class), any(LoadBalancerConfiguration.class), same(Action.DELETE));
-
- when(ev.getAction()).thenReturn(Action.UPDATE);
- lbaasHandlerSpy.processEvent(ev);
- verify(lbaasHandlerSpy, times(4)).extractLBConfiguration(any(NeutronLoadBalancer.class)); // 2 + 2 above
- verify(loadBalancerProvider, times(2)).programLoadBalancerRules(any(Node.class), any(LoadBalancerConfiguration.class), same(Action.DELETE)); // 1 + 1 above
- verify(loadBalancerProvider, times(2)).programLoadBalancerRules(any(Node.class), any(LoadBalancerConfiguration.class), same(Action.ADD)); // 1 + 1 above
- }
-
- /**
- * Test method {@link LBaaSHandler#extractLBConfiguration(NeutronLoadBalancer)}
- */
- @Test
- public void testExtractLBConfiguration(){
- LoadBalancerConfiguration lbConfig = lbaasHandler.extractLBConfiguration(neutronLB);
-
- verify(neutronLBPoolCache, times(1)).getAllNeutronLoadBalancerPools();
-
- // make sure the load balancer configuration was correctly populated
- assertEquals("Error, did not return the correct value", "key", lbConfig.getProviderNetworkType());
- assertEquals("Error, did not return the correct value", "value", lbConfig.getProviderSegmentationId());
- assertEquals("Error, did not return the correct value", "mac_address", lbConfig.getVmac());
-
- // make sure the load balancer pool member was correctly populated
- LoadBalancerConfiguration.LoadBalancerPoolMember member = lbConfig.getMembers().get("pool_memberID");
- assertEquals("Error, did not return the correct value", "pool_member_address", member.getIP());
- assertEquals("Error, did not return the correct value", "mac_address", member.getMAC());
- assertEquals("Error, did not return the correct value", LoadBalancerConfiguration.PROTOCOL_TCP, member.getProtocol());
- assertTrue("Error, did not return the correct value", 1 == member.getPort());
- }
-
- /**
- * Test method {@link LBaaSHandler#notifyNode(Node, Action)}
- */
- @Test
- public void testNotifyNode() {
- lbaasHandlerSpy.notifyNode(mock(Node.class), Action.ADD);
-
- verify(lbaasHandlerSpy, times(1)).extractLBConfiguration(any(NeutronLoadBalancer.class));
- verify(neutronLBCache, times(1)).getAllNeutronLoadBalancers();
- verify(neutronLBPoolCache, times(1)).getAllNeutronLoadBalancerPools();
- verify(loadBalancerProvider, times(1)).programLoadBalancerRules(any(Node.class), any(LoadBalancerConfiguration.class), any(Action.class));
- }
-
- @Test
- public void testSetDependencies() throws Exception {
- EventDispatcher eventDispatcher = mock(EventDispatcher.class);
- LoadBalancerProvider loadBalancerProvider = mock(LoadBalancerProvider.class);
- NodeCacheManager nodeCacheManager = mock(NodeCacheManager.class);
-
- ServiceHelper.overrideGlobalInstance(EventDispatcher.class, eventDispatcher);
- ServiceHelper.overrideGlobalInstance(LoadBalancerProvider.class, loadBalancerProvider);
- ServiceHelper.overrideGlobalInstance(NodeCacheManager.class, nodeCacheManager);
-
- lbaasHandler.setDependencies(mock(ServiceReference.class));
-
- Assert.assertEquals("Error, did not return the correct object", lbaasHandler.eventDispatcher, eventDispatcher);
- assertEquals("Error, did not return the correct object", getField("loadBalancerProvider"), loadBalancerProvider);
- assertEquals("Error, did not return the correct object", getField("nodeCacheManager"), nodeCacheManager);
- }
-
- @Test
- public void testSetDependenciesObject() throws Exception{
- INeutronNetworkCRUD iNeutronNetworkCRUD = mock(INeutronNetworkCRUD.class);
- lbaasHandler.setDependencies(iNeutronNetworkCRUD);
- assertEquals("Error, did not return the correct object", getField("neutronNetworkCache"), iNeutronNetworkCRUD);
-
- INeutronPortCRUD iNeutronPortCRUD = mock(INeutronPortCRUD.class);
- lbaasHandler.setDependencies(iNeutronPortCRUD);
- assertEquals("Error, did not return the correct object", getField("neutronPortCache"), iNeutronPortCRUD);
-
- INeutronSubnetCRUD iNeutronSubnetCRUD = mock(INeutronSubnetCRUD.class);
- lbaasHandler.setDependencies(iNeutronSubnetCRUD);
- assertEquals("Error, did not return the correct object", getField("neutronSubnetCache"), iNeutronSubnetCRUD);
-
- INeutronLoadBalancerCRUD iNeutronLoadBalancerCRUD = mock(INeutronLoadBalancerCRUD.class);
- lbaasHandler.setDependencies(iNeutronLoadBalancerCRUD);
- assertEquals("Error, did not return the correct object", getField("neutronLBCache"), iNeutronLoadBalancerCRUD);
-
- INeutronLoadBalancerPoolCRUD iNeutronLoadBalancerPoolCRUD = mock(INeutronLoadBalancerPoolCRUD.class);
- lbaasHandler.setDependencies(iNeutronLoadBalancerPoolCRUD);
- assertEquals("Error, did not return the correct object", getField("neutronLBPoolCache"), iNeutronLoadBalancerPoolCRUD);
-
- LoadBalancerProvider loadBalancerProvider = mock(LoadBalancerProvider.class);
- lbaasHandler.setDependencies(loadBalancerProvider);
- assertEquals("Error, did not return the correct object", getField("loadBalancerProvider"), loadBalancerProvider);
- }
-
- private Object getField(String fieldName) throws Exception {
- Field field = LBaaSHandler.class.getDeclaredField(fieldName);
- field.setAccessible(true);
- return field.get(lbaasHandler);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2016 Inocybe 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.netvirt.openstack.netvirt;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.any;
-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;
-import java.net.HttpURLConnection;
-import java.util.ArrayList;
-import java.util.Collections;
-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.mockito.Mockito;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheManager;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancer;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancerPoolMember;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronLoadBalancerPoolCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronNetworkCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.api.EventDispatcher;
-import org.opendaylight.netvirt.openstack.netvirt.api.LoadBalancerConfiguration;
-import org.opendaylight.netvirt.openstack.netvirt.api.LoadBalancerConfiguration.LoadBalancerPoolMember;
-import org.opendaylight.netvirt.openstack.netvirt.api.LoadBalancerProvider;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancerPool;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSubnet;
-import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronLoadBalancerCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronPortCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSubnetCRUD;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology
- .Node;
-import org.osgi.framework.ServiceReference;
-
-/**
- * Unit test for {@link LBaaSPoolMemberHandler}
- */
-@RunWith(MockitoJUnitRunner.class)
-public class LBaaSPoolHandlerTest {
-
- @InjectMocks LBaaSPoolHandler lBaaSPoolHandler;
-
- @Mock private INeutronLoadBalancerPoolCRUD neutronLBPoolCache;
- @Mock private INeutronLoadBalancerCRUD neutronLBCache;
- @Mock private LoadBalancerProvider loadBalancerProvider;
- @Mock private NodeCacheManager nodeCacheManager;
-
- @Mock private NeutronLoadBalancerPool neutronLBPool;
- @Mock private INeutronSubnetCRUD neutronSubnetCache;
- @Mock private INeutronNetworkCRUD neutronNetworkCache;
- @Mock private INeutronPortCRUD neutronPortCache;
-
- @Before
- public void setUp() {
- when(neutronLBPool.getLoadBalancerPoolProtocol()).thenReturn(LoadBalancerConfiguration.PROTOCOL_HTTP);
-
- lBaaSPoolHandler.setDependencies(neutronPortCache);
- final NeutronPort neutronPort = new NeutronPort();
- final Neutron_IPs neutronIP1 = new Neutron_IPs();
- neutronIP1.setSubnetUUID("pool_member_subnetID");
- neutronIP1.setIpAddress("pool_member_address");
- final Neutron_IPs neutronIP2 = new Neutron_IPs();
- neutronIP2.setSubnetUUID("subnetID");
- neutronIP2.setIpAddress("vip_address");
- final Neutron_IPs neutronIP3 = new Neutron_IPs();
- neutronIP3.setSubnetUUID("subnetID");
- neutronIP3.setIpAddress("pool_member_address");
- final List<Neutron_IPs> neutronIPs = new ArrayList<>();
- neutronIPs.add(neutronIP1);
- neutronIPs.add(neutronIP2);
- neutronIPs.add(neutronIP3);
- neutronPort.setFixedIPs(neutronIPs);
- neutronPort.setMacAddress("mac_address");
- when(neutronPortCache.getAllPorts()).thenReturn(Collections.singletonList(neutronPort));
-
- lBaaSPoolHandler.setDependencies(neutronSubnetCache);
- final NeutronSubnet neutronSubnet1 = new NeutronSubnet();
- neutronSubnet1.setID("pool_member_subnetID");
- neutronSubnet1.setNetworkUUID("pool_member_networkUUID");
- final NeutronSubnet neutronSubnet2 = new NeutronSubnet();
- neutronSubnet2.setID("subnetID");
- neutronSubnet2.setNetworkUUID("pool_member_networkUUID");
- List<NeutronSubnet> neutronSubnets = new ArrayList<>();
- neutronSubnets.add(neutronSubnet1);
- neutronSubnets.add(neutronSubnet2);
- when(neutronSubnetCache.getAllSubnets()).thenReturn(neutronSubnets);
-
- lBaaSPoolHandler.setDependencies(neutronNetworkCache);
- final NeutronNetwork neutronNetwork = new NeutronNetwork();
- neutronNetwork.setNetworkUUID("pool_member_networkUUID");
- neutronNetwork.setProviderNetworkType("key");
- neutronNetwork.setProviderSegmentationID("value");
- when(neutronNetworkCache.getAllNetworks()).thenReturn(Collections.singletonList(neutronNetwork));
-
- List<NeutronLoadBalancerPoolMember> members = new ArrayList<>();
- NeutronLoadBalancerPoolMember neutronLBPoolMember = mock(NeutronLoadBalancerPoolMember.class);
- when(neutronLBPoolMember.getPoolMemberAdminStateIsUp()).thenReturn(true);
- when(neutronLBPoolMember.getPoolMemberSubnetID()).thenReturn("subnetID");
- when(neutronLBPoolMember.getID()).thenReturn("pool_memberID");
- when(neutronLBPoolMember.getPoolMemberAddress()).thenReturn("pool_member_address");
- when(neutronLBPoolMember.getPoolMemberProtoPort()).thenReturn(1);
- members.add(neutronLBPoolMember);
- when(neutronLBPool.getLoadBalancerPoolMembers()).thenReturn(members);
-
- List<NeutronLoadBalancer> list_neutronLB = new ArrayList<>();
- NeutronLoadBalancer neutronLB = mock(NeutronLoadBalancer.class);
- when(neutronLB.getLoadBalancerName()).thenReturn("load_balancer_name");
- when(neutronLB.getLoadBalancerVipAddress()).thenReturn("vip_address");
- when(neutronLB.getLoadBalancerVipSubnetID()).thenReturn("subnetID");
- list_neutronLB.add(neutronLB);
- when(neutronLBCache.getAllNeutronLoadBalancers()).thenReturn(list_neutronLB);
- }
-
- /**
- * Test method {@link LBaaSPoolHandler#canCreateNeutronLoadBalancerPool(NeutronLoadBalancerPool)}
- */
- @Test
- public void testCanCreateNeutronLoadBalancerPoolMember() {
- when(neutronLBPool.getLoadBalancerPoolProtocol())
- .thenReturn(LoadBalancerConfiguration.PROTOCOL_HTTP) // to test HTTP_OK
- .thenReturn(null) // to test HTTP_BAD_REQUEST
- .thenReturn("dummy_proto"); // to test HTTP_NOT_ACCEPTABLE
-
- assertEquals("Error, canCreateNeutronLoadBalancerPool() didn't return the correct HTTP flag", HttpURLConnection.HTTP_OK, lBaaSPoolHandler.canCreateNeutronLoadBalancerPool(neutronLBPool));
- assertEquals("Error, canCreateNeutronLoadBalancerPool() didn't return the correct HTTP flag", HttpURLConnection.HTTP_BAD_REQUEST, lBaaSPoolHandler.canCreateNeutronLoadBalancerPool(neutronLBPool));
- assertEquals("Error, canCreateNeutronLoadBalancerPool() didn't return the correct HTTP flag", HttpURLConnection.HTTP_NOT_ACCEPTABLE, lBaaSPoolHandler.canCreateNeutronLoadBalancerPool(neutronLBPool));
- }
-
- /**
- * Test method {@link LBaaSPoolHandler#canUpdateNeutronLoadBalancerPool(NeutronLoadBalancerPool, NeutronLoadBalancerPool)}
- */
- public void testCanUpdateNeutronLoadBalancerPool() {
- assertEquals("Error, did not return the correct HTTP flag", HttpURLConnection.HTTP_NOT_IMPLEMENTED, lBaaSPoolHandler.canUpdateNeutronLoadBalancerPool(any(NeutronLoadBalancerPool.class), any(NeutronLoadBalancerPool.class)));
- }
-
- /**
- * Test method {@link LBaaSPoolHandler#canDeleteNeutronLoadBalancerPool(NeutronLoadBalancerPool)}
- */
- @Test
- public void testCanDeleteNeutronLoadBalancerPool() {
- when(neutronLBPool.getLoadBalancerPoolProtocol())
- .thenReturn(LoadBalancerConfiguration.PROTOCOL_HTTP) // to test HTTP_OK
- .thenReturn(null) // to test HTTP_BAD_REQUEST
- .thenReturn("dummy_proto"); // to test HTTP_NOT_ACCEPTABLE
-
- assertEquals("Error, canDeleteNeutronLoadBalancerPool() didn't return the correct HTTP flag", HttpURLConnection.HTTP_OK, lBaaSPoolHandler.canDeleteNeutronLoadBalancerPool(neutronLBPool));
- assertEquals("Error, canDeleteNeutronLoadBalancerPool() didn't return the correct HTTP flag", HttpURLConnection.HTTP_BAD_REQUEST, lBaaSPoolHandler.canDeleteNeutronLoadBalancerPool(neutronLBPool));
- assertEquals("Error, canDeleteNeutronLoadBalancerPool() didn't return the correct HTTP flag", HttpURLConnection.HTTP_NOT_ACCEPTABLE, lBaaSPoolHandler.canDeleteNeutronLoadBalancerPool(neutronLBPool));
- }
-
- /**
- * Test method {@link LBaaSPoolHandler#processEvent(AbstractEvent)}
- */
- @Test
- public void testProcessEvent() {
- LBaaSPoolHandler lbaasPoolHandlerSpy = Mockito.spy(lBaaSPoolHandler);
-
- NorthboundEvent ev = mock(NorthboundEvent.class);
- when(ev.getLoadBalancerPool()).thenReturn(neutronLBPool);
-
- List<Node> list_node = new ArrayList<>();
- list_node .add(mock(Node.class));
- when(nodeCacheManager.getBridgeNodes()).thenReturn(list_node);
-
- when(ev.getAction()).thenReturn(Action.ADD);
- lbaasPoolHandlerSpy.processEvent(ev);
- verify(lbaasPoolHandlerSpy, times(1)).extractLBConfiguration(any(NeutronLoadBalancerPool.class));
-
- when(ev.getAction()).thenReturn(Action.DELETE);
- lbaasPoolHandlerSpy.processEvent(ev);
- verify(lbaasPoolHandlerSpy, times(2)).extractLBConfiguration(any(NeutronLoadBalancerPool.class)); // 1 + 1 above
-
- when(ev.getAction()).thenReturn(Action.UPDATE);
- lbaasPoolHandlerSpy.processEvent(ev);
- verify(lbaasPoolHandlerSpy, times(2)).extractLBConfiguration(any(NeutronLoadBalancerPool.class)); // same as before as nothing as been done
- }
-
- /**
- * Test method {@link LBaaSPoolHandler#extractLBConfiguration(NeutronLoadBalancerPool)}
- */
- @Test
- public void testExtractLBConfiguration() {
- List<LoadBalancerConfiguration> list_lbConfig = lBaaSPoolHandler.extractLBConfiguration(neutronLBPool);
- assertFalse(list_lbConfig.isEmpty());
- LoadBalancerConfiguration lbConfig = list_lbConfig.get(0);
-
- verify(neutronLBCache, times(1)).getAllNeutronLoadBalancers();
-
- // make sure the load balancer configuration was correctly populated
- assertEquals("Error, did not return the correct value", "key", lbConfig.getProviderNetworkType());
- assertEquals("Error, did not return the correct value", "value", lbConfig.getProviderSegmentationId());
- assertEquals("Error, did not return the correct value", "mac_address", lbConfig.getVmac());
-
- // make sure the load balancer pool member was correctly populated
- LoadBalancerPoolMember member = lbConfig.getMembers().get("pool_memberID");
- assertEquals("Error, did not return the correct value", "pool_member_address", member.getIP());
- assertEquals("Error, did not return the correct value", "mac_address", member.getMAC());
- assertEquals("Error, did not return the correct value", LoadBalancerConfiguration.PROTOCOL_HTTP, member.getProtocol());
- assertTrue("Error, did not return the correct value", 1 == member.getPort());
- }
-
- @Test
- public void testSetDependencies() throws Exception {
- EventDispatcher eventDispatcher = mock(EventDispatcher.class);
- LoadBalancerProvider loadBalancerProvider = mock(LoadBalancerProvider.class);
- NodeCacheManager nodeCacheManager = mock(NodeCacheManager.class);
-
- ServiceHelper.overrideGlobalInstance(EventDispatcher.class, eventDispatcher);
- ServiceHelper.overrideGlobalInstance(LoadBalancerProvider.class, loadBalancerProvider);
- ServiceHelper.overrideGlobalInstance(NodeCacheManager.class, nodeCacheManager);
-
- lBaaSPoolHandler.setDependencies(mock(ServiceReference.class));
-
- assertEquals("Error, did not return the correct object", lBaaSPoolHandler.eventDispatcher, eventDispatcher);
- assertEquals("Error, did not return the correct object", getField("loadBalancerProvider"), loadBalancerProvider);
- assertEquals("Error, did not return the correct object", getField("nodeCacheManager"), nodeCacheManager);
- }
-
- @Test
- public void testSetDependenciesObject() throws Exception{
- INeutronNetworkCRUD iNeutronNetworkCRUD = mock(INeutronNetworkCRUD.class);
- lBaaSPoolHandler.setDependencies(iNeutronNetworkCRUD);
- assertEquals("Error, did not return the correct object", getField("neutronNetworkCache"), iNeutronNetworkCRUD);
-
- INeutronPortCRUD iNeutronPortCRUD = mock(INeutronPortCRUD.class);
- lBaaSPoolHandler.setDependencies(iNeutronPortCRUD);
- assertEquals("Error, did not return the correct object", getField("neutronPortCache"), iNeutronPortCRUD);
-
- INeutronSubnetCRUD iNeutronSubnetCRUD = mock(INeutronSubnetCRUD.class);
- lBaaSPoolHandler.setDependencies(iNeutronSubnetCRUD);
- assertEquals("Error, did not return the correct object", getField("neutronSubnetCache"), iNeutronSubnetCRUD);
-
- INeutronLoadBalancerCRUD iNeutronLoadBalancerCRUD = mock(INeutronLoadBalancerCRUD.class);
- lBaaSPoolHandler.setDependencies(iNeutronLoadBalancerCRUD);
- assertEquals("Error, did not return the correct object", getField("neutronLBCache"), iNeutronLoadBalancerCRUD);
-
- LoadBalancerProvider loadBalancerProvider = mock(LoadBalancerProvider.class);
- lBaaSPoolHandler.setDependencies(loadBalancerProvider);
- assertEquals("Error, did not return the correct object", getField("loadBalancerProvider"), loadBalancerProvider);
- }
-
- private Object getField(String fieldName) throws Exception {
- Field field = LBaaSPoolHandler.class.getDeclaredField(fieldName);
- field.setAccessible(true);
- return field.get(lBaaSPoolHandler);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2016 Inocybe 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.netvirt.openstack.netvirt;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyString;
-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;
-import java.net.HttpURLConnection;
-import java.util.ArrayList;
-import java.util.Collections;
-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.mockito.Mockito;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.LoadBalancerProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheManager;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancer;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancerPoolMember;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronLoadBalancerPoolCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronNetworkCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronPortCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.api.EventDispatcher;
-import org.opendaylight.netvirt.openstack.netvirt.api.LoadBalancerConfiguration;
-import org.opendaylight.netvirt.openstack.netvirt.api.LoadBalancerConfiguration.LoadBalancerPoolMember;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronLoadBalancerPool;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSubnet;
-import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronLoadBalancerCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSubnetCRUD;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-
-import org.osgi.framework.ServiceReference;
-
-/**
- * Unit test for {@link LBaaSPoolMemberHandler}
- */
-@RunWith(MockitoJUnitRunner.class)
-public class LBaaSPoolMemberHandlerTest {
-
- @InjectMocks LBaaSPoolMemberHandler lBaaSPoolMemberHandler;
-
- @Mock private INeutronLoadBalancerPoolCRUD neutronLBPoolCache;
- @Mock private INeutronLoadBalancerCRUD neutronLBCache;
- @Mock private LoadBalancerProvider loadBalancerProvider;
- @Mock private NodeCacheManager nodeCacheManager;
- @Mock private INeutronPortCRUD neutronPortCache;
- @Mock private INeutronNetworkCRUD neutronNetworkCache;
- @Mock private INeutronSubnetCRUD neutronSubnetCache;
-
- private NeutronLoadBalancerPoolMember neutronLBMember;
-
- @Before
- public void setUp() {
- neutronLBMember = new NeutronLoadBalancerPoolMember();
- neutronLBMember.setID("pool_memberID");
- neutronLBMember.setPoolMemberAddress("pool_member_address");
- neutronLBMember.setPoolMemberSubnetID("pool_member_subnetID");
- neutronLBMember.setPoolMemberProtoPort(1);
- neutronLBMember.setPoolID("poolID");
-
- lBaaSPoolMemberHandler.setDependencies(neutronPortCache);
- final NeutronPort neutronPort = new NeutronPort();
- final Neutron_IPs neutronIP1 = new Neutron_IPs();
- neutronIP1.setSubnetUUID("pool_member_subnetID");
- neutronIP1.setIpAddress("pool_member_address");
- final Neutron_IPs neutronIP2 = new Neutron_IPs();
- neutronIP2.setSubnetUUID("pool_member_subnetID");
- neutronIP2.setIpAddress("vip_address");
- final List<Neutron_IPs> neutronIPs = new ArrayList<>();
- neutronIPs.add(neutronIP1);
- neutronIPs.add(neutronIP2);
- neutronPort.setFixedIPs(neutronIPs);
- neutronPort.setMacAddress("mac_address");
- when(neutronPortCache.getAllPorts()).thenReturn(Collections.singletonList(neutronPort));
-
- lBaaSPoolMemberHandler.setDependencies(neutronSubnetCache);
- final NeutronSubnet neutronSubnet = new NeutronSubnet();
- neutronSubnet.setID("pool_member_subnetID");
- neutronSubnet.setNetworkUUID("pool_member_networkUUID");
- when(neutronSubnetCache.getAllSubnets()).thenReturn(Collections.singletonList(neutronSubnet));
-
- lBaaSPoolMemberHandler.setDependencies(neutronNetworkCache);
- final NeutronNetwork neutronNetwork = new NeutronNetwork();
- neutronNetwork.setNetworkUUID("pool_member_networkUUID");
- neutronNetwork.setProviderNetworkType("key");
- neutronNetwork.setProviderSegmentationID("value");
- when(neutronNetworkCache.getAllNetworks()).thenReturn(Collections.singletonList(neutronNetwork));
-
- List<NeutronLoadBalancerPoolMember> members = new ArrayList<>();
- NeutronLoadBalancerPoolMember neutronLBPoolMember = new NeutronLoadBalancerPoolMember();
- neutronLBPoolMember.setPoolMemberAdminStateIsUp(true);
- neutronLBPoolMember.setPoolMemberSubnetID("pool_member_subnetID");
- neutronLBPoolMember.setID("pool_memberID1");
- neutronLBPoolMember.setPoolMemberProtoPort(1);
- members.add(neutronLBPoolMember);
-
- NeutronLoadBalancerPool neutronLBPool = new NeutronLoadBalancerPool();
- neutronLBPool.setLoadBalancerPoolProtocol(LoadBalancerConfiguration.PROTOCOL_TCP);
- neutronLBPool.setLoadBalancerPoolMembers(members);
- when(neutronLBPoolCache.getNeutronLoadBalancerPool(anyString())).thenReturn(neutronLBPool);
-
- NeutronLoadBalancer neutronLB = new NeutronLoadBalancer();
- neutronLB.setLoadBalancerName("load_balancer_name");
- neutronLB.setLoadBalancerVipAddress("vip_address");
- neutronLB.setLoadBalancerVipSubnetID("pool_member_subnetID");
- when(neutronLBCache.getAllNeutronLoadBalancers()).thenReturn(Collections.singletonList(neutronLB));
- }
-
- /**
- * Test method {@link LBaaSPoolMemberHandler#canCreateNeutronLoadBalancerPoolMember(NeutronLoadBalancerPoolMember)}
- */
- @Test
- public void testCanCreateNeutronLoadBalancerPoolMember() {
- // HTTP_BAD_REQUEST
- neutronLBMember.setPoolID(null);
- assertEquals("Error, canCreateNeutronLoadBalancerPoolMember() didn't return the correct HTTP flag", HttpURLConnection.HTTP_BAD_REQUEST, lBaaSPoolMemberHandler.canCreateNeutronLoadBalancerPoolMember(neutronLBMember));
-
- // HTTP_OK
- neutronLBMember.setPoolID("poolID");
- assertEquals("Error, canCreateNeutronLoadBalancerPoolMember() didn't return the correct HTTP flag", HttpURLConnection.HTTP_OK, lBaaSPoolMemberHandler.canCreateNeutronLoadBalancerPoolMember(neutronLBMember));
-
- // HTTP_NOT_ACCEPTABLE
- when(neutronNetworkCache.getAllNetworks()).thenReturn(Collections.emptyList());
- assertEquals("Error, canCreateNeutronLoadBalancerPoolMember() didn't return the correct HTTP flag", HttpURLConnection.HTTP_NOT_ACCEPTABLE, lBaaSPoolMemberHandler.canCreateNeutronLoadBalancerPoolMember(neutronLBMember));
- }
-
- /**
- * Test method {@link LBaaSPoolMemberHandler#canUpdateNeutronLoadBalancerPoolMember(NeutronLoadBalancerPoolMember, NeutronLoadBalancerPoolMember)}
- */
- @Test
- public void testCanUpdateNeutronLoadBalancerPoolMember() {
- assertEquals("Error, did not return the correct HTTP flag", HttpURLConnection.HTTP_NOT_IMPLEMENTED, lBaaSPoolMemberHandler.canUpdateNeutronLoadBalancerPoolMember(null, null));
- }
-
- /**
- * Test method {@link LBaaSPoolMemberHandler#canDeleteNeutronLoadBalancerPoolMember(NeutronLoadBalancerPoolMember)}
- */
- @Test
- public void testCanDeleteNeutronLoadBalancerPoolMember() {
- // HTTP_BAD_REQUEST
- neutronLBMember.setPoolID(null);
- assertEquals("Error, canDeleteNeutronLoadBalancerPoolMember() didn't return the correct HTTP flag", HttpURLConnection.HTTP_BAD_REQUEST, lBaaSPoolMemberHandler.canDeleteNeutronLoadBalancerPoolMember(neutronLBMember));
-
- // HTTP_OK
- neutronLBMember.setPoolID("poolID");
- assertEquals("Error, canDeleteNeutronLoadBalancerPoolMember() didn't return the correct HTTP flag", HttpURLConnection.HTTP_OK, lBaaSPoolMemberHandler.canDeleteNeutronLoadBalancerPoolMember(neutronLBMember));
-
- // HTTP_NOT_ACCEPTABLE
- when(neutronNetworkCache.getAllNetworks()).thenReturn(Collections.emptyList());
- assertEquals("Error, canDeleteNeutronLoadBalancerPoolMember() didn't return the correct HTTP flag", HttpURLConnection.HTTP_NOT_ACCEPTABLE, lBaaSPoolMemberHandler.canDeleteNeutronLoadBalancerPoolMember(neutronLBMember));
- }
-
- /**
- * Test method {@link LBaaSPoolMemberHandler#processEvent(AbstractEvent)}
- */
- @Test
- public void testProcessEvent(){
- LBaaSPoolMemberHandler lbaasPoolMemberHandlerSpy = Mockito.spy(lBaaSPoolMemberHandler);
-
- NorthboundEvent ev = mock(NorthboundEvent.class);
- when(ev.getLoadBalancerPoolMember()).thenReturn(neutronLBMember);
-
- List<Node> list_node = new ArrayList<>();
- list_node .add(mock(Node.class));
- when(nodeCacheManager.getBridgeNodes()).thenReturn(list_node);
-
- when(ev.getAction()).thenReturn(Action.ADD);
- lbaasPoolMemberHandlerSpy.processEvent(ev);
- verify(lbaasPoolMemberHandlerSpy, times(1)).extractLBConfiguration(any(NeutronLoadBalancerPoolMember.class));
-
- when(ev.getAction()).thenReturn(Action.DELETE);
- lbaasPoolMemberHandlerSpy.processEvent(ev);
- verify(lbaasPoolMemberHandlerSpy, times(2)).extractLBConfiguration(any(NeutronLoadBalancerPoolMember.class)); // 1 + 1 above
-
- when(ev.getAction()).thenReturn(Action.UPDATE);
- lbaasPoolMemberHandlerSpy.processEvent(ev);
- verify(lbaasPoolMemberHandlerSpy, times(2)).extractLBConfiguration(any(NeutronLoadBalancerPoolMember.class)); // same as before as nothing as been done
- }
-
- /**
- * Test method {@link LBaaSPoolMemberHandler#extractLBConfiguration(NeutronLoadBalancerPoolMember)}
- */
- @Test
- public void testExtractLBConfiguration() {
- LoadBalancerConfiguration lbConfig = lBaaSPoolMemberHandler.extractLBConfiguration(neutronLBMember);
-
- // make sure the load balancer configuration was correctly populated
- assertEquals("Error, did not return the correct value", "key", lbConfig.getProviderNetworkType());
- assertEquals("Error, did not return the correct value", "value", lbConfig.getProviderSegmentationId());
- assertEquals("Error, did not return the correct value", "mac_address", lbConfig.getVmac());
-
- // make sure the load balancer pool member was correctly populated
- LoadBalancerPoolMember member = lbConfig.getMembers().get("pool_memberID");
- assertEquals("Error, did not return the correct value", "pool_member_address", member.getIP());
- assertEquals("Error, did not return the correct value", "mac_address", member.getMAC());
- assertEquals("Error, did not return the correct value", LoadBalancerConfiguration.PROTOCOL_TCP, member.getProtocol());
- assertTrue("Error, did not return the correct value", 1 == member.getPort());
- }
-
- @Test
- public void testSetDependencies() throws Exception {
- EventDispatcher eventDispatcher = mock(EventDispatcher.class);
- LoadBalancerProvider loadBalancerProvider = mock(LoadBalancerProvider.class);
- NodeCacheManager nodeCacheManager = mock(NodeCacheManager.class);
-
- ServiceHelper.overrideGlobalInstance(EventDispatcher.class, eventDispatcher);
- ServiceHelper.overrideGlobalInstance(LoadBalancerProvider.class, loadBalancerProvider);
- ServiceHelper.overrideGlobalInstance(NodeCacheManager.class, nodeCacheManager);
-
- lBaaSPoolMemberHandler.setDependencies(mock(ServiceReference.class));
-
- assertEquals("Error, did not return the correct object", lBaaSPoolMemberHandler.eventDispatcher, eventDispatcher);
- assertEquals("Error, did not return the correct object", getField("loadBalancerProvider"), loadBalancerProvider);
- assertEquals("Error, did not return the correct object", getField("nodeCacheManager"), nodeCacheManager);
- }
-
- @Test
- public void testSetDependenciesObject() throws Exception{
- INeutronNetworkCRUD iNeutronNetworkCRUD = mock(INeutronNetworkCRUD.class);
- lBaaSPoolMemberHandler.setDependencies(iNeutronNetworkCRUD);
- assertEquals("Error, did not return the correct object", getField("neutronNetworkCache"), iNeutronNetworkCRUD);
-
- INeutronPortCRUD iNeutronPortCRUD = mock(INeutronPortCRUD.class);
- lBaaSPoolMemberHandler.setDependencies(iNeutronPortCRUD);
- assertEquals("Error, did not return the correct object", getField("neutronPortCache"), iNeutronPortCRUD);
-
- INeutronSubnetCRUD iNeutronSubnetCRUD = mock(INeutronSubnetCRUD.class);
- lBaaSPoolMemberHandler.setDependencies(iNeutronSubnetCRUD);
- assertEquals("Error, did not return the correct object", getField("neutronSubnetCache"), iNeutronSubnetCRUD);
-
- INeutronLoadBalancerCRUD iNeutronLoadBalancerCRUD = mock(INeutronLoadBalancerCRUD.class);
- lBaaSPoolMemberHandler.setDependencies(iNeutronLoadBalancerCRUD);
- assertEquals("Error, did not return the correct object", getField("neutronLBCache"), iNeutronLoadBalancerCRUD);
-
- INeutronLoadBalancerPoolCRUD iNeutronLoadBalancerPoolCRUD = mock(INeutronLoadBalancerPoolCRUD.class);
- lBaaSPoolMemberHandler.setDependencies(iNeutronLoadBalancerPoolCRUD);
- assertEquals("Error, did not return the correct object", getField("neutronLBPoolCache"), iNeutronLoadBalancerPoolCRUD);
-
- LoadBalancerProvider loadBalancerProvider = mock(LoadBalancerProvider.class);
- lBaaSPoolMemberHandler.setDependencies(loadBalancerProvider);
- assertEquals("Error, did not return the correct object", getField("loadBalancerProvider"), loadBalancerProvider);
- }
-
- private Object getField(String fieldName) throws Exception {
- Field field = LBaaSPoolMemberHandler.class.getDeclaredField(fieldName);
- field.setAccessible(true);
- return field.get(lBaaSPoolMemberHandler);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2016 Inocybe 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.netvirt.openstack.netvirt;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Matchers.same;
-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;
-import java.net.HttpURLConnection;
-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.mockito.Mockito;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.TenantNetworkManager;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronNetworkCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.BridgeConfigurationManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.EventDispatcher;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.openstack.netvirt.impl.NeutronL3Adapter;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.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.osgi.framework.ServiceReference;
-
-/**
- * Unit test for {@link NetworkHandler}
- */
-@RunWith(MockitoJUnitRunner.class)
-public class NetworkHandlerTest {
-
- @InjectMocks private NetworkHandler networkHandler;
-
- @Mock private NeutronNetwork sharedNeutronNetwork;
- @Mock private NeutronNetwork nonSharedNeutronNetwork;
-
- @Mock private NeutronL3Adapter neutronL3Adapter;
- @Mock private TenantNetworkManager tenantNetworkManager;
- @Mock private INeutronNetworkCRUD neutronNetworkCache;
- @Mock private BridgeConfigurationManager bridgeConfigurationManager;
- @Mock private NodeCacheManager nodeCacheManager;
- @Mock private Southbound southbound;
-
- @Before
- public void setup() {
- when(sharedNeutronNetwork.isShared()).thenReturn(true);
- when(nonSharedNeutronNetwork.isShared()).thenReturn(false);
- }
-
- /**
- * Test method {@link NetworkHandler#canCreateNetwork(NeutronNetwork)}
- */
- @Test
- public void testCanCreateNetwork() {
- assertEquals("Error, did not return the correct HTTP flag", HttpURLConnection.HTTP_OK, networkHandler.canCreateNetwork(sharedNeutronNetwork));
- assertEquals("Error, did not return the correct HTTP flag", HttpURLConnection.HTTP_OK, networkHandler.canCreateNetwork(nonSharedNeutronNetwork));
- }
-
- /**
- * Test method {@link NetworkHandler#canUpdateNetwork(NeutronNetwork, NeutronNetwork)}
- */
- @Test
- public void testCanUpdateNetwork() {
- assertEquals("Error, did not return the correct HTTP flag", HttpURLConnection.HTTP_OK, networkHandler.canUpdateNetwork(sharedNeutronNetwork, sharedNeutronNetwork));
- assertEquals("Error, did not return the correct HTTP flag", HttpURLConnection.HTTP_OK, networkHandler.canUpdateNetwork(nonSharedNeutronNetwork, nonSharedNeutronNetwork));
- }
-
- /**
- * Test method {@link NetworkHandler#canDeleteNetwork(NeutronNetwork)}
- */
- @Test
- public void testCanDeleteNetwork() {
- assertEquals("Error, did not return the correct HTTP flag", HttpURLConnection.HTTP_OK, networkHandler.canDeleteNetwork(nonSharedNeutronNetwork));
- }
-
- /**
- * Test method {@link NetworkHandler#processEvent(AbstractEvent)}
- */
- @Test
- public void testProcessEvent() {
- NetworkHandler networkHandlerSpy = Mockito.spy(networkHandler);
-
- NorthboundEvent ev = mock(NorthboundEvent.class);
- when(ev.getNeutronNetwork()).thenReturn(nonSharedNeutronNetwork);
-
- when(ev.getAction()).thenReturn(Action.ADD);
- networkHandlerSpy.processEvent(ev);
- verify(neutronL3Adapter, times(1)).handleNeutronNetworkEvent(any(NeutronNetwork.class), same(Action.ADD));
-
- when(ev.getAction()).thenReturn(Action.UPDATE);
- networkHandlerSpy.processEvent(ev);
- verify(neutronL3Adapter, times(1)).handleNeutronNetworkEvent(any(NeutronNetwork.class), same(Action.UPDATE));
-
- String portName = "portName";
-
- List<NeutronNetwork> networks = new ArrayList<>();
- when(neutronNetworkCache.getAllNetworks()).thenReturn(networks);
-
- List<Node> nodes = new ArrayList<>();
- nodes.add(mock(Node.class));
- when(nodeCacheManager.getNodes()).thenReturn(nodes);
-
- List<String> phyIfName = new ArrayList<>();
- phyIfName.add(portName);
- when(bridgeConfigurationManager.getAllPhysicalInterfaceNames(any(Node.class))).thenReturn(phyIfName );
-
- List<OvsdbTerminationPointAugmentation> ports = new ArrayList<>();
- OvsdbTerminationPointAugmentation port = mock(OvsdbTerminationPointAugmentation.class);
- when(port.getName()).thenReturn(portName);
- ports.add(port);
- when(southbound.getTerminationPointsOfBridge(any(Node.class))).thenReturn(ports);
-
- when(ev.getAction()).thenReturn(Action.DELETE);
- when(southbound.isTunnel(any(OvsdbTerminationPointAugmentation.class))).thenReturn(true);
- networkHandlerSpy.processEvent(ev); // test delete with southbound.isTunnel(true)
- when(southbound.isTunnel(any(OvsdbTerminationPointAugmentation.class))).thenReturn(false);
- networkHandlerSpy.processEvent(ev); // test delete with southbound.isTunnel(false)
- // the functions are called once per call to processEvent()
- verify(neutronL3Adapter, times(2)).handleNeutronNetworkEvent(any(NeutronNetwork.class), same(Action.DELETE));
- verify(tenantNetworkManager, times(2)).networkDeleted(anyString());
- // depending on the southbound.isTunnel()
- verify(southbound, times(2)).deleteTerminationPoint(any(Node.class), anyString());
- }
-
- @Test
- public void testSetDependencies() throws Exception {
- TenantNetworkManager tenantNetworkManager = mock(TenantNetworkManager.class);
- BridgeConfigurationManager bridgeConfigurationManager = mock(BridgeConfigurationManager.class);
- NodeCacheManager nodeCacheManager = mock(NodeCacheManager.class);
- NeutronL3Adapter neutronL3Adapter = mock(NeutronL3Adapter.class);
- Southbound southbound = mock(Southbound.class);
- EventDispatcher eventDispatcher = mock(EventDispatcher.class);
-
-
- ServiceHelper.overrideGlobalInstance(TenantNetworkManager.class, tenantNetworkManager);
- ServiceHelper.overrideGlobalInstance(BridgeConfigurationManager.class, bridgeConfigurationManager);
- ServiceHelper.overrideGlobalInstance(NodeCacheManager.class, nodeCacheManager);
- ServiceHelper.overrideGlobalInstance(NeutronL3Adapter.class, neutronL3Adapter);
- ServiceHelper.overrideGlobalInstance(Southbound.class, southbound);
- ServiceHelper.overrideGlobalInstance(EventDispatcher.class, eventDispatcher);
-
- networkHandler.setDependencies(mock(ServiceReference.class));
-
- assertEquals("Error, did not return the correct object", getField("tenantNetworkManager"), tenantNetworkManager);
- assertEquals("Error, did not return the correct object", getField("bridgeConfigurationManager"), bridgeConfigurationManager);
- assertEquals("Error, did not return the correct object", getField("nodeCacheManager"), nodeCacheManager);
- assertEquals("Error, did not return the correct object", getField("neutronL3Adapter"), neutronL3Adapter);
- assertEquals("Error, did not return the correct object", getField("southbound"), southbound);
- assertEquals("Error, did not return the correct object", networkHandler.eventDispatcher, eventDispatcher);
- }
-
- @Test
- public void testSetDependenciesObject() throws Exception{
- INeutronNetworkCRUD iNeutronNetworkCRUD = mock(INeutronNetworkCRUD.class);
- networkHandler.setDependencies(iNeutronNetworkCRUD);
- assertEquals("Error, did not return the correct object", getField("neutronNetworkCache"), iNeutronNetworkCRUD);
-}
-
- private Object getField(String fieldName) throws Exception {
- Field field = NetworkHandler.class.getDeclaredField(fieldName);
- field.setAccessible(true);
- return field.get(networkHandler);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2016 Inocybe 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.netvirt.openstack.netvirt;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-import java.util.AbstractMap;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-import org.junit.Test;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronNetworkCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSubnet;
-import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronPortCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSubnetCRUD;
-
-/**
- * Unit test for {@link NeutronCacheUtils}
- */
-public class NeutronCacheUtilsTest {
-
- /**
- * Test method {@link NeutronCacheUtils#getMacAddress(INeutronPortCRUD, String, String)}
- */
- @Test
- public void testGetMacAddress(){
- INeutronPortCRUD neutronPortsCache = mock(INeutronPortCRUD.class);
- NeutronPort port = mock(NeutronPort.class);
- Neutron_IPs ip = mock(Neutron_IPs.class);
- when(ip.getIpAddress()).thenReturn("ip_address");
- when(ip.getSubnetUUID()).thenReturn("subnetUUID");
- List<Neutron_IPs> list_fixedIP = new ArrayList<>();
- list_fixedIP.add(ip);
- when(port.getFixedIPs()).thenReturn(list_fixedIP);
- when(port.getMacAddress()).thenReturn("mac_address");
- List<NeutronPort> list_port = new ArrayList<>();
- list_port.add(port);
-
- when(neutronPortsCache.getAllPorts()).thenReturn(list_port);
-
- assertEquals("Error, getMacAddress() did not return the correct value", "mac_address", NeutronCacheUtils.getMacAddress(neutronPortsCache, "subnetUUID", "ip_address"));
- }
-
- /**
- * Test method {@link NeutronCacheUtils#getProviderInformation(INeutronNetworkCRUD, INeutronSubnetCRUD, String)}
- */
- @Test
- public void testGetProviderInformation() {
- INeutronSubnetCRUD neutronSubnetCache = mock(INeutronSubnetCRUD.class);
- NeutronSubnet subnet = mock(NeutronSubnet.class);
- when(subnet.getID()).thenReturn("subnetUUID");
- when(subnet.getNetworkUUID()).thenReturn("networkUUID");
- List<NeutronSubnet> list_subnet = new ArrayList<>();
- list_subnet.add(subnet);
-
- when(neutronSubnetCache.getAllSubnets()).thenReturn(list_subnet );
-
- INeutronNetworkCRUD neutronNetworkCache = mock(INeutronNetworkCRUD.class);
- NeutronNetwork network = mock(NeutronNetwork.class);
- when(network.getID()).thenReturn("networkUUID");
- when(network.getProviderNetworkType()).thenReturn("network_type_1");
- when(network.getProviderSegmentationID()).thenReturn("network_segID");
- List<NeutronNetwork> list_network = new ArrayList<>();
- list_network.add(network);
-
- when(neutronNetworkCache.getAllNetworks()).thenReturn(list_network);
-
- Map.Entry<String,String> entry = new AbstractMap.SimpleEntry<>(
- network.getProviderNetworkType(), network.getProviderSegmentationID());
-
- assertEquals("Error, getProviderInformation() did not return the correct values", entry, NeutronCacheUtils.getProviderInformation(neutronNetworkCache, neutronSubnetCache, "subnetUUID"));
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Inocybe 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.netvirt.openstack.netvirt;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.mock;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-
-/**
- * Unit test for {@link NodeCacheManagerEvent}
- */
-
-@RunWith(MockitoJUnitRunner.class)
-public class NodeCacheManagerEventTest {
-
- @InjectMocks private NodeCacheManagerEvent nodeCacheManagerEvent;
-
- @Test
- public void testToString() {
- Node node = mock(Node.class);
- nodeCacheManagerEvent = new NodeCacheManagerEvent(node, Action.ADD);
- assertEquals("Error, toString() did not return the correct string", "NodeCacheManagerEvent [action=ADD, node=" + node + "]", nodeCacheManagerEvent.toString());
- }
-
- @Test
- public void testHashCode() {
- assertNotNull("Error, hashCode shouldn't be null", nodeCacheManagerEvent.hashCode());
- }
-
- @Test
- public void testEquals() {
- assertTrue("Error, the two object should be equal", nodeCacheManagerEvent.equals(nodeCacheManagerEvent));
- assertFalse("Error, the two object should not be equal", nodeCacheManagerEvent.equals("dummy"));
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Inocybe 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.netvirt.openstack.netvirt;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import org.junit.Test;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-
-/**
- * Unit test for {@link NodeConfiguration}
- */
-public class NodeConfigurationTest {
-
- @Test
- public void testNodeConfiguration() {
- NodeConfiguration nodeConf = new NodeConfiguration();
-
- assertEquals("Error, did not populate the internal vlan queue correctly", Constants.MAX_VLAN - 1, nodeConf.getInternalVlans().size());
- assertNotNull("Error, tenant vlan map has not been initialized", nodeConf.getTenantVlanMap());
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2016 Inocybe 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.netvirt.openstack.netvirt;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyString;
-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;
-import java.net.HttpURLConnection;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.EventDispatcher;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.openstack.netvirt.impl.NeutronL3Adapter;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-import org.opendaylight.netvirt.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.osgi.framework.ServiceReference;
-
-/**
- * Unit test fort {@link PortHandler}
- */
-@RunWith(MockitoJUnitRunner.class)
-public class PortHandlerTest {
-
- @InjectMocks private PortHandler portHandler;
-
- @Mock private NeutronL3Adapter neutronL3Adapter;
- @Mock private NodeCacheManager nodeCacheManager;
- @Mock private Southbound southbound;
-
- @Test
- public void testCanCreatePort() {
- assertEquals("Error, did not return the correct HTTP flag", HttpURLConnection.HTTP_OK, portHandler.canCreatePort(mock(NeutronPort.class)));
- }
-
- @Test
- public void testCanUpdatePort() {
- assertEquals("Error, did not return the correct HTTP flag", HttpURLConnection.HTTP_OK, portHandler.canUpdatePort(mock(NeutronPort.class), mock(NeutronPort.class)));
- }
-
- @Test
- public void testCanDeletePort() {
- assertEquals("Error, did not return the correct HTTP flag", HttpURLConnection.HTTP_OK, portHandler.canDeletePort(mock(NeutronPort.class)));
- }
-
- @Test
- public void testProcessEvent() {
- PortHandler portHandlerSpy = Mockito.spy(portHandler);
-
- NeutronPort neutronPort = mock(NeutronPort.class);
- when(neutronPort.getTenantID()).thenReturn("tenantID");
- when(neutronPort.getNetworkUUID()).thenReturn("networkUUID");
- when(neutronPort.getID()).thenReturn("ID");
- when(neutronPort.getPortUUID()).thenReturn("portUUID");
-
- NorthboundEvent ev = mock(NorthboundEvent.class);
- when(ev.getPort()).thenReturn(neutronPort);
-
- when(ev.getAction()).thenReturn(Action.ADD);
- portHandlerSpy.processEvent(ev);
- verify(neutronL3Adapter, times(1)).handleNeutronPortEvent(neutronPort, Action.ADD);
-
- when(ev.getAction()).thenReturn(Action.UPDATE);
- portHandlerSpy.processEvent(ev);
- verify(neutronL3Adapter, times(1)).handleNeutronPortEvent(neutronPort, Action.UPDATE);
-
- List<Node> nodes = new ArrayList<>();
- nodes.add(mock(Node.class));
- when(nodeCacheManager.getNodes()).thenReturn(nodes);
-
- List<OvsdbTerminationPointAugmentation> ports = new ArrayList<>();
- OvsdbTerminationPointAugmentation port = mock(OvsdbTerminationPointAugmentation.class);
- ports.add(port);
- when(southbound.readTerminationPointAugmentations(any(Node.class))).thenReturn(ports);
-
- when(southbound.getInterfaceExternalIdsValue(any(OvsdbTerminationPointAugmentation.class), anyString())).thenReturn("portUUID");
-
- when(ev.getAction()).thenReturn(Action.DELETE);
- portHandlerSpy.processEvent(ev);
- verify(neutronL3Adapter, times(1)).handleNeutronPortEvent(neutronPort, Action.DELETE);
- verify(southbound, times(1)).deleteTerminationPoint(any(Node.class), anyString());
- }
-
- @Test
- public void testSetDependencies() throws Exception {
- NodeCacheManager nodeCacheManager = mock(NodeCacheManager.class);
- NeutronL3Adapter neutronL3Adapter = mock(NeutronL3Adapter.class);
- Southbound southbound = mock(Southbound.class);
- EventDispatcher eventDispatcher = mock(EventDispatcher.class);
-
- ServiceHelper.overrideGlobalInstance(NodeCacheManager.class, nodeCacheManager);
- ServiceHelper.overrideGlobalInstance(NeutronL3Adapter.class, neutronL3Adapter);
- ServiceHelper.overrideGlobalInstance(Southbound.class, southbound);
- ServiceHelper.overrideGlobalInstance(EventDispatcher.class, eventDispatcher);
-
- portHandler.setDependencies(mock(ServiceReference.class));
-
- assertEquals("Error, did not return the correct object", getField("nodeCacheManager"), nodeCacheManager);
- assertEquals("Error, did not return the correct object", getField("neutronL3Adapter"), neutronL3Adapter);
- assertEquals("Error, did not return the correct object", getField("southbound"), southbound);
- assertEquals("Error, did not return the correct object", portHandler.eventDispatcher, eventDispatcher);
- }
-
- private Object getField(String fieldName) throws Exception {
- Field field = PortHandler.class.getDeclaredField(fieldName);
- field.setAccessible(true);
- return field.get(portHandler);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2016 Inocybe 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.netvirt.openstack.netvirt;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-
-import java.lang.reflect.Field;
-import java.net.HttpURLConnection;
-
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.netvirt.openstack.netvirt.api.EventDispatcher;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityGroup;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityRule;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.osgi.framework.ServiceReference;
-
-/**
- * Unit test {@link PortSecurityHandler}
- */
-@RunWith(MockitoJUnitRunner.class)
-public class PortSecurityHandlerTest {
-
- @InjectMocks private PortSecurityHandler portSecurityHandler;
- private PortSecurityHandler posrtSecurityHandlerSpy;
- @Mock
- EventDispatcher eventDispatcher;
-
- @Before
- public void setUp() {
- posrtSecurityHandlerSpy = Mockito.spy(portSecurityHandler);
- }
-
- @Test
- public void testCanCreateNeutronSecurityGroup() {
- assertEquals("Error, did not return the correct HTTP flag", HttpURLConnection.HTTP_CREATED, portSecurityHandler.canCreateNeutronSecurityGroup(mock(NeutronSecurityGroup.class)));
-
- posrtSecurityHandlerSpy.neutronSecurityGroupCreated(any(NeutronSecurityGroup.class));
- verify(posrtSecurityHandlerSpy, times(1)).canCreateNeutronSecurityGroup(any(NeutronSecurityGroup.class));
- }
-
- @Test
- public void testCanUpdateNeutronSecurityGroup() {
- assertEquals("Error, did not return the correct HTTP flag", HttpURLConnection.HTTP_OK, portSecurityHandler.canUpdateNeutronSecurityGroup(mock(NeutronSecurityGroup.class), mock(NeutronSecurityGroup.class)));
- }
-
- @Test
- public void testCanDeleteNeutronSecurityGroup() {
- assertEquals("Error, did not return the correct HTTP flag", HttpURLConnection.HTTP_OK, portSecurityHandler.canDeleteNeutronSecurityGroup(mock(NeutronSecurityGroup.class)));
-
- posrtSecurityHandlerSpy.neutronSecurityGroupDeleted(any(NeutronSecurityGroup.class));
- verify(posrtSecurityHandlerSpy, times(1)).canDeleteNeutronSecurityGroup(any(NeutronSecurityGroup.class));
- }
-
- @Test
- public void testCanCreateNeutronSecurityRule() {
- assertEquals("Error, did not return the correct HTTP flag", HttpURLConnection.HTTP_CREATED, portSecurityHandler.canCreateNeutronSecurityRule(mock(NeutronSecurityRule.class)));
-
- posrtSecurityHandlerSpy.neutronSecurityRuleCreated(any(NeutronSecurityRule.class));
- verify(posrtSecurityHandlerSpy, times(1)).enqueueEvent(any(AbstractEvent.class));
- }
-
- @Test
- public void testCanUpdateNeutronSecurityRule() {
- assertEquals("Error, did not return the correct HTTP flag", HttpURLConnection.HTTP_OK, portSecurityHandler.canUpdateNeutronSecurityRule(mock(NeutronSecurityRule.class), mock(NeutronSecurityRule.class)));
- }
-
- @Test
- public void testCanDeleteNeutronSecurityRule() {
- assertEquals("Error, did not return the correct HTTP flag", HttpURLConnection.HTTP_OK, portSecurityHandler.canDeleteNeutronSecurityRule(mock(NeutronSecurityRule.class)));
-
- posrtSecurityHandlerSpy.neutronSecurityRuleDeleted(any(NeutronSecurityRule.class));
- verify(posrtSecurityHandlerSpy, times(1)).enqueueEvent(any(AbstractEvent.class));
- }
-
- @Test
- public void testProcessEvent() {
- // TODO see PortSecurityHandler#processEvent()
- }
-
- @Test
- public void testSetDependencies() throws Exception {
- EventDispatcher eventDispatcher = mock(EventDispatcher.class);
-
- ServiceHelper.overrideGlobalInstance(EventDispatcher.class, eventDispatcher);
-
- portSecurityHandler.setDependencies(mock(ServiceReference.class));
-
- Assert.assertEquals("Error, did not return the correct object", portSecurityHandler.eventDispatcher, eventDispatcher);
- }
-
-
- private Object getField(String fieldName) throws Exception {
- Field field = PortSecurityHandler.class.getDeclaredField(fieldName);
- field.setAccessible(true);
- return field.get(portSecurityHandler);
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2016 Inocybe 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.netvirt.openstack.netvirt;
-
-import static org.junit.Assert.assertEquals;
-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;
-import java.net.HttpURLConnection;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.EventDispatcher;
-import org.opendaylight.netvirt.openstack.netvirt.impl.NeutronL3Adapter;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronRouter;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronRouter_Interface;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.osgi.framework.ServiceReference;
-
-/**
- * Unit test fort {@link RouterHandler}
- */
-@RunWith(MockitoJUnitRunner.class)
-public class RouterHandlerTest {
-
- @InjectMocks RouterHandler routerHandler;
-
- @Mock NeutronL3Adapter neutronL3Adapter;
-
- @Test
- public void testCanCreateRouter() {
- assertEquals("Error, canCreateRouter() did not return the correct HTTP flag", HttpURLConnection.HTTP_OK, routerHandler.canCreateRouter(mock(NeutronRouter.class)));
- }
-
- @Test
- public void testCanUpdateRouter() {
- assertEquals("Error, canUpdateRouter() did not return the correct HTTP flag", HttpURLConnection.HTTP_OK, routerHandler.canUpdateRouter(mock(NeutronRouter.class), mock(NeutronRouter.class)));
- }
-
- @Test
- public void testCanDeleteRouter() {
- assertEquals("Error, canDeleteRouter() did not return the correct HTTP flag", HttpURLConnection.HTTP_OK, routerHandler.canDeleteRouter(mock(NeutronRouter.class)));
- }
-
- @Test
- public void testCanAttachAndDettachInterface() {
- NeutronRouter router = mock(NeutronRouter.class);
- when(router.getName()).thenReturn("router_name");
-
- NeutronRouter_Interface routerInterface = mock(NeutronRouter_Interface.class);
- when(routerInterface.getPortUUID()).thenReturn("portUUID");
- when(routerInterface.getSubnetUUID()).thenReturn("subnetUUID");
-
- assertEquals("Error, canAttachInterface() did not return the correct HTTP flag", HttpURLConnection.HTTP_OK, routerHandler.canAttachInterface(router, routerInterface));
- assertEquals("Error, canDetachInterface() did not return the correct HTTP flag", HttpURLConnection.HTTP_OK, routerHandler.canDetachInterface(router, routerInterface));
- }
-
- @Test
- public void testProcessEvent() {
- NorthboundEvent ev = mock(NorthboundEvent.class);
-
- when(ev.getAction()).thenReturn(Action.UPDATE);
- when(ev.getRouter()).thenReturn(mock(NeutronRouter.class));
- when(ev.getRouterInterface())
- .thenReturn(null)
- .thenReturn(mock(NeutronRouter_Interface.class));
-
- routerHandler.processEvent(ev);
- verify(neutronL3Adapter, times(1)).handleNeutronRouterEvent(ev.getRouter(), Action.UPDATE);
- routerHandler.processEvent(ev);
- verify(neutronL3Adapter, times(1)).handleNeutronRouterInterfaceEvent(ev.getRouter(), ev.getRouterInterface(), Action.UPDATE);
- }
-
- @Test
- public void testSetDependencies() throws Exception {
- NeutronL3Adapter neutronL3Adapter = mock(NeutronL3Adapter.class);
- EventDispatcher eventDispatcher = mock(EventDispatcher.class);
-
- ServiceHelper.overrideGlobalInstance(NeutronL3Adapter.class, neutronL3Adapter);
- ServiceHelper.overrideGlobalInstance(EventDispatcher.class, eventDispatcher);
-
- routerHandler.setDependencies(mock(ServiceReference.class));
-
- assertEquals("Error, did not return the correct object", getField("neutronL3Adapter"), neutronL3Adapter);
- assertEquals("Error, did not return the correct object", routerHandler.eventDispatcher, eventDispatcher);
- }
-
- private Object getField(String fieldName) throws Exception {
- Field field = RouterHandler.class.getDeclaredField(fieldName);
- field.setAccessible(true);
- return field.get(routerHandler);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2016 Inocybe 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.netvirt.openstack.netvirt;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.any;
-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;
-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.mockito.Mockito;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.BridgeConfigurationManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.ConfigurationService;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-import org.opendaylight.netvirt.openstack.netvirt.api.NetworkingProviderManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.OvsdbInventoryListener;
-import org.opendaylight.netvirt.openstack.netvirt.api.TenantNetworkManager;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-import org.opendaylight.netvirt.openstack.netvirt.api.EventDispatcher;
-import org.opendaylight.netvirt.openstack.netvirt.api.NetworkingProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.OvsdbInventoryService;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.openstack.netvirt.impl.DistributedArpService;
-import org.opendaylight.netvirt.openstack.netvirt.impl.NeutronL3Adapter;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeName;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation;
-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.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPoint;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.osgi.framework.ServiceReference;
-
-/**
- * Unit test fort {@link SouthboundHandler}
- */
-@RunWith(MockitoJUnitRunner.class)
-public class SouthboundHandlerTest {
-
- @InjectMocks private SouthboundHandler southboundHandler;
- private SouthboundHandler southboundHandlerSpy;
-
- @Mock private ConfigurationService configurationService;
- @Mock private BridgeConfigurationManager bridgeConfigurationManager;
- @Mock private TenantNetworkManager tenantNetworkManager;
- @Mock private NetworkingProviderManager networkingProviderManager;
- @Mock private DistributedArpService distributedArpService;
- @Mock private NeutronL3Adapter neutronL3Adapter;
- @Mock private NodeCacheManager nodeCacheManager;
- @Mock private OvsdbInventoryService ovsdbInventoryService;
- @Mock private Southbound southbound;
-
- @Before
- public void setUp() {
- southboundHandler.eventDispatcher = mock(EventDispatcher.class);
- southboundHandlerSpy = Mockito.spy(southboundHandler);
- }
-
- @Test
- public void testTriggerUpdates() {
- Node node = mock(Node.class);
- when(node.getAugmentation(OvsdbNodeAugmentation.class)).thenReturn(mock(OvsdbNodeAugmentation.class));
-
- List<Node> nodes = new ArrayList<>();
- nodes.add(mock(Node.class));
- when(southbound.readOvsdbTopologyNodes()).thenReturn(nodes);
-
- southboundHandlerSpy.triggerUpdates();
- verify(southboundHandlerSpy, times(1)).ovsdbUpdate(any(Node.class), any(DataObject.class), any(OvsdbInventoryListener.OvsdbType.class), any(Action.class));
-
- }
-
- @Test
- public void testNotifyNode() {
- when(southbound.getBridge(any(Node.class))).thenReturn(mock(OvsdbBridgeAugmentation.class));
-
- NetworkingProvider networkingProvider = mock(NetworkingProvider.class);
- when(networkingProviderManager.getProvider(any(Node.class))).thenReturn(networkingProvider);
-
- southboundHandlerSpy.notifyNode(mock(Node.class), Action.ADD);
-
- verify(networkingProvider, times(1)).initializeOFFlowRules(any(Node.class));
- }
-
- @Test
- public void testProcessEvent() {
- SouthboundEvent ev = mock(SouthboundEvent.class);
- Node node = mock(Node.class);
-
- // NODE
- when(ev.getNode()).thenReturn(node);
- when(ev.getAugmentationData()).thenReturn(mock(OvsdbNodeAugmentation.class));
- when(ev.getType()).thenReturn(SouthboundEvent.Type.NODE);
-
- when(ev.getAction()).thenReturn(Action.ADD);
- southboundHandler.processEvent(ev);
- verify(nodeCacheManager, times(1)).nodeAdded(any(Node.class));
- verify(bridgeConfigurationManager, times(1)).prepareNode(any(Node.class));
- Mockito.reset(nodeCacheManager);
-
- when(ev.getAction()).thenReturn(Action.UPDATE);
- southboundHandler.processEvent(ev);
- verify(nodeCacheManager, times(1)).nodeAdded(any(Node.class));
- Mockito.reset(nodeCacheManager);
-
- when(ev.getAction()).thenReturn(Action.DELETE);
- southboundHandler.processEvent(ev);
- verify(nodeCacheManager, times(1)).nodeRemoved(any(Node.class));
- Mockito.reset(nodeCacheManager);
-
- Mockito.reset(ev);
-
- // BRIDGE
- OvsdbBridgeAugmentation br = mock(OvsdbBridgeAugmentation.class);
- OvsdbBridgeName brName = mock(OvsdbBridgeName.class);
- when(br.getBridgeName()).thenReturn(brName);
- when(configurationService.getIntegrationBridgeName()).thenReturn(Constants.INTEGRATION_BRIDGE);
-
- when(ev.getNode()).thenReturn(node);
- when(ev.getAugmentationData()).thenReturn(br);
- when(ev.getType()).thenReturn(SouthboundEvent.Type.BRIDGE);
-
- when(southbound.getDatapathId(any(OvsdbBridgeAugmentation.class))).thenReturn("45");
-
- when(ev.getAction()).thenReturn(Action.ADD);
- southboundHandler.processEvent(ev);
- verify(nodeCacheManager, times(1)).nodeAdded(any(Node.class));
- Mockito.reset(nodeCacheManager);
-
- when(ev.getAction()).thenReturn(Action.UPDATE);
- southboundHandler.processEvent(ev);
- verify(nodeCacheManager, times(1)).nodeAdded(any(Node.class));
- Mockito.reset(nodeCacheManager);
-
- when(ev.getAction()).thenReturn(Action.DELETE);
- // Verify that non-integration bridges are deleted
- when(brName.getValue()).thenReturn("br-test");
- southboundHandler.processEvent(ev);
- verify(nodeCacheManager, times(1)).nodeRemoved(any(Node.class));
- verify(southbound, times(1)).deleteBridge(any(Node.class));
- Mockito.reset(nodeCacheManager);
- Mockito.reset(southbound);
- // Verify that integration bridge is not deleted
- when(brName.getValue()).thenReturn(Constants.INTEGRATION_BRIDGE);
- southboundHandler.processEvent(ev);
- verify(nodeCacheManager, times(1)).nodeRemoved(any(Node.class));
- verify(southbound, times(0)).deleteBridge(any(Node.class));
- Mockito.reset(nodeCacheManager);
- Mockito.reset(southbound);
-
- Mockito.reset(ev);
-
- // PORT
- OvsdbTerminationPointAugmentation ovsdbTerminationPointAugmentation = mock(OvsdbTerminationPointAugmentation.class);
- when(ovsdbTerminationPointAugmentation.getName()).thenReturn("network");
-// Mockito.<Class<?>>when(ovsdbTerminationPointAugmentation.getInterfaceType()).thenReturn(InterfaceTypeBase.class);
-// when(ovsdbTerminationPointAugmentation.getInterfaceType()).thenReturn(n);
- when(ev.getNode()).thenReturn(node);
- when(ev.getAugmentationData()).thenReturn(ovsdbTerminationPointAugmentation);
- when(ev.getType()).thenReturn(SouthboundEvent.Type.PORT);
-
- NetworkingProvider networkingProvider = mock(NetworkingProvider.class);
- NeutronNetwork neutronNetwork = mock(NeutronNetwork.class);
- when(neutronNetwork.getRouterExternal()).thenReturn(false);
- when(tenantNetworkManager.getTenantNetwork(any(OvsdbTerminationPointAugmentation.class))).thenReturn(neutronNetwork);
- when(networkingProviderManager.getProvider(any(Node.class))).thenReturn(networkingProvider);
- when(bridgeConfigurationManager.createLocalNetwork(any(Node.class), any(NeutronNetwork.class))).thenReturn(true);
-
- when(ev.getAction()).thenReturn(Action.ADD);
- southboundHandler.processEvent(ev);
- verify(neutronL3Adapter, times(1)).handleInterfaceEvent(any(Node.class), any(OvsdbTerminationPointAugmentation.class), any(NeutronNetwork.class), any(Action.class));
- verify(networkingProvider, times(1)).handleInterfaceUpdate(any(NeutronNetwork.class), any(Node.class), any(OvsdbTerminationPointAugmentation.class));
- Mockito.reset(neutronL3Adapter);
- Mockito.reset(networkingProvider);
-
- when(ev.getAction()).thenReturn(Action.UPDATE);
- NeutronPort neutronPort = mock(NeutronPort.class);
- when(tenantNetworkManager.getTenantPort(any(OvsdbTerminationPointAugmentation.class))).thenReturn(neutronPort);
- southboundHandler.processEvent(ev);
- verify(distributedArpService, times(1)).processInterfaceEvent(any(Node.class), any(OvsdbTerminationPointAugmentation.class), any(NeutronNetwork.class), any(Boolean.class), any(Action.class));
- verify(neutronL3Adapter, times(1)).handleInterfaceEvent(any(Node.class), any(OvsdbTerminationPointAugmentation.class), any(NeutronNetwork.class), any(Action.class));
- verify(networkingProvider, times(1)).handleInterfaceUpdate(any(NeutronNetwork.class), any(Node.class), any(OvsdbTerminationPointAugmentation.class));
- Mockito.reset(neutronL3Adapter);
- Mockito.reset(distributedArpService);
- Mockito.reset(networkingProvider);
-
-// List<String> phyIfName = new ArrayList<String>();
-// phyIfName.add("network");
-// when(bridgeConfigurationManager.getAllPhysicalInterfaceNames(any(Node.class))).thenReturn(phyIfName);
-//
-// when(ev.getAction()).thenReturn(Action.DELETE); //isInterfaceOfIntereset true
-// southboundHandler.processEvent(ev);
-// verify(neutronL3Adapter, times(1)).handleInterfaceEvent(any(Node.class), any(OvsdbTerminationPointAugmentation.class), any(NeutronNetwork.class), any(Action.class));
-// verify(networkingProvider, times(1)).handleInterfaceDelete(anyString(), any(NeutronNetwork.class), any(Node.class), any(OvsdbTerminationPointAugmentation.class), anyBoolean());
-//
-// Mockito.reset(networkingProvider);
-//
-// when(southbound.getBridge(any(Node.class))).thenReturn(mock(OvsdbBridgeAugmentation.class));
-// List<TerminationPoint> terminationPoints = new ArrayList<TerminationPoint>();
-// TerminationPoint terminationPoint = mock(TerminationPoint.class);
-// OvsdbTerminationPointAugmentation ovsdbTerminationPointAugmentation2 = mock(OvsdbTerminationPointAugmentation.class);
-// when(terminationPoint.getAugmentation(any(Class.class))).thenReturn(ovsdbTerminationPointAugmentation);
-// Uuid uuid = mock(Uuid.class);
-// when(ovsdbTerminationPointAugmentation.getInterfaceUuid()).thenReturn(uuid);
-// when(ovsdbTerminationPointAugmentation2.getInterfaceUuid()).thenReturn(uuid);
-// terminationPoints.add(terminationPoint);
-// when(node.getTerminationPoint()).thenReturn(terminationPoints);
-//
-// when(ev.getAction()).thenReturn(Action.DELETE); //isInterfaceOfIntereset false - network != null
-// southboundHandler.processEvent(ev);
-// verify(networkingProvider, times(1)).handleInterfaceDelete(anyString(), any(NeutronNetwork.class), any(Node.class), any(OvsdbTerminationPointAugmentation.class), anyBoolean());
-
- // OPENVSWITCH
- when(ev.getNode()).thenReturn(node);
- when(ev.getAugmentationData()).thenReturn(ovsdbTerminationPointAugmentation);
- when(ev.getType()).thenReturn(SouthboundEvent.Type.OPENVSWITCH);
-
- when(ovsdbTerminationPointAugmentation.getName()).thenReturn("network");
- List<TerminationPoint> terminationPoints = new ArrayList<>();
- terminationPoints.add(mock(TerminationPoint.class));
- when(southbound.extractTerminationPoints(any(Node.class))).thenReturn(terminationPoints);
- }
-
- @Test
- public void testSetDependencies() throws Exception {
- ConfigurationService configurationService = mock(ConfigurationService.class);
- NetworkingProviderManager networkingProviderManager = mock(NetworkingProviderManager.class);
- TenantNetworkManager tenantNetworkManager = mock(TenantNetworkManager.class);
- BridgeConfigurationManager bridgeConfigurationManager = mock(BridgeConfigurationManager.class);
- NodeCacheManager nodeCacheManager = mock(NodeCacheManager.class);
- NeutronL3Adapter neutronL3Adapter = mock(NeutronL3Adapter.class);
- DistributedArpService distributedArpService = mock(DistributedArpService.class);
- Southbound southbound = mock(Southbound.class);
- EventDispatcher eventDispatcher = mock(EventDispatcher.class);
- OvsdbInventoryService ovsdbInventoryService = mock(OvsdbInventoryService.class);
-
- ServiceHelper.overrideGlobalInstance(ConfigurationService.class, configurationService);
- ServiceHelper.overrideGlobalInstance(NetworkingProviderManager.class, networkingProviderManager);
- ServiceHelper.overrideGlobalInstance(TenantNetworkManager.class, tenantNetworkManager);
- ServiceHelper.overrideGlobalInstance(BridgeConfigurationManager.class, bridgeConfigurationManager);
- ServiceHelper.overrideGlobalInstance(NodeCacheManager.class, nodeCacheManager);
- ServiceHelper.overrideGlobalInstance(DistributedArpService.class, distributedArpService);
- ServiceHelper.overrideGlobalInstance(NeutronL3Adapter.class, neutronL3Adapter);
- ServiceHelper.overrideGlobalInstance(Southbound.class, southbound);
- ServiceHelper.overrideGlobalInstance(EventDispatcher.class, eventDispatcher);
- ServiceHelper.overrideGlobalInstance(OvsdbInventoryService.class, ovsdbInventoryService);
-
- southboundHandler.setDependencies(mock(ServiceReference.class));
- assertEquals("Error, did not return the correct object", getField("configurationService"), configurationService);
- assertEquals("Error, did not return the correct object", getField("networkingProviderManager"), networkingProviderManager);
- assertEquals("Error, did not return the correct object", getField("tenantNetworkManager"), tenantNetworkManager);
- assertEquals("Error, did not return the correct object", getField("bridgeConfigurationManager"), bridgeConfigurationManager);
- assertEquals("Error, did not return the correct object", getField("nodeCacheManager"), nodeCacheManager);
- assertEquals("Error, did not return the correct object", getField("distributedArpService"), distributedArpService);
- assertEquals("Error, did not return the correct object", getField("neutronL3Adapter"), neutronL3Adapter);
- assertEquals("Error, did not return the correct object", getField("southbound"), southbound);
- assertEquals("Error, did not return the correct object", getField("ovsdbInventoryService"), ovsdbInventoryService);
- assertEquals("Error, did not return the correct object", southboundHandler.eventDispatcher, eventDispatcher);
- }
-
- private Object getField(String fieldName) throws Exception {
- Field field = SouthboundHandler.class.getDeclaredField(fieldName);
- field.setAccessible(true);
- return field.get(southboundHandler);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2016 Inocybe 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.netvirt.openstack.netvirt;
-
-import static org.junit.Assert.assertEquals;
-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;
-import java.net.HttpURLConnection;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.EventDispatcher;
-import org.opendaylight.netvirt.openstack.netvirt.impl.NeutronL3Adapter;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSubnet;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.osgi.framework.ServiceReference;
-
-/**
- * Unit test fort {@link SubnetHandler}
- */
-@RunWith(MockitoJUnitRunner.class)
-public class SubnetHandlerTest {
-
- @InjectMocks private SubnetHandler subnetHandler;
-
- @Mock NeutronL3Adapter neutronl3Adapter;
-
- @Test
- public void testCanCreateSubnet() {
- assertEquals("Error, canCreateSubnet() did not return the correct HTTP flag", HttpURLConnection.HTTP_OK, subnetHandler.canCreateSubnet(mock(NeutronSubnet.class)));
- }
-
- @Test
- public void testCanUpdateSubnet() {
- assertEquals("Error, canUpdateSubnet() did not return the correct HTTP flag", HttpURLConnection.HTTP_OK, subnetHandler.canUpdateSubnet(mock(NeutronSubnet.class), mock(NeutronSubnet.class)));
- }
-
- @Test
- public void testCanDeleteSubnet() {
- assertEquals("Error, canDeleteSubnet() did not return the correct HTTP flag", HttpURLConnection.HTTP_OK, subnetHandler.canDeleteSubnet(mock(NeutronSubnet.class)));
- }
-
- @Test
- public void testProcessEvent() {
- NorthboundEvent ev = mock(NorthboundEvent.class);
- when(ev.getSubnet()).thenReturn(mock(NeutronSubnet.class));
-
- when(ev.getAction()).thenReturn(Action.ADD);
- subnetHandler.processEvent(ev);
- verify(neutronl3Adapter, times(1)).handleNeutronSubnetEvent(ev.getSubnet(), ev.getAction());
-
- when(ev.getAction()).thenReturn(Action.DELETE);
- subnetHandler.processEvent(ev);
- verify(neutronl3Adapter, times(1)).handleNeutronSubnetEvent(ev.getSubnet(), ev.getAction());
-
- when(ev.getAction()).thenReturn(Action.UPDATE);
- subnetHandler.processEvent(ev);
- verify(neutronl3Adapter, times(1)).handleNeutronSubnetEvent(ev.getSubnet(), ev.getAction());
- }
-
- @Test
- public void testSetDependencies() throws Exception {
- NeutronL3Adapter neutronL3Adapter = mock(NeutronL3Adapter.class);
- EventDispatcher eventDispatcher = mock(EventDispatcher.class);
-
- ServiceHelper.overrideGlobalInstance(NeutronL3Adapter.class, neutronL3Adapter);
- ServiceHelper.overrideGlobalInstance(EventDispatcher.class, eventDispatcher);
-
- subnetHandler.setDependencies(mock(ServiceReference.class));
-
- assertEquals("Error, did not return the correct object", getField("neutronL3Adapter"), neutronL3Adapter);
- assertEquals("Error, did not return the correct object", subnetHandler.eventDispatcher, eventDispatcher);
- }
-
- private Object getField(String fieldName) throws Exception {
- Field field = SubnetHandler.class.getDeclaredField(fieldName);
- field.setAccessible(true);
- return field.get(subnetHandler);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Intel Corp. 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.netvirt.openstack.netvirt.api;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import java.util.HashMap;
-import java.util.Map;
-import org.junit.Before;
-import org.junit.Test;
-
-public class LoadBalancerConfigurationTest {
- private LoadBalancerConfiguration lbConfig;
- private Map<String, LoadBalancerConfiguration.LoadBalancerPoolMember> lbMap = new HashMap<>();
- private Object[][] valuesArray =
- {{"mockUUID1", "mockUUID2", "mockUUID3"},
- {"10.10.1.343", "10.10.1.391", "10.10.1.31"},
- {"D5:6B:59:E8:F4:84", "D5:4B:60:E8:F5:84", "D5:4B:60:E8:F6:84"},
- {"tcp", "tcp", "http"},
- {125304, 125304, 1204}};
-
- @Before
- public void setUp() throws Exception {
- lbConfig = new LoadBalancerConfiguration();
- lbConfig.addMember(valuesArray[0][0].toString(), valuesArray[1][0].toString(),
- valuesArray[2][0].toString(), valuesArray[3][0].toString(), (Integer)valuesArray[4][0]);
- lbConfig.addMember(valuesArray[0][1].toString(), valuesArray[1][1].toString(),
- valuesArray[2][1].toString(), valuesArray[3][1].toString(), (Integer)valuesArray[4][1]);
- lbMap = lbConfig.getMembers();
- }
-
- @Test
- public void testConstructorLbConfig() throws Exception{
- lbConfig.setName("test-name");
- lbConfig.setProviderNetworkType("vlan");
- lbConfig.setProviderSegmentationId("segment-id-mock");
- lbConfig.setVip("192.168.58.87");
- lbConfig.setVmac("A2-E2-24-E3-44-8D");
- LoadBalancerConfiguration lbConfigLocal = new LoadBalancerConfiguration(lbConfig);
-
- assertEquals("getName() returned the wrong value", "test-name", lbConfigLocal.getName());
- assertEquals("getProviderNetworkType() returned the wrong value", "vlan",
- lbConfigLocal.getProviderNetworkType());
- assertEquals("getProviderSegmentationId() returned the wrong value", "segment-id-mock",
- lbConfigLocal.getProviderSegmentationId());
- assertEquals("getVip() returned the wrong value", "192.168.58.87", lbConfigLocal.getVip());
- assertEquals("getVmac() returned the wrong value", "A2-E2-24-E3-44-8D", lbConfigLocal.getVmac());
-
- Map<String, LoadBalancerConfiguration.LoadBalancerPoolMember> lbMapLocal = lbConfigLocal.getMembers();
- for (LoadBalancerConfiguration.LoadBalancerPoolMember lbMember: lbMapLocal.values()){
- assertTrue("IP expected " + valuesArray[1][lbMember.getIndex()] + " found: " +
- lbMember.getIP(), valuesArray[1][lbMember.getIndex()] == lbMember.getIP());
- assertTrue("MAC expected " + valuesArray[2][lbMember.getIndex()] + " found " +
- lbMember.getMAC(), valuesArray[2][lbMember.getIndex()] == lbMember.getMAC());
- assertTrue("protocol expected " + valuesArray[3][lbMember.getIndex()] + " found " +
- lbMember.getProtocol(), valuesArray[3][lbMember.getIndex()] == lbMember.getProtocol());
- assertTrue("port expected " + valuesArray[4][lbMember.getIndex()] + " found " +
- lbMember.getPort(), valuesArray[4][lbMember.getIndex()].equals(lbMember.getPort()));
- }
- }
-
- @Test
- public void testGetMembers() throws Exception {
- Map<String, LoadBalancerConfiguration.LoadBalancerPoolMember> lbMapLocal = lbConfig.getMembers();
- for (LoadBalancerConfiguration.LoadBalancerPoolMember lbMember: lbMapLocal.values()){
- assertTrue("IP expected " + valuesArray[1][lbMember.getIndex()] + " found: " +
- lbMember.getIP(), valuesArray[1][lbMember.getIndex()] == lbMember.getIP());
- assertTrue("MAC expected " + valuesArray[2][lbMember.getIndex()] + " found " +
- lbMember.getMAC(), valuesArray[2][lbMember.getIndex()] == lbMember.getMAC());
- assertTrue("protocol expected " + valuesArray[3][lbMember.getIndex()] + " found " +
- lbMember.getProtocol(), valuesArray[3][lbMember.getIndex()] == lbMember.getProtocol());
- assertTrue("port expected " + valuesArray[4][lbMember.getIndex()] + " found " +
- lbMember.getPort(), valuesArray[4][lbMember.getIndex()].equals(lbMember.getPort()));
- }
- assertEquals("Get members does not return members", lbMap, lbConfig.getMembers());
- }
-
- @Test
- public void testAddMember() throws Exception {
- lbConfig.addMember(valuesArray[0][2].toString(), valuesArray[1][2].toString(), valuesArray[2][2].toString(),
- valuesArray[3][2].toString(), (Integer)valuesArray[4][2]);
- Map<String, LoadBalancerConfiguration.LoadBalancerPoolMember> lbMapLocal2 = lbConfig.getMembers();
- assertTrue("Error, maps are unequal after adding a member. Size should be " + 3 +
- " but size is " + lbMapLocal2.size(), 3 == lbMapLocal2.size());
- }
-
- @Test
- public void testRemoveMember() throws Exception {
- lbConfig.addMember(valuesArray[0][2].toString(), valuesArray[1][2].toString(), valuesArray[2][2].toString(),
- valuesArray[3][2].toString(), (Integer)valuesArray[4][2]);
- Map<String, LoadBalancerConfiguration.LoadBalancerPoolMember> lbMapLocal = lbConfig.getMembers();
- assertTrue("Error, maps are not equal lbMapLocal size is " + lbMapLocal.size() + " size should be " +
- 3, lbMapLocal.size() == 3);
- lbConfig.removeMember("mockUUID3");
- Map<String, LoadBalancerConfiguration.LoadBalancerPoolMember> lbMapLocal2 = lbConfig.getMembers();
- assertTrue("Error, maps are unequal after removing a member, size should be " + 2 + " but is " +
- lbMapLocal2.size(), 2 == lbMapLocal2.size());
- }
-
- @Test
- public void testIsValid() throws Exception {
- assertFalse("load balancer config returned true for isValid, should be true ", lbConfig.isValid());
- lbConfig.setProviderNetworkType("mockProviderNetworkType");
- assertTrue("load balancer config returned false for isValid, should be true ", lbConfig.isValid());
- lbConfig.removeMember("mockUUID2");
- lbConfig.removeMember("mockUUID1");
- assertFalse("load balancer config returned true for isValid, should be false ", lbConfig.isValid());
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2016 Intel Corp. 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.netvirt.openstack.netvirt.impl;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyList;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.RETURNS_MOCKS;
-import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.reset;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyNoMoreInteractions;
-import static org.mockito.Mockito.when;
-
-import java.lang.reflect.Field;
-import java.util.List;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.Matchers;
-import org.mockito.Mock;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.netvirt.openstack.netvirt.api.OvsdbTables;
-import org.opendaylight.netvirt.openstack.netvirt.api.ConfigurationService;
-import org.opendaylight.netvirt.openstack.netvirt.api.NetworkingProviderManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.DatapathTypeSystem;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation;
-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.osgi.framework.ServiceReference;
-
-/**
- * Test class for BridgeConfigurationManagerImpl
- *
- * @author Marcus Koontz
- * @author Alexis de Talhouet
- * @author Sam Hague (shague@redhat.com)
- */
-@RunWith(MockitoJUnitRunner.class)
-public class BridgeConfigurationManagerImplTest {
- @Mock private Node node;
- @Mock private OvsdbBridgeAugmentation bridge;
- @Mock private OvsdbTerminationPointAugmentation port;
- @Mock private NeutronNetwork neutronNetwork;
- @Mock private ConfigurationService configurationService;
- @Mock private Southbound southbound;
- @InjectMocks public static BridgeConfigurationManagerImpl bridgeConfigurationManagerImpl;
-
- private static final String ADDRESS = "127.0.0.1";
- private static final String BR_INT = "br-int";
- private static final String ETH1 = "eth1";
- private static final String ETH2 = "eth2";
- private static final String ETH3 = "eth3";
- private static final String PORT_BR_INT = "br-int";
- private static final String BRIDGE_UUID = "f527b951-3934-4182-9f29-33fc09f6f0c6";
- private static final String PHYSNET1 = "physnet1";
- private static final String PHYSNET2 = "physnet2";
- private static final String PHYSNET3 = "physnet3";
- private static final String PROVIDER_MAPPINGS = PHYSNET1 + ":" + ETH1 + "," + PHYSNET2 + ":" + ETH2;
- private static final String PROVIDER_MAPPINGS_DEFAULT = PHYSNET1 + ":" + ETH1;
-
- @Test
- public void testGetBridgeUuid() {
- when(southbound.getBridgeUuid(any(Node.class), anyString()))
- .thenReturn(null)
- .thenReturn(BRIDGE_UUID);
-
- assertEquals("Error, null should have been returned", null,
- bridgeConfigurationManagerImpl.getBridgeUuid(node, BR_INT));
- assertEquals("Error, did not return UUID of correct bridge", BRIDGE_UUID,
- bridgeConfigurationManagerImpl.getBridgeUuid(node, BR_INT));
- verify(southbound, times(2)).getBridgeUuid(any(Node.class), anyString());
- }
-
- @Test
- public void testIsNodeNeutronReady() throws Exception {
- when(southbound.getBridge(any(Node.class), anyString()))
- .thenReturn(null)
- .thenReturn(bridge);
-
- verifyNoMoreInteractions(configurationService);
- assertFalse("Error, did not return correct boolean from isNodeNeutronReady",
- bridgeConfigurationManagerImpl.isNodeNeutronReady(node));
-
- when(configurationService.getIntegrationBridgeName()).thenReturn(BR_INT);
- assertTrue("Error, did not return correct boolean from isNodeNeutronReady",
- bridgeConfigurationManagerImpl.isNodeNeutronReady(node));
-
- verify(configurationService, times(2)).getIntegrationBridgeName();
- verify(southbound, times(2)).getBridge(any(Node.class), anyString());
- }
-
- @Test
- public void testIsNodeOverlayReady() throws Exception {
- when(southbound.getBridge(any(Node.class), anyString()))
- .thenReturn(null)
- .thenReturn(bridge);
-
- BridgeConfigurationManagerImpl bridgeConfigurationManagerImplSpy =
- spy(new BridgeConfigurationManagerImpl());
- doReturn(false).when(bridgeConfigurationManagerImplSpy).isNodeNeutronReady(any(Node.class));
- bridgeConfigurationManagerImplSpy.setConfigurationService(configurationService);
- bridgeConfigurationManagerImplSpy.setSouthbound(southbound);
-
- verifyNoMoreInteractions(configurationService);
-
- assertFalse("Error, did not return correct boolean from isNodeOverlayReady",
- bridgeConfigurationManagerImplSpy.isNodeOverlayReady(node));
-
- doReturn(true).when(bridgeConfigurationManagerImplSpy).isNodeNeutronReady(any(Node.class));
-
- assertFalse("Error, did not return correct boolean from isNodeOverlayReady",
- bridgeConfigurationManagerImplSpy.isNodeOverlayReady(node));
-
- assertTrue("Error, did not return correct boolean from isNodeOverlayReady",
- bridgeConfigurationManagerImplSpy.isNodeOverlayReady(node));
-
- verify(configurationService, times(2)).getNetworkBridgeName();
- verify(southbound, times(2)).getBridge(any(Node.class), anyString());
- }
-
- @Test
- public void testIsPortOnBridge() throws Exception {
- when(southbound.extractTerminationPointAugmentation(any(Node.class), anyString()))
- .thenReturn(null)
- .thenReturn(port);
-
- assertFalse("Error, port " + PORT_BR_INT + " should not be found",
- bridgeConfigurationManagerImpl.isPortOnBridge(node, PORT_BR_INT));
- assertTrue("Error, port " + PORT_BR_INT + " should be found",
- bridgeConfigurationManagerImpl.isPortOnBridge(node, PORT_BR_INT));
- verify(southbound, times(2)).extractTerminationPointAugmentation(any(Node.class), anyString());
- }
-
- @Test
- public void testIsNodeTunnelReady() throws Exception {
- when(southbound.isBridgeOnOvsdbNode(any(Node.class), anyString()))
- .thenReturn(false)
- .thenReturn(true);
-
- verifyNoMoreInteractions(configurationService);
- assertFalse("Error, did not return correct boolean from isNodeTunnelReady",
- bridgeConfigurationManagerImpl.isNodeTunnelReady(node, node));
-
- when(configurationService.isL3ForwardingEnabled()).thenReturn(false);
- when(configurationService.getIntegrationBridgeName()).thenReturn(BR_INT);
- assertTrue("Error, did not return correct boolean from isNodeTunnelReady",
- bridgeConfigurationManagerImpl.isNodeTunnelReady(node, node));
-
- verify(configurationService, times(1)).isL3ForwardingEnabled();
- verify(configurationService, times(3)).getIntegrationBridgeName();
- verify(southbound, times(2)).isBridgeOnOvsdbNode(any(Node.class), anyString());
- }
-
- @Test
- public void testIsNodeVlanReady() throws Exception {
- when(southbound.isBridgeOnOvsdbNode(any(Node.class), anyString()))
- .thenReturn(false)
- .thenReturn(true);
-
- when(southbound.extractTerminationPointAugmentation(any(Node.class), anyString()))
- .thenReturn(null)
- .thenReturn(port);
-
- when(neutronNetwork.getProviderPhysicalNetwork()).thenReturn("test");
-
- verifyNoMoreInteractions(configurationService);
- assertFalse("Error, did not return correct boolean from isNodeTunnelReady",
- bridgeConfigurationManagerImpl.isNodeVlanReady(node, node, neutronNetwork));
-
- BridgeConfigurationManagerImpl bridgeConfigurationManagerImplSpy =
- spy(new BridgeConfigurationManagerImpl());
- doReturn(ETH1).when(bridgeConfigurationManagerImplSpy).getPhysicalInterfaceName(any(Node.class), anyString());
- bridgeConfigurationManagerImplSpy.setConfigurationService(configurationService);
- bridgeConfigurationManagerImplSpy.setSouthbound(southbound);
-
- assertFalse("Error, did not return correct boolean from isNodeVlanReady",
- bridgeConfigurationManagerImpl.isNodeVlanReady(node, node, neutronNetwork));
-
- assertTrue("Error, did not return correct boolean from isNodeVlanReady",
- bridgeConfigurationManagerImpl.isNodeVlanReady(node, node, neutronNetwork));
-
- verify(configurationService, times(3)).getIntegrationBridgeName();
- verify(neutronNetwork, times(2)).getProviderPhysicalNetwork();
- }
-
- @Test
- public void testIsNodeL3Ready() {
- when(southbound.isBridgeOnOvsdbNode(any(Node.class), anyString())).thenReturn(true);
- when(southbound.extractTerminationPointAugmentation(any(Node.class), anyString())).thenReturn(mock(OvsdbTerminationPointAugmentation.class));
- when(southbound.readBridgeNode(any(Node.class), anyString())).thenReturn(mock(Node.class));
-
- assertTrue("Error, isNodeL3Ready didn't return true", bridgeConfigurationManagerImpl.isNodeL3Ready(node, node));
- }
-
- @Test
- public void testPrepareNode() {
- when(configurationService.getIntegrationBridgeName()).thenReturn(BR_INT);
- when(southbound.isBridgeOnOvsdbNode(any(Node.class), anyString())).thenReturn(false);
-
- // TODO Figure out the strings
- //when(ConfigProperties.getProperty(any(Class.class), anyString())).thenReturn(ADDRESS);
-
- when(southbound.addBridge(any(Node.class), anyString(), anyList(), eq(DatapathTypeSystem.class))).thenReturn(true);
- when(southbound.readConfigBridge(any(Node.class), anyString())).thenReturn(mock(Node.class));
- when(configurationService.isL3ForwardingEnabled()).thenReturn(true);
- when(configurationService.isL3MultipleExternalNetworkEnabled()).thenReturn(true);
- bridgeConfigurationManagerImpl.prepareNode(node);
-
- // TODO This test doesn't verify anything
- }
-
- @Test
- public void testCreateLocalNetwork() throws Exception {
- NeutronNetwork neutronNetworkMock = mock(NeutronNetwork.class, RETURNS_MOCKS);
- String networkTypes[] = {"vlan", "vxlan", "gre"};
- BridgeConfigurationManagerImpl bridgeConfigurationManagerImplSpy =
- spy(new BridgeConfigurationManagerImpl());
- bridgeConfigurationManagerImplSpy.setConfigurationService(configurationService);
- bridgeConfigurationManagerImplSpy.setSouthbound(southbound);
-
- for (String networkType : networkTypes) {
- when(neutronNetworkMock.getProviderNetworkType()).thenReturn(networkType);
- when(southbound.readOvsdbNode(any(Node.class))).thenReturn(node);
-
- doAnswer(invocation -> Boolean.TRUE).when(bridgeConfigurationManagerImplSpy).isNodeVlanReady(any(Node.class), any(Node.class), any(NeutronNetwork.class));
-
- doAnswer(invocation -> Boolean.TRUE).when(bridgeConfigurationManagerImplSpy).isNodeTunnelReady(any(Node.class), any(Node.class));
-
- assertTrue("bridgeConfigMock.isNodeVlanReady is not true",
- bridgeConfigurationManagerImplSpy.isNodeVlanReady(node, node, neutronNetworkMock));
- assertTrue("bridgeConfigMock.isNodeTunnelReady is not true",
- bridgeConfigurationManagerImplSpy.isNodeTunnelReady(node, node));
-
- assertTrue("Error, isCreated is not true for " + networkType,
- bridgeConfigurationManagerImplSpy.createLocalNetwork(node, neutronNetworkMock));
- switch (networkType) {
- case "vlan":
- verify(neutronNetworkMock, times(1)).getProviderNetworkType();
- break;
- case "vxlan":
- verify(neutronNetworkMock, times(2)).getProviderNetworkType();
- break;
- case "gre":
- verify(neutronNetworkMock, times(3)).getProviderNetworkType();
- break;
- }
- reset(neutronNetworkMock);
- reset(node);
- reset(bridgeConfigurationManagerImplSpy);
- }
- }
-
- @Test
- public void testGetPhysicalInterfaceName() throws Exception {
- when(southbound.getOtherConfig(any(Node.class), Matchers.eq(OvsdbTables.OPENVSWITCH), anyString()))
- .thenReturn(null)
- .thenReturn(null)
- .thenReturn(PROVIDER_MAPPINGS);
- String networkNames[] = {PHYSNET1, PHYSNET2};
- String interfaceNames[] = {ETH1, ETH2};
-
- verifyNoMoreInteractions(configurationService);
- when(configurationService.getDefaultProviderMapping()).thenReturn(PROVIDER_MAPPINGS_DEFAULT);
-
- assertNull("Error, should not have found " + PHYSNET2 + ":" + ETH2,
- bridgeConfigurationManagerImpl.getPhysicalInterfaceName(node, PHYSNET2));
- assertEquals("Error, should have found " + PHYSNET1 + ":" + ETH1,
- ETH1, bridgeConfigurationManagerImpl.getPhysicalInterfaceName(node, PHYSNET1));
- for (int i = 0; i < networkNames.length; i++) {
- assertEquals("Error, network: " + networkNames[i]
- + ", did not match interface: "+ interfaceNames[i],
- interfaceNames[i],
- bridgeConfigurationManagerImpl.getPhysicalInterfaceName(node, networkNames[i]));
- }
- assertNull(PHYSNET1, bridgeConfigurationManagerImpl.getPhysicalInterfaceName(node, PHYSNET3));
- verify(configurationService, times(5)).getProviderMappingsKey();
- verify(configurationService, times(2)).getDefaultProviderMapping();
- verify(southbound, times(5)).getOtherConfig(any(Node.class), eq(OvsdbTables.OPENVSWITCH), anyString());
- }
-
- @Test
- public void testGetAllPhysicalInterfaceNames() throws Exception {
- when(southbound.getOtherConfig(any(Node.class), eq(OvsdbTables.OPENVSWITCH), anyString()))
- .thenReturn(null)
- .thenReturn(PROVIDER_MAPPINGS);
-
- verifyNoMoreInteractions(configurationService);
- when(configurationService.getDefaultProviderMapping()).thenReturn(PROVIDER_MAPPINGS_DEFAULT);
-
- List<String> interfaces = bridgeConfigurationManagerImpl.getAllPhysicalInterfaceNames(node);
- assertEquals("Error, should have found 1 interface", 1, interfaces.size());
- assertTrue("Error, should have found " + ETH1, interfaces.contains(ETH1));
- assertFalse("Error, should not have found " + ETH2, interfaces.contains(ETH2));
- interfaces = bridgeConfigurationManagerImpl.getAllPhysicalInterfaceNames(node);
- assertEquals("Error, should have found 2 interfaces", 2, interfaces.size());
- assertTrue("Error, should have found " + ETH1, interfaces.contains(ETH1));
- assertTrue("Error, should have found " + ETH1, interfaces.contains(ETH2));
- assertFalse("Error, should not have found " + ETH3, interfaces.contains(ETH3));
-
- verify(configurationService, times(2)).getProviderMappingsKey();
- verify(configurationService, times(1)).getDefaultProviderMapping();
- verify(southbound, times(2)).getOtherConfig(any(Node.class), eq(OvsdbTables.OPENVSWITCH), anyString());
- }
-
- @Test
- public void testSetDependencies() throws Exception {
- ConfigurationService configurationService = mock(ConfigurationService.class);
- NetworkingProviderManager networkingProviderManager = mock(NetworkingProviderManager.class);
- Southbound southbound = mock(Southbound.class);
-
- ServiceHelper.overrideGlobalInstance(ConfigurationService.class, configurationService);
- ServiceHelper.overrideGlobalInstance(NetworkingProviderManager.class, networkingProviderManager);
- ServiceHelper.overrideGlobalInstance(Southbound.class, southbound);
-
- bridgeConfigurationManagerImpl.setDependencies(mock(ServiceReference.class));
-
- assertEquals("Error, did not return the correct object", getField("configurationService"), configurationService);
- assertEquals("Error, did not return the correct object", getField("networkingProviderManager"), networkingProviderManager);
- assertEquals("Error, did not return the correct object", getField("southbound"), southbound);
- }
-
- private Object getField(String fieldName) throws Exception {
- Field field = BridgeConfigurationManagerImpl.class.getDeclaredField(fieldName);
- field.setAccessible(true);
- return field.get(bridgeConfigurationManagerImpl);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2016 Inocybe 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.netvirt.openstack.netvirt.impl;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-import java.lang.reflect.Field;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.netvirt.openstack.netvirt.api.OvsdbTables;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.utils.config.ConfigProperties;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-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.network.topology.topology
- .Node;
-import org.osgi.framework.ServiceReference;
-
-/**
- * Unit test for {@link ConfigurationServiceImpl}
- */
-@RunWith(MockitoJUnitRunner.class)
-public class ConfigurationServiceImplTest {
-
- @InjectMocks private ConfigurationServiceImpl configurationServiceImpl;
-
- @Mock private Southbound southbound;
-
- private static final String ADDRESS = "127.0.0.1";
- private static final String IS_FOWARDING_ENABLE = "yes";
- private static final String IS_LEARN_ENABLE = "yes";
- private static final String IS_MULTIPLE_EXTERNAL_NETWORK_ENABLE = "yes";
-
- /**
- * Test method {@link ConfigurationServiceImpl#getTunnelEndPoint(Node)}
- */
- @Test
- public void testGetTunnelEndPoint() throws Exception {
- when(southbound.getOtherConfig(any(Node.class), any(OvsdbTables.class), anyString())).thenReturn(ADDRESS);
-
- assertEquals("Error, did not return the expected address", ADDRESS, configurationServiceImpl.getTunnelEndPoint(mock(Node.class)).getHostAddress());
- }
-
- @Test
- public void testGetOpenFlowVersion() {
- assertEquals("Error, did not return the correct OF version", Constants.OPENFLOW13, configurationServiceImpl.getOpenflowVersion(mock(Node.class)));
- }
-
- @Test
- public void testIsL3FowardingEnable() {
- ConfigProperties.overrideProperty("ovsdb.l3.fwd.enabled", IS_FOWARDING_ENABLE);
-
- assertTrue("Error, l3 fowarding should be activated", configurationServiceImpl.isL3ForwardingEnabled());
- }
-
- @Test
- public void testIsRemoteMacLearnEnabled() {
- ConfigProperties.overrideProperty("ovsdb.remotemac.learn.enabled", IS_LEARN_ENABLE);
-
- assertTrue("Error, remote mac learn should be activated", configurationServiceImpl.isRemoteMacLearnEnabled());
- }
-
- @Test
- public void testIsL3MultipleExternalNetworkEnabled() {
- ConfigProperties.overrideProperty("ovsdb.l3.multiple.network.enabled", IS_MULTIPLE_EXTERNAL_NETWORK_ENABLE);
-
- assertTrue("Error, l3 multiple external network should be activated", configurationServiceImpl.isL3MultipleExternalNetworkEnabled());
- }
-
- /**
- * Test method {@link ConfigurationServiceImpl#getDefaultGatewayMacAddress(Node)}
- */
- @Test
- public void testGetDefaultGatewayMacAddress(){
- Node node = mock(Node.class);
- NodeId nodeId = mock(NodeId.class);
-
- when(node.getNodeId()).thenReturn(nodeId);
- when(nodeId.getValue()).thenReturn("nodeIdValue");
- ConfigProperties.overrideProperty("ovsdb.l3gateway.mac." + node.getNodeId().getValue(), "gateway");
-
- assertEquals("Error, did not return the defaultGatewayMacAddress of the node", "gateway",
- configurationServiceImpl.getDefaultGatewayMacAddress(node));
- }
-
- @Test
- public void testSetDependencies() throws Exception {
- Southbound southbound = mock(Southbound.class);
-
- ServiceHelper.overrideGlobalInstance(Southbound.class, southbound);
-
- configurationServiceImpl.setDependencies(mock(ServiceReference.class));
-
- assertEquals("Error, did not return the correct object", getField("southbound"), southbound);
- }
-
- private Object getField(String fieldName) throws Exception {
- Field field = ConfigurationServiceImpl.class.getDeclaredField(fieldName);
- field.setAccessible(true);
- return field.get(configurationServiceImpl);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 NEC Corporation 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.netvirt.openstack.netvirt.impl;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyLong;
-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.when;
-
-import java.lang.reflect.Field;
-import java.net.InetAddress;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.ArpProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.ConfigurationService;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.Status;
-import org.opendaylight.netvirt.openstack.netvirt.api.StatusCode;
-import org.opendaylight.netvirt.openstack.netvirt.api.TenantNetworkManager;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronNetworkCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronPortCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation;
-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.NodeId;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-
-import org.osgi.framework.ServiceReference;
-import org.powermock.api.mockito.PowerMockito;
-import org.powermock.api.support.membermodification.MemberMatcher;
-import org.powermock.api.support.membermodification.MemberModifier;
-import org.powermock.core.classloader.annotations.PrepareForTest;
-import org.powermock.modules.junit4.PowerMockRunner;
-import org.powermock.reflect.Whitebox;
-
-/**
- * Unit test for {@link DistributedArpService}
- */
-@PrepareForTest({ServiceHelper.class, InetAddress.class, DistributedArpService.class})
-@RunWith(PowerMockRunner.class)
-public class DistributedArpServiceTest {
-
- @Mock private DistributedArpService distributedArpService;
- /**
- * ID used for testing different scenarios.
- */
- private static final String ID = "45";
- /**
- * IP used for testing different scenarios.
- */
- private static final String IP = "127.0.0.1";
- /**
- * MALFORM_IP used for testing different scenarios.
- */
- private static final String MALFORM_IP = "127.0.0.1.5";
- /**
- * INTF_NAME used for testing different scenarios.
- */
- private static final String INTF_NAME = "br-int";
- /**
- * UUID used for testing different scenarios.
- */
- private static final String UUID = "7da709ff-397f-4778-a0e8-994811272fdb";
- /**
- * FIXED_IP_ADDRESS used for testing different scenarios.
- */
- private static final String FIXED_IP_ADDRESS = "192.168.1.0";
- /**
- * MAC_ADDRESS used for testing different scenarios.
- */
- private static final String MAC_ADDRESS = "00:00:5E:00:02:01";
- /**
- * MAC_ADDRESS_2 used for testing different scenarios.
- */
- private static final String MAC_ADDRESS_2 = "00:00:5E:00:02:02";
- /**
- * PORT_INT used for testing different scenarios.
- */
- private static final String PORT_INT = "port_int";
-
- @Before
- public void setUp() throws Exception{
- distributedArpService = PowerMockito.spy(new DistributedArpService());
- }
-
- /**
- * Test that checks if @{DistributedArpService#handlePortEvent} is called
- * and then checks that the port event process to write arp rules for neutron ports based on action.
- */
- @Test
- public void testHandlePortEvent() throws Exception {
- NeutronPort neutronPort = PowerMockito.mock(NeutronPort.class);
- Node node = PowerMockito.mock(Node.class);
-
- // Suppress the called to these functions.
- MemberModifier.suppress(MemberMatcher.method(DistributedArpService.class, "handleNeutronPortForArp", NeutronPort.class, Node.class, boolean.class, Action.class));
-
- Whitebox.invokeMethod(distributedArpService, "handlePortEvent", neutronPort, node, false, Action.ADD);
- PowerMockito.verifyPrivate(distributedArpService, times(1)).invoke("handleNeutronPortForArp", any(NeutronPort.class), any(Node.class), any(boolean.class), eq(Action.ADD));
-
- //Case 1: Delete Action.
- Whitebox.invokeMethod(distributedArpService, "handlePortEvent", neutronPort, node, false, Action.DELETE);
- PowerMockito.verifyPrivate(distributedArpService, times(1)).invoke("handleNeutronPortForArp", any(NeutronPort.class), any(Node.class), any(boolean.class), eq(Action.DELETE));
- }
-
- /**
- * Test that checks if @{DistributedArpService#programStaticRuleStage1} is called
- * and then checks that the arp rules are added/removed based on neutron port event.
- */
- @Test
- public void testProgramStaticRuleStage1() throws Exception {
- MemberModifier.suppress(MemberMatcher.method(DistributedArpService.class, "programStaticRuleStage2", Long.class, String.class, String.class, String.class, Action.class));
- PowerMockito.when(distributedArpService, "programStaticRuleStage2", anyLong(), anyString(), anyString(), anyString(), any(Action.class)).thenReturn(new Status(StatusCode.SUCCESS));
-
- //Case 1: Add Action.
- Whitebox.invokeMethod(distributedArpService, "programStaticRuleStage1", 12L, PORT_INT, MAC_ADDRESS, IP, Action.ADD);
- PowerMockito.verifyPrivate(distributedArpService, times(1)).invoke("programStaticRuleStage2", anyLong(), anyString(), anyString(), anyString(), eq(Action.ADD));
-
- //Case 2: Delete Action.
- Whitebox.invokeMethod(distributedArpService, "programStaticRuleStage1", 12L, PORT_INT, MAC_ADDRESS, IP, Action.DELETE);
- PowerMockito.verifyPrivate(distributedArpService, times(1)).invoke("programStaticRuleStage2", anyLong(), anyString(), anyString(), anyString(), eq(Action.DELETE));
- }
-
- /**
- * Test that checks if @{DistributedArpService#programStaticRuleStage2} is called
- * and then checks that the arp rules are programmed by invoke arpProvider.
- */
- @Test
- public void testProgramStaticRuleStage2() throws Exception {
- //Case 1: StatusCode BADREQUEST.
- assertEquals("Error, this not return the correct status code", new Status(StatusCode.BADREQUEST), Whitebox.invokeMethod(distributedArpService, "programStaticRuleStage2",
- 45L, PORT_INT, MAC_ADDRESS, MALFORM_IP, Action.ADD));
- PowerMockito.mockStatic(InetAddress.class);
- InetAddress inetAddress = mock(InetAddress.class);
- PowerMockito.when(InetAddress.getByName(anyString())).thenReturn(inetAddress);
-
- //Case 2: StatusCode SUCCESS.
- assertEquals("Error, this not return the correct status code", new Status(StatusCode.SUCCESS), Whitebox.invokeMethod(distributedArpService, "programStaticRuleStage2",
- 45L, PORT_INT, MAC_ADDRESS, IP, Action.DELETE));
- }
-
- /**
- * Test that checks if @{DistributedArpService#handleNeutornPortForArp} is called
- * and then checks that the arp rules are written based on event for neutron port.
- */
- @Test
- public void testHandleNeutornPortForArp() throws Exception {
- Southbound southbound = mock(Southbound.class);
- Neutron_IPs neutronIp = mock(Neutron_IPs.class);
- when(neutronIp.getIpAddress()).thenReturn(FIXED_IP_ADDRESS);
- List<Neutron_IPs> neutronIps = new ArrayList<>();
- neutronIps.add(neutronIp);
- NeutronPort neutronPort = mock(NeutronPort.class);
- when(neutronPort.getNetworkUUID()).thenReturn(UUID);
- when(neutronPort.getMacAddress()).thenReturn(MAC_ADDRESS_2);
- when(neutronPort.getFixedIPs()).thenReturn(neutronIps);
- NeutronNetwork neutronNetwork = mock(NeutronNetwork.class);
- when(neutronNetwork.getProviderSegmentationID()).thenReturn(ID);
- List<Node> nodes = new ArrayList<>();
- nodes.add(mock(Node.class));
- TenantNetworkManager tenantNetworkManager = mock(TenantNetworkManager.class);
- MemberModifier.field(DistributedArpService.class, "tenantNetworkManager").set(distributedArpService, tenantNetworkManager);
- when(tenantNetworkManager.isTenantNetworkPresentInNode(any(Node.class), eq(ID))).thenReturn(true);
- PowerMockito.doReturn(15L).when(distributedArpService, "getDatapathIdIntegrationBridge", any(Node.class));
- INeutronNetworkCRUD neutronNetworkCache = mock(INeutronNetworkCRUD.class);
- when(neutronNetworkCache.getNetwork(anyString())).thenReturn(neutronNetwork);
- MemberModifier.field(DistributedArpService.class, "neutronNetworkCache").set(distributedArpService, neutronNetworkCache);
- NodeCacheManager nodeCacheManager = mock(NodeCacheManager.class);
- when(nodeCacheManager.getBridgeNodes()).thenReturn(nodes);
- MemberModifier.field(DistributedArpService.class, "nodeCacheManager").set(distributedArpService, nodeCacheManager);
- MemberModifier.field(DistributedArpService.class, "flgDistributedARPEnabled").set(distributedArpService, true);
-
- // Suppress the called to these functions.
- MemberModifier.suppress(MemberMatcher.method(DistributedArpService.class, "programStaticRuleStage1", Long.class, String.class, String.class, String.class, Action.class));
-
- List<OvsdbTerminationPointAugmentation> ports = new ArrayList<>();
- ports.add(mock(OvsdbTerminationPointAugmentation.class));
- PowerMockito.when(southbound.readTerminationPointAugmentations(any(Node.class))).thenReturn(ports);
-
- PowerMockito.doReturn(true).when(distributedArpService, "getNeutronPortsForNode", any(Node.class), any(List.class), anyString());
- Whitebox.invokeMethod(distributedArpService, "handleNeutronPortForArp", neutronPort, mock(Node.class), false, Action.ADD);
- PowerMockito.verifyPrivate(distributedArpService, times(1)).invoke("getDatapathIdIntegrationBridge", any(Node.class));
-
- // Case 2: Delete Action.
- Whitebox.invokeMethod(distributedArpService, "handleNeutronPortForArp", neutronPort, mock(Node.class), false, Action.DELETE);
- PowerMockito.verifyPrivate(distributedArpService, times(2)).invoke("getDatapathIdIntegrationBridge", any(Node.class));
- }
-
- /**
- * Test that checks if @{DistributedArpService#getDatapathIdIntegrationBridge} is called
- * and then checks the node integration bridge, then return its datapathID.
- */
- @Test
- public void testGetDatapathIdIntegrationBridge() throws Exception {
- Southbound southbound = mock(Southbound.class);
- ConfigurationService configurationService = mock(ConfigurationService.class);
-
- MemberModifier.field(DistributedArpService.class, "southbound").set(distributedArpService, southbound);
- MemberModifier.field(DistributedArpService.class, "configurationService").set(distributedArpService, configurationService);
-
- PowerMockito.when(southbound.getBridge(any(Node.class), anyString())).thenReturn(mock(OvsdbBridgeAugmentation.class));
- PowerMockito.when(configurationService.getIntegrationBridgeName()).thenReturn("");
- PowerMockito.when(southbound.getDataPathId(any(Node.class))).thenReturn(45L);
-
- //Assert check for correct Dp Id.
- assertEquals("Error, did not return the correct Dpid", 45, (long)Whitebox.invokeMethod(distributedArpService, "getDatapathIdIntegrationBridge", mock(Node.class)));
- }
-
- /**
- * Test that checks if @{DistributedArpService#processInterfaceEvent} is called
- * and then checks that the event is processing.
- */
- @Test
- public void testProcessInterfaceEvent() throws Exception {
- NeutronPort neutronPort = mock(NeutronPort.class);
- NeutronNetwork neutronNetwork = mock(NeutronNetwork.class);
- PowerMockito.doNothing().when(distributedArpService).handlePortEvent(any(NeutronPort.class), any(Node.class), any(boolean.class), any(Action.class));
- // init instance variables.
- TenantNetworkManager tenantNetworkManager = mock(TenantNetworkManager.class);
- MemberModifier.field(DistributedArpService.class, "tenantNetworkManager").set(distributedArpService , tenantNetworkManager);
-
- // Mock variables
- NodeId nodeId = mock(NodeId.class);
- when(nodeId.getValue()).thenReturn(ID);
- Node node = mock(Node.class);
- when(node.getNodeId()).thenReturn(nodeId);
-
- OvsdbTerminationPointAugmentation intf = mock(OvsdbTerminationPointAugmentation.class);
- when(intf.getName()).thenReturn(INTF_NAME);
-
- when(tenantNetworkManager.getTenantPort(intf)).thenReturn(neutronPort);
-
- //Case 1: Add Action.
- distributedArpService.processInterfaceEvent(node, intf, neutronNetwork, false, Action.ADD);
- Mockito.verify(distributedArpService, times(1)).handlePortEvent(neutronPort, node, false, Action.ADD);
-
- //Case 2: Delete Action.
- distributedArpService.processInterfaceEvent(node, intf, neutronNetwork, false, Action.DELETE);
- Mockito.verify(distributedArpService, times(1)).handlePortEvent(neutronPort, node, false, Action.DELETE);
- }
-
- /**
- * Test that checks if @{DistributedArpService#setDependencies} is called
- * and then checks the object instances.
- */
- @Test
- public void testSetDependencies() throws Exception {
- TenantNetworkManager tenantNetworkManager = mock(TenantNetworkManager.class);
- ConfigurationService configurationService = mock(ConfigurationService.class);
- ArpProvider arpProvider = mock(ArpProvider.class);
- NodeCacheManager nodeCacheManager = mock(NodeCacheManager.class);
- Southbound southbound = mock(Southbound.class);
-
- ServiceHelper.overrideGlobalInstance(TenantNetworkManager.class, tenantNetworkManager);
- ServiceHelper.overrideGlobalInstance(ConfigurationService.class, configurationService);
- ServiceHelper.overrideGlobalInstance(ArpProvider.class, arpProvider);
- ServiceHelper.overrideGlobalInstance(NodeCacheManager.class, nodeCacheManager);
- ServiceHelper.overrideGlobalInstance(Southbound.class, southbound);
-
- distributedArpService.setDependencies(mock(ServiceReference.class));
-
- assertEquals("Error, did not return the correct object", getField("tenantNetworkManager"), tenantNetworkManager);
- assertEquals("Error, did not return the correct object", getField("configurationService"), configurationService);
- assertEquals("Error, did not return the correct object", getField("arpProvider"), arpProvider);
- assertEquals("Error, did not return the correct object", getField("nodeCacheManager"), nodeCacheManager);
- assertEquals("Error, did not return the correct object", getField("southbound"), southbound);
- }
-
- /**
- * Test that checks if @{DistributedArpService#setDependencies} is called
- * and then checks the object instances.
- */
- @Test
- public void testSetDependenciesObject() throws Exception{
- INeutronNetworkCRUD iNeutronNetworkCRUD = mock(INeutronNetworkCRUD.class);
- distributedArpService.setDependencies(iNeutronNetworkCRUD);
- assertEquals("Error, did not return the correct object", getField("neutronNetworkCache"), iNeutronNetworkCRUD);
-
- INeutronPortCRUD iNeutronPortCRUD = mock(INeutronPortCRUD.class);
- distributedArpService.setDependencies(iNeutronPortCRUD);
- assertEquals("Error, did not return the correct object", getField("neutronPortCache"), iNeutronPortCRUD);
-
- ArpProvider arpProvider = mock(ArpProvider.class);
- distributedArpService.setDependencies(arpProvider);
- assertEquals("Error, did not return the correct object", getField("arpProvider"), arpProvider);
- }
-
-
- private Object getField(String fieldName) throws Exception {
- Field field = DistributedArpService.class.getDeclaredField(fieldName);
- field.setAccessible(true);
- return field.get(distributedArpService);
- }
-
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (c) 2015, 2016 Inocybe 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.netvirt.openstack.netvirt.impl;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNull;
-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;
-import java.util.Random;
-import java.util.concurrent.BlockingQueue;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.netvirt.openstack.netvirt.AbstractHandler;
-import org.opendaylight.netvirt.openstack.netvirt.AbstractEvent;
-import org.opendaylight.netvirt.openstack.netvirt.api.Constants;
-import org.osgi.framework.ServiceReference;
-
-/**
- * Unit test for {@link EventDispatcherImpl}
- */
-public class EventDispatcherImplTest {
-
- private EventDispatcherImpl eventDispatcherImpl = new EventDispatcherImpl();
-
- private AbstractHandler handler = mock(AbstractHandler.class);
- private ServiceReference<?> ref = mock(ServiceReference.class);
-
- private AbstractEvent.HandlerType handlerTypeObject = AbstractEvent.HandlerType.NEUTRON_FLOATING_IP;
-
- @Before
- public void setUp() {
- Random r = new Random();
-
- when(ref.getProperty(org.osgi.framework.Constants.SERVICE_ID)).thenReturn(r.nextLong());
- when(ref.getProperty(Constants.EVENT_HANDLER_TYPE_PROPERTY)).thenReturn(handlerTypeObject);
- }
-
- /**
- * Test methods {@link EventDispatcherImpl#eventHandlerRemoved(ServiceReference)}
- * and {@link EventDispatcherImpl#eventHandlerAdded(ServiceReference, AbstractHandler)}
- */
- @Test
- public void testHandlerAddedAndRemoved() throws Exception{
- AbstractHandler[] handlers = ( AbstractHandler[]) getField("handlers");
-
- assertNotEquals("Error, handler should be null", handlers[handlerTypeObject.ordinal()], handler);
-
- eventDispatcherImpl.eventHandlerAdded(ref, handler);
-
- assertEquals("Error, did not return the added handler", handlers[handlerTypeObject.ordinal()], handler);
-
- eventDispatcherImpl.eventHandlerRemoved(ref);
-
- assertNull("Error, handler should be null as it has just been removed", handlers[handlerTypeObject.ordinal()]);
- }
-
- /**
- * Test method {@link EventDispatcherImpl#enqueueEvent(AbstractEvent)}
- */
- @SuppressWarnings("unchecked")
- @Test
- public void testEnqueueEvent() throws Exception{
- BlockingQueue<AbstractEvent> events = (BlockingQueue<AbstractEvent>) getField("events");
-
- assertEquals("Error, did not return the expected size, nothing has been added yet", 0, events.size());
-
- eventDispatcherImpl.eventHandlerAdded(ref, handler);
-
- AbstractEvent mockEvent = mock(AbstractEvent.class);
- when(mockEvent.getHandlerType()).thenReturn(handlerTypeObject);
- final int numEnqueues = 4;
- for (int i = 0; i < numEnqueues; i++) {
- eventDispatcherImpl.enqueueEvent(mockEvent);
- }
-
- // Because events are processed in a different thread, this is a race
- // We want to ensure that all the events were enqueued; so the sum of
- // what's been processed and what's still in the queue must equal the
- // number of events we enqueued
- eventDispatcherImpl.stop();
- verify(handler, times(numEnqueues - events.size())).processEvent(mockEvent);
- }
-
- private Object getField(String fieldName) throws Exception {
- Field field = EventDispatcherImpl.class.getDeclaredField(fieldName);
- field.setAccessible(true);
- return field.get(eventDispatcherImpl);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2016 Inocybe 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.netvirt.openstack.netvirt.impl;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyBoolean;
-import static org.mockito.Matchers.anyInt;
-import static org.mockito.Matchers.anyLong;
-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.when;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Field;
-import java.net.InetAddress;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-
-import org.apache.commons.lang3.tuple.Pair;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronFloatingIP;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronRouter;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronRouter_Interface;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSubnet;
-import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronFloatingIPCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronNetworkCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronPortCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSubnetCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.AbstractHandler;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.ArpProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.ConfigurationService;
-import org.opendaylight.netvirt.openstack.netvirt.api.EventDispatcher;
-import org.opendaylight.netvirt.openstack.netvirt.api.InboundNatProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.L3ForwardingProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.OutboundNatProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.RoutingProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.openstack.netvirt.api.Status;
-import org.opendaylight.netvirt.openstack.netvirt.api.StatusCode;
-import org.opendaylight.netvirt.openstack.netvirt.api.TenantNetworkManager;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation;
-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.NodeId;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-
-import org.osgi.framework.ServiceReference;
-import org.powermock.api.mockito.PowerMockito;
-import org.powermock.api.support.membermodification.MemberMatcher;
-import org.powermock.api.support.membermodification.MemberModifier;
-import org.powermock.core.classloader.annotations.PrepareForTest;
-import org.powermock.modules.junit4.PowerMockRunner;
-import org.powermock.reflect.Whitebox;
-
-/**
- * Unit test for {@link NeutronL3Adapter}
- */
-@PrepareForTest({ServiceHelper.class, InetAddress.class, NeutronL3Adapter.class, DistributedArpService.class})
-@RunWith(PowerMockRunner.class)
-public class NeutronL3AdapterTest {
-
- @Mock private NeutronL3Adapter neutronL3Adapter;
- @Mock private DistributedArpService distributedArpService;
-
- private static final String ID = "45";
- private static final String IP = "127.0.0.1";
- private static final String MALFORM_IP = "127.0.0.1.5";
- private static final String INTF_NAME = "br-int";
- private static final String EXTERNAL_ROUTER_MAC_UPDATE = "";
- private static final String UUID = "7da709ff-397f-4778-a0e8-994811272fdb";
- private static final String FIXED_IP_ADDRESS = "192.168.1.0";
- private static final String FLOATING_IP_ADDRESS = "192.168.1.1";
- private static final String OWNER_ROUTER_INTERFACE = "network:router_interface";
- private static final String OWNER_FLOATING_IP = "network:floatingip";
- private static final String MAC_ADDRESS = "00:00:5E:00:02:01";
- private static final String MAC_ADDRESS_2 = "00:00:5E:00:02:02";
- private static final String PORT_INT = "port_int";
- private static final String SEG_ID = "2";
- private static final String CIDR = "192.168.100.0/24";
- private static final String OFPort = "OFPort|45";
- private static final String IP_MASK = "127.0.0.1/32";
-
- @SuppressWarnings("rawtypes")
- private Class floatingIpClass;
- private Object floatingIpObject;
-
- @Before
- public void setUp() throws Exception{
- neutronL3Adapter = PowerMockito.mock(NeutronL3Adapter.class, Mockito.CALLS_REAL_METHODS);
- Whitebox.setInternalState(neutronL3Adapter, "distributedArpService", distributedArpService);
- // init instance variables
- MemberModifier.field(NeutronL3Adapter.class, "enabled").set(neutronL3Adapter, true);
-
- // floating ip (nested private class from NeutronL3Adapter)
- floatingIpClass = Whitebox.getInnerClassType(NeutronL3Adapter.class, "FloatIpData");
- floatingIpObject = createFloatingIpObject();
- }
-
- @Test
- public void testUpdateExternalRouterMac() throws Exception {
- // Suppress the called to these functions
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "flushExistingIpRewrite"));
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "rebuildExistingIpRewrite"));
-
- neutronL3Adapter.updateExternalRouterMac(EXTERNAL_ROUTER_MAC_UPDATE);
-
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("flushExistingIpRewrite");
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("rebuildExistingIpRewrite");
- }
-
- @Test
- public void testhandleNeutronSubnetEvent() throws Exception {
- ConcurrentMap<String,NeutronNetwork> networkCleanupCache = new ConcurrentHashMap<>();
- INeutronNetworkCRUD neutronNetworkCache = mock(INeutronNetworkCRUD.class);
- NeutronNetwork neutronNetwork = mock(NeutronNetwork.class);
- when(neutronNetwork.getNetworkUUID()).thenReturn("00000000-0000-0000-0000-000000000000");
- when(neutronNetworkCache.getNetwork(anyString())).thenReturn(neutronNetwork);
- // Mock variables
- MemberModifier.field(NeutronL3Adapter.class, "networkCleanupCache").set(neutronL3Adapter , networkCleanupCache);
- MemberModifier.field(NeutronL3Adapter.class, "neutronNetworkCache").set(neutronL3Adapter , neutronNetworkCache);
- neutronL3Adapter.handleNeutronSubnetEvent(mock(NeutronSubnet.class), Action.ADD);
- }
-
- @Test
- public void testHandleNeutronPortEvent() throws Exception {
- Map<String, NeutronRouter_Interface> subnetIdToRouterInterfaceCache = new HashMap<>();
- ConcurrentMap<String,NeutronPort> portCleanupCache = new ConcurrentHashMap<>();
- // Mock variables
- Neutron_IPs neutronIP = mock(Neutron_IPs.class);
- when(neutronIP.getSubnetUUID()).thenReturn(UUID);
- List<Neutron_IPs> list_neutronIP = new ArrayList<>();
- list_neutronIP.add(neutronIP);
- NeutronPort neutronPort = mock(NeutronPort.class);
- when(neutronPort.getDeviceOwner()).thenReturn(OWNER_ROUTER_INTERFACE);
- when(neutronPort.getFixedIPs()).thenReturn(list_neutronIP);
- INeutronFloatingIPCRUD neutronFloatingIpCache = mock(INeutronFloatingIPCRUD.class);
-
- // init instance variables
- MemberModifier.field(NeutronL3Adapter.class, "neutronPortCache").set(neutronL3Adapter , mock(INeutronPortCRUD.class));
- subnetIdToRouterInterfaceCache.put(UUID, mock(NeutronRouter_Interface.class));
- MemberModifier.field(NeutronL3Adapter.class, "subnetIdToRouterInterfaceCache").set(neutronL3Adapter , subnetIdToRouterInterfaceCache);
- MemberModifier.field(NeutronL3Adapter.class, "portCleanupCache").set(neutronL3Adapter , portCleanupCache);
- MemberModifier.field(NeutronL3Adapter.class, "neutronFloatingIpCache").set(neutronL3Adapter , neutronFloatingIpCache);
-
- // Suppress the called to these functions
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "updateL3ForNeutronPort", NeutronPort.class, boolean.class));
- Mockito.doNothing().when(neutronL3Adapter).handleNeutronRouterInterfaceEvent(any(NeutronRouter.class), any(NeutronRouter_Interface.class), any(Action.class));
-
- neutronL3Adapter.handleNeutronPortEvent(neutronPort, Action.ADD);
- Mockito.verify(neutronL3Adapter).handleNeutronRouterInterfaceEvent(any(NeutronRouter.class), any(NeutronRouter_Interface.class), eq(Action.ADD));
-
- when(neutronPort.getDeviceOwner()).thenReturn("");
- neutronL3Adapter.handleNeutronPortEvent(neutronPort, Action.ADD);
- Mockito.verify(neutronL3Adapter, times(2)).handleNeutronRouterInterfaceEvent(any(NeutronRouter.class), any(NeutronRouter_Interface.class), eq(Action.ADD));
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("updateL3ForNeutronPort", any(NeutronPort.class), eq(false));
-
- neutronL3Adapter.handleNeutronPortEvent(neutronPort, Action.DELETE);
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("updateL3ForNeutronPort", any(NeutronPort.class), eq(true));
- }
-
- @Test
- public void testhandleNeutronRouterEvent() throws Exception {
- // Nothing to be done here
- neutronL3Adapter.handleNeutronRouterEvent(mock(NeutronRouter.class), Action.ADD);
- }
-
- @Test
- public void testHandleNeutronRouterInterfaceEvent() throws Exception {
- // Mock variables
- NeutronRouter_Interface neutronRouterInterface = mock(NeutronRouter_Interface.class);
- when(neutronRouterInterface.getPortUUID()).thenReturn(UUID);
- when(neutronRouterInterface.getSubnetUUID()).thenReturn(UUID);
-
- Neutron_IPs neutronIP = mock(Neutron_IPs.class);
- when(neutronIP.getSubnetUUID()).thenReturn(UUID);
- NeutronPort neutronPort = mock(NeutronPort.class);
- List<Neutron_IPs> list_neutronIP = new ArrayList<>();
- list_neutronIP.add(neutronIP);
- when(neutronPort.getFixedIPs()).thenReturn(list_neutronIP);
- List<NeutronPort> list_neutronPort = new ArrayList<>();
- list_neutronPort.add(neutronPort);
- INeutronPortCRUD neutronPortCache = mock(INeutronPortCRUD.class);
- when(neutronPortCache.getAllPorts()).thenReturn(list_neutronPort);
-
- // init instance variables
- MemberModifier.field(NeutronL3Adapter.class, "neutronPortCache").set(neutronL3Adapter , neutronPortCache);
-
- // Suppress the called to these functions
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "programFlowsForNeutronRouterInterface", NeutronRouter_Interface.class, Boolean.class));
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "updateL3ForNeutronPort", NeutronPort.class, boolean.class));
-
- neutronL3Adapter.handleNeutronRouterInterfaceEvent(mock(NeutronRouter.class), neutronRouterInterface, Action.ADD);
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("programFlowsForNeutronRouterInterface", any(NeutronRouter_Interface.class), eq(false));
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("updateL3ForNeutronPort", any(NeutronPort.class), eq(false));
-
- neutronL3Adapter.handleNeutronRouterInterfaceEvent(mock(NeutronRouter.class), neutronRouterInterface, Action.DELETE);
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("programFlowsForNeutronRouterInterface", any(NeutronRouter_Interface.class), eq(true));
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("updateL3ForNeutronPort", any(NeutronPort.class), eq(true));
- }
-
- @Test
- public void testHandleNeutronFloatingIPEvent() throws Exception {
- // Mock variables
- NeutronFloatingIP neutronFloatingIP = mock(NeutronFloatingIP.class);
- when(neutronFloatingIP.getFixedIPAddress()).thenReturn(FIXED_IP_ADDRESS);
- when(neutronFloatingIP.getFloatingIPAddress()).thenReturn(FLOATING_IP_ADDRESS);
- when(neutronFloatingIP.getID()).thenReturn(UUID);
-
- // Suppress the called to these functions
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "programFlowsForFloatingIPArpAdd", NeutronFloatingIP.class));
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "programFlowsForFloatingIPInbound", NeutronFloatingIP.class, Action.class));
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "programFlowsForFloatingIPOutbound", NeutronFloatingIP.class, Action.class));
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "programFlowsForFloatingIPArpDelete", String.class));
-
- neutronL3Adapter.handleNeutronFloatingIPEvent(neutronFloatingIP, Action.ADD);
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("programFlowsForFloatingIPArpAdd", any(NeutronFloatingIP.class));
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("programFlowsForFloatingIPInbound", any(NeutronFloatingIP.class), eq(Action.ADD));
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("programFlowsForFloatingIPOutbound", any(NeutronFloatingIP.class), eq(Action.ADD));
-
- neutronL3Adapter.handleNeutronFloatingIPEvent(neutronFloatingIP, Action.DELETE);
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("programFlowsForFloatingIPArpDelete", anyString());
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("programFlowsForFloatingIPInbound", any(NeutronFloatingIP.class), eq(Action.DELETE));
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("programFlowsForFloatingIPOutbound", any(NeutronFloatingIP.class), eq(Action.DELETE));
- }
-
- @SuppressWarnings({ "unchecked", "rawtypes" })
- @Test
- public void testProgramFlowsForFloatingIPInbound() throws Exception {
- Map floatIpDataMapCache = new HashMap();
-
- NeutronFloatingIP neutronFloatingIp = mock(NeutronFloatingIP.class);
- when(neutronFloatingIp.getID()).thenReturn(ID);
-
- // init instance variables
- floatIpDataMapCache .put(ID, floatingIpObject);
- MemberModifier.field(NeutronL3Adapter.class, "floatIpDataMapCache").set(neutronL3Adapter , floatIpDataMapCache);
-
- // Suppress the called to these functions
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "programInboundIpRewriteStage1", Long.class, Long.class, String.class, String.class, String.class, Action.class));
-
- Whitebox.invokeMethod(neutronL3Adapter, "programFlowsForFloatingIPInbound", neutronFloatingIp, Action.ADD);
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("programInboundIpRewriteStage1", anyLong(), anyLong(), anyString(), anyString(), anyString(), eq(Action.ADD));
- }
-
- @SuppressWarnings({ "unchecked", "rawtypes" })
- @Test
- public void testProgramFlowsForFloatingIPOutbound() throws Exception {
- Map floatIpDataMapCache = new HashMap();
-
- NeutronFloatingIP neutronFloatingIp = mock(NeutronFloatingIP.class);
- when(neutronFloatingIp.getID()).thenReturn(ID);
-
- // init instance variables
- floatIpDataMapCache.put(ID, floatingIpObject);
- MemberModifier.field(NeutronL3Adapter.class, "floatIpDataMapCache").set(neutronL3Adapter , floatIpDataMapCache);
-
- // Suppress the called to these functions
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "programOutboundIpRewriteStage1", floatingIpClass, Action.class));
-
- Whitebox.invokeMethod(neutronL3Adapter, "programFlowsForFloatingIPOutbound", neutronFloatingIp, Action.ADD);
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("programOutboundIpRewriteStage1", any(floatingIpClass), eq(Action.ADD));
- }
-
- @SuppressWarnings({ "unchecked", "rawtypes" })
- @Test
- public void testFlushExistingIpRewrite() throws Exception {
- Map floatIpDataMapCache = new HashMap();
-
- // init instance variables
- floatIpDataMapCache.put(ID, floatingIpObject);
- MemberModifier.field(NeutronL3Adapter.class, "floatIpDataMapCache").set(neutronL3Adapter , floatIpDataMapCache);
-
- // Suppress the called to these functions
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "programOutboundIpRewriteStage1", floatingIpClass, Action.class));
- PowerMockito.doReturn(floatIpDataMapCache.values()).when(neutronL3Adapter, "getAllFloatingIPsWithMetadata");
- Whitebox.invokeMethod(neutronL3Adapter, "flushExistingIpRewrite");
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("programOutboundIpRewriteStage1", any(floatingIpClass), eq(Action.DELETE));
- }
-
- @SuppressWarnings({ "unchecked", "rawtypes" })
- @Test
- public void testRebuildExistingIpRewrite() throws Exception {
- Map floatIpDataMapCache = new HashMap();
-
- // init instance variables
- floatIpDataMapCache.put(ID, floatingIpObject);
- MemberModifier.field(NeutronL3Adapter.class, "floatIpDataMapCache").set(neutronL3Adapter , floatIpDataMapCache);
-
- // Suppress the called to these functions
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "programOutboundIpRewriteStage1", floatingIpClass, Action.class));
-
- PowerMockito.doReturn(floatIpDataMapCache.values()).when(neutronL3Adapter, "getAllFloatingIPsWithMetadata");
- Whitebox.invokeMethod(neutronL3Adapter, "rebuildExistingIpRewrite");
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("programOutboundIpRewriteStage1", any(floatingIpClass), eq(Action.ADD));
- }
-
- @SuppressWarnings({ "unchecked", "rawtypes" })
- @Test
- public void testProgramFlowsForFloatingIPArpAdd() throws Exception {
- Map<String, Pair> neutronPortToDpIdCache = new HashMap<>();
- Map<String, String> networkIdToRouterMacCache = new HashMap<>();
- Map floatIpDataMapCache = new HashMap();
-
- NeutronFloatingIP neutronFloatingIP = mock(NeutronFloatingIP.class);
- when(neutronFloatingIP.getFixedIPAddress()).thenReturn(FIXED_IP_ADDRESS);
- when(neutronFloatingIP.getFloatingIPAddress()).thenReturn(FLOATING_IP_ADDRESS);
- when(neutronFloatingIP.getPortUUID()).thenReturn(UUID);
- NeutronPort neutronPort = mock(NeutronPort.class);
- when(neutronPort.getMacAddress()).thenReturn(MAC_ADDRESS);
- NeutronNetwork neutronNetwork = mock(NeutronNetwork.class);
- when(neutronNetwork.getProviderSegmentationID()).thenReturn(ID);
- when(neutronNetwork.getID()).thenReturn(ID);
-
- // init instance variables
- floatIpDataMapCache.put(ID, floatingIpObject);
- neutronPortToDpIdCache.put(UUID, mock(Pair.class));
- networkIdToRouterMacCache.put(ID, MAC_ADDRESS);
- INeutronNetworkCRUD neutronNetworkCache = mock(INeutronNetworkCRUD.class);
- when(neutronNetworkCache.getNetwork(anyString())).thenReturn(neutronNetwork);
- INeutronPortCRUD neutronPortCache = mock(INeutronPortCRUD.class);
- when(neutronPortCache.getPort(anyString())).thenReturn(neutronPort);
- PowerMockito.doReturn(neutronPort).when(neutronL3Adapter, "findNeutronPortForFloatingIp", anyString());
- PowerMockito.doReturn(15L).when(neutronL3Adapter, "findOFPortForExtPatch", anyLong());
- MemberModifier.field(NeutronL3Adapter.class, "floatIpDataMapCache").set(neutronL3Adapter , floatIpDataMapCache);
- MemberModifier.field(NeutronL3Adapter.class, "neutronPortToDpIdCache").set(neutronL3Adapter , neutronPortToDpIdCache);
- MemberModifier.field(NeutronL3Adapter.class, "neutronPortCache").set(neutronL3Adapter , neutronPortCache);
- MemberModifier.field(NeutronL3Adapter.class, "neutronNetworkCache").set(neutronL3Adapter , neutronNetworkCache);
- MemberModifier.field(NeutronL3Adapter.class, "networkIdToRouterMacCache").set(neutronL3Adapter , networkIdToRouterMacCache);
-
- // Suppress the called to these functions
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "findNeutronPortForFloatingIp", String.class));
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "findOFPortForExtPatch", Long.class));
-
- Whitebox.invokeMethod(neutronL3Adapter, "programFlowsForFloatingIPArpAdd", neutronFloatingIP);
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("findNeutronPortForFloatingIp", anyString());
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("findOFPortForExtPatch", anyLong());
- }
-
- @SuppressWarnings({ "unchecked", "rawtypes" })
- @Test
- public void testProgramFlowsForFloatingIPArpDelete() throws Exception {
- Map floatIpDataMapCache = new HashMap();
-
- // init instance variables
- floatIpDataMapCache.put(ID, floatingIpObject);
- MemberModifier.field(NeutronL3Adapter.class, "floatIpDataMapCache").set(neutronL3Adapter , floatIpDataMapCache);
-
- Whitebox.invokeMethod(neutronL3Adapter, "programFlowsForFloatingIPArpDelete", ID);
- }
-
- @Test
- public void testFindNeutronPortForFloatingIp() throws Exception {
- NeutronPort neutronPort = mock(NeutronPort.class);
- when(neutronPort.getDeviceOwner()).thenReturn(OWNER_FLOATING_IP);
- when(neutronPort.getDeviceID()).thenReturn(ID);
- List<NeutronPort> list_neutronPort = new ArrayList<>();
- list_neutronPort.add(neutronPort);
- INeutronPortCRUD neutronPortCache = mock(INeutronPortCRUD.class);
- when(neutronPortCache.getAllPorts()).thenReturn(list_neutronPort);
-
- MemberModifier.field(NeutronL3Adapter.class, "neutronPortCache").set(neutronL3Adapter , neutronPortCache);
-
- assertEquals("Error, did not return the correct NeutronPort", neutronPort, Whitebox.invokeMethod(neutronL3Adapter, "findNeutronPortForFloatingIp", ID));
- }
-
- @Test
- public void testFindOFPortForExtPatch() throws Exception {
- ConfigurationService configurationService = mock(ConfigurationService.class);
- when(configurationService.getPatchPortName(any(Pair.class))).thenReturn(PORT_INT);
- MemberModifier.field(NeutronL3Adapter.class, "configurationService").set(neutronL3Adapter , configurationService);
- List<Node> nodes = new ArrayList<>();
- nodes.add(mock(Node.class));
- NodeCacheManager nodeCacheManager = mock(NodeCacheManager.class);
- when(nodeCacheManager.getBridgeNodes()).thenReturn(nodes);
- MemberModifier.field(NeutronL3Adapter.class, "nodeCacheManager").set(neutronL3Adapter , nodeCacheManager);
- Southbound southbound = mock(Southbound.class);
- when(southbound.getDataPathId(any(Node.class))).thenReturn(Long.valueOf(ID));
- OvsdbTerminationPointAugmentation terminationPointOfBridge = mock(OvsdbTerminationPointAugmentation.class);
- when(terminationPointOfBridge.getOfport()).thenReturn(Long.valueOf(ID));
- when(southbound.getTerminationPointOfBridge(any(Node.class), anyString())).thenReturn(terminationPointOfBridge);
- MemberModifier.field(NeutronL3Adapter.class, "southbound").set(neutronL3Adapter , southbound);
-
- assertEquals("Error, did not return the correct NeutronPort", Long.valueOf(ID), Whitebox.invokeMethod(neutronL3Adapter, "findOFPortForExtPatch", Long.valueOf(ID)));
- }
-
- @Test
- public void testHandleNeutronNetworkEvent() throws Exception {
- // Nothing to be done here
- ConcurrentMap<String,NeutronNetwork> networkCleanupCache = new ConcurrentHashMap<>();
- // Mock variables
- MemberModifier.field(NeutronL3Adapter.class, "networkCleanupCache").set(neutronL3Adapter , networkCleanupCache);
- Whitebox.invokeMethod(neutronL3Adapter, "handleNeutronNetworkEvent", mock(NeutronNetwork.class), Action.ADD);
- }
-
- @Test
- public void testHandleInterfaceEvent() throws Exception {
- Map<String, Pair<Long, Uuid>> neutronPortToDpIdCache = new HashMap<>();
- // init instance variables
- TenantNetworkManager tenantNetworkManager = mock(TenantNetworkManager.class);
- MemberModifier.field(NeutronL3Adapter.class, "tenantNetworkManager").set(neutronL3Adapter , tenantNetworkManager);
- MemberModifier.field(NeutronL3Adapter.class, "neutronPortToDpIdCache").set(neutronL3Adapter , neutronPortToDpIdCache);
-
- // Mock variables
- NodeId nodeId = mock(NodeId.class);
- when(nodeId.getValue()).thenReturn(ID);
- Node node = mock(Node.class);
- when(node.getNodeId()).thenReturn(nodeId);
-
- OvsdbTerminationPointAugmentation intf = mock(OvsdbTerminationPointAugmentation.class);
- when(intf.getInterfaceUuid()).thenReturn(mock(Uuid.class));
- when(intf.getName()).thenReturn(INTF_NAME);
-
- NeutronPort neutronPort = mock(NeutronPort.class);
- when(neutronPort.getPortUUID()).thenReturn(UUID);
-
- when(tenantNetworkManager.getTenantPort(intf)).thenReturn(neutronPort);
-
- // Suppress the called to these functions
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "getDpidForIntegrationBridge", Node.class));
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "handleInterfaceEventAdd", String.class, Long.class, Uuid.class));
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "handleInterfaceEventDelete", OvsdbTerminationPointAugmentation.class, Long.class));
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "storePortInCleanupCache", NeutronPort.class));
-
- PowerMockito.when(neutronL3Adapter, "getDpidForIntegrationBridge", any(Node.class)).thenReturn(45L);
- Mockito.doNothing().when(neutronL3Adapter).handleNeutronPortEvent(any(NeutronPort.class), any(Action.class));
-
- neutronL3Adapter.handleInterfaceEvent(node, intf, mock(NeutronNetwork.class), Action.UPDATE);
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("getDpidForIntegrationBridge", any(Node.class));
- Mockito.verify(neutronL3Adapter).handleNeutronPortEvent(neutronPort, Action.UPDATE);
-
- neutronL3Adapter.handleInterfaceEvent(node, intf, mock(NeutronNetwork.class), Action.DELETE);
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("handleInterfaceEventDelete", any(OvsdbTerminationPointAugmentation.class), anyLong());
- Mockito.verify(neutronL3Adapter).handleNeutronPortEvent(neutronPort, Action.DELETE);
- }
-
- @Test
- public void testHandleInterfaceEventAdd() throws Exception {
- Map<String, Pair<Long, Uuid>> neutronPortToDpIdCache = new HashMap<>();
- // init instance variables
- MemberModifier.field(NeutronL3Adapter.class, "neutronPortToDpIdCache").set(neutronL3Adapter , neutronPortToDpIdCache);
- int temp = neutronPortToDpIdCache.size();
-
- Whitebox.invokeMethod(neutronL3Adapter, "handleInterfaceEventAdd", "", 5L, mock(Uuid.class));
-
- assertEquals("Error, did not add the port", temp+1, neutronPortToDpIdCache.size());
- }
-
- @SuppressWarnings("unchecked")
- @Test
- public void testHandleInterfaceEventDelete() throws Exception {
- Map<String, Pair<Long, Uuid>> neutronPortToDpIdCache = new HashMap<>();
- OvsdbTerminationPointAugmentation intf = mock(OvsdbTerminationPointAugmentation.class);
- Uuid uuid = mock(Uuid.class);
- when(intf.getInterfaceUuid()).thenReturn(uuid );
- Pair<Long, Uuid> pair = mock(Pair.class);
- when(pair.getRight()).thenReturn(uuid);
-
- // init instance variables
- neutronPortToDpIdCache.put("key", pair);
- MemberModifier.field(NeutronL3Adapter.class, "neutronPortToDpIdCache").set(neutronL3Adapter , neutronPortToDpIdCache);
- int temp = neutronPortToDpIdCache.size();
-
- Whitebox.invokeMethod(neutronL3Adapter, "handleInterfaceEventDelete", intf, Long.valueOf(ID));
-
- assertEquals("Error, did not remove the port", temp-1, neutronPortToDpIdCache.size());
- }
-
- @Test
- public void testUpdateL3ForNeutronPort() throws Exception {
- Map<String, String> networkIdToRouterMacCache = new HashMap<>();
-
- Neutron_IPs neutronIp = mock(Neutron_IPs.class);
- when(neutronIp.getIpAddress()).thenReturn(FIXED_IP_ADDRESS);
- List<Neutron_IPs> neutronIps = new ArrayList<>();
- neutronIps.add(neutronIp);
- NeutronPort neutronPort = mock(NeutronPort.class);
- when(neutronPort.getNetworkUUID()).thenReturn(UUID);
- when(neutronPort.getMacAddress()).thenReturn(MAC_ADDRESS_2);
- when(neutronPort.getFixedIPs()).thenReturn(neutronIps);
- NeutronNetwork neutronNetwork = mock(NeutronNetwork.class);
- when(neutronNetwork.getProviderSegmentationID()).thenReturn(ID);
- List<Node> nodes = new ArrayList<>();
- nodes.add(mock(Node.class));
- TenantNetworkManager tenantNetworkManager = mock(TenantNetworkManager.class);
- MemberModifier.field(NeutronL3Adapter.class, "tenantNetworkManager").set(neutronL3Adapter , tenantNetworkManager);
- when(tenantNetworkManager.isTenantNetworkPresentInNode(any(Node.class), eq(ID))).thenReturn(true);
- PowerMockito.doReturn(15L).when(neutronL3Adapter, "getDpidForIntegrationBridge", any(Node.class));
-
- // init instance variables
- networkIdToRouterMacCache .put(UUID, MAC_ADDRESS);
- MemberModifier.field(NeutronL3Adapter.class, "networkIdToRouterMacCache").set(neutronL3Adapter , networkIdToRouterMacCache);
- INeutronNetworkCRUD neutronNetworkCache = mock(INeutronNetworkCRUD.class);
- when(neutronNetworkCache.getNetwork(anyString())).thenReturn(neutronNetwork);
- MemberModifier.field(NeutronL3Adapter.class, "neutronNetworkCache").set(neutronL3Adapter , neutronNetworkCache);
- NodeCacheManager nodeCacheManager = mock(NodeCacheManager.class);
- when(nodeCacheManager.getBridgeNodes()).thenReturn(nodes);
- MemberModifier.field(NeutronL3Adapter.class, "nodeCacheManager").set(neutronL3Adapter , nodeCacheManager);
-
- // Suppress the called to these functions
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "getDpidForIntegrationBridge", Node.class));
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "programL3ForwardingStage1", Node.class, Long.class, String.class, String.class, String.class, Action.class));
-
- Whitebox.invokeMethod(neutronL3Adapter, "updateL3ForNeutronPort", neutronPort, false);
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("getDpidForIntegrationBridge", any(Node.class));
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("programL3ForwardingStage1", any(Node.class), anyLong(), anyString(), anyString(), anyString(), eq(Action.ADD));
-
- Whitebox.invokeMethod(neutronL3Adapter, "updateL3ForNeutronPort", neutronPort, true);
- PowerMockito.verifyPrivate(neutronL3Adapter, times(2)).invoke("getDpidForIntegrationBridge", any(Node.class));
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("programL3ForwardingStage1", any(Node.class), anyLong(), anyString(), anyString(), anyString(), eq(Action.DELETE));
- }
-
- @Test
- public void testProgramL3ForwardingStage1() throws Exception {
-
- NodeId nodeId = mock(NodeId.class);
- when(nodeId.getValue()).thenReturn(ID);
- Node node = mock(Node.class);
- when(node.getNodeId()).thenReturn(nodeId);
-
- // Suppress the called to these functions
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "programL3ForwardingStage2", Node.class, Long.class, String.class, String.class, String.class, Action.class));
-
- // init instance variables
- PowerMockito.when(neutronL3Adapter, "programL3ForwardingStage2", any(Node.class), anyLong(), anyString(), anyString(), anyString(), eq(Action.ADD)).thenReturn(new Status(StatusCode.SUCCESS));
- PowerMockito.when(neutronL3Adapter, "programL3ForwardingStage2", any(Node.class), anyLong(), anyString(), anyString(), anyString(), eq(Action.DELETE)).thenReturn(new Status(StatusCode.SUCCESS));
-
-
- Whitebox.invokeMethod(neutronL3Adapter, "programL3ForwardingStage1", node, 45L, SEG_ID, MAC_ADDRESS, IP, Action.ADD);
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("programL3ForwardingStage2", any(Node.class), anyLong(), anyString(), anyString(), anyString(), eq(Action.ADD));
-
-
- Whitebox.invokeMethod(neutronL3Adapter, "programL3ForwardingStage1", node, 45L, SEG_ID, MAC_ADDRESS, IP, Action.DELETE);
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("programL3ForwardingStage2", any(Node.class), anyLong(), anyString(), anyString(), anyString(), eq(Action.DELETE));
- }
-
- @Test
- public void testProgramL3ForwardingStage2() throws Exception {
- NodeId nodeId = mock(NodeId.class);
- when(nodeId.getValue()).thenReturn(ID);
- Node node = mock(Node.class);
- when(node.getNodeId()).thenReturn(nodeId);
-
- assertEquals("Error, this not return the correct status code", new Status(StatusCode.BADREQUEST), Whitebox.invokeMethod(neutronL3Adapter, "programL3ForwardingStage2", node,
- 45L, SEG_ID, MAC_ADDRESS, MALFORM_IP, Action.ADD));
-
- PowerMockito.mockStatic(InetAddress.class);
- InetAddress inetAddress = mock(InetAddress.class);
- PowerMockito.when(InetAddress.getByName(anyString())).thenReturn(inetAddress);
-
- assertEquals("Error, this not return the correct status code", new Status(StatusCode.SUCCESS), Whitebox.invokeMethod(neutronL3Adapter, "programL3ForwardingStage2", node,
- 45L, SEG_ID, MAC_ADDRESS, IP, Action.ADD));
- }
-
- @Test
- public void testProgramFlowsForNeutronRouterInterface() throws Exception {
- Map<String, String> networkIdToRouterMacCache = new HashMap<>();
- Map<String, List<Neutron_IPs>> networkIdToRouterIpListCache = new HashMap<>();
- Map<String, NeutronRouter_Interface> subnetIdToRouterInterfaceCache = new HashMap<>();
-
- NeutronRouter_Interface intf = mock(NeutronRouter_Interface.class);
- when(intf.getPortUUID()).thenReturn(UUID);
- when(intf.getSubnetUUID()).thenReturn(UUID);
- Neutron_IPs neutronIp = mock(Neutron_IPs.class);
- when(neutronIp.getIpAddress()).thenReturn(FIXED_IP_ADDRESS);
- List<Neutron_IPs> ips = new ArrayList<>();
- ips.add(neutronIp);
- NeutronPort neutronPort = mock(NeutronPort.class);
- when(neutronPort.getMacAddress()).thenReturn(MAC_ADDRESS);
- when(neutronPort.getFixedIPs()).thenReturn(ips);
- when(neutronPort.getNetworkUUID()).thenReturn(UUID);
- NeutronSubnet neutronSubnet = mock(NeutronSubnet.class);
- when(neutronSubnet.getNetworkUUID()).thenReturn(UUID);
- when(neutronSubnet.getGatewayIP()).thenReturn(IP);
- when(neutronSubnet.getCidr()).thenReturn("cidr");
- NeutronNetwork neutronNetwork = mock(NeutronNetwork.class);
- when(neutronNetwork.getProviderSegmentationID()).thenReturn(ID);
- when(neutronNetwork.getRouterExternal()).thenReturn(false); //might change that to true
- when(neutronNetwork.getNetworkUUID()).thenReturn(UUID);
- NeutronRouter neutronRouter = mock(NeutronRouter.class);
-
- Node node = mock(Node.class);
- List<Node> nodes = new ArrayList<>();
- nodes.add(node);
-
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "getDpidForIntegrationBridge", Node.class));
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "programFlowsForNeutronRouterInterfacePair", Node.class, Long.class, NeutronRouter_Interface.class, NeutronRouter_Interface.class, NeutronNetwork.class, String.class, String.class, String.class, int.class, Action.class, Boolean.class));
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "programFlowForNetworkFromExternal", Node.class, Long.class, String.class, String.class, String.class, int.class, Action.class));
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "programIpRewriteExclusionStage1", Node.class, Long.class, String.class, String.class, Action.class));
-
- // init instance variables
- INeutronPortCRUD neutronPortCache = mock(INeutronPortCRUD.class);
- PowerMockito.when(neutronPortCache.getPort(anyString())).thenReturn(neutronPort);
- PowerMockito.when(neutronPortCache.getAllPorts()).thenReturn(new ArrayList<>());
- INeutronSubnetCRUD neutronSubnetCache = mock(INeutronSubnetCRUD.class);
- PowerMockito.when(neutronSubnetCache.getSubnet(anyString())).thenReturn(neutronSubnet);
- INeutronNetworkCRUD neutronNetworkCache = mock(INeutronNetworkCRUD.class);
- PowerMockito.when(neutronNetworkCache.getNetwork(anyString())).thenReturn(neutronNetwork);
- NodeCacheManager nodeCacheManager = mock(NodeCacheManager.class);
- PowerMockito.when(nodeCacheManager.getBridgeNodes()).thenReturn(nodes);
- MemberModifier.field(NeutronL3Adapter.class, "networkIdToRouterMacCache").set(neutronL3Adapter , networkIdToRouterMacCache);
- MemberModifier.field(NeutronL3Adapter.class, "networkIdToRouterIpListCache").set(neutronL3Adapter , networkIdToRouterIpListCache);
- MemberModifier.field(NeutronL3Adapter.class, "subnetIdToRouterInterfaceCache").set(neutronL3Adapter , subnetIdToRouterInterfaceCache);
- MemberModifier.field(NeutronL3Adapter.class, "neutronPortCache").set(neutronL3Adapter , neutronPortCache);
- MemberModifier.field(NeutronL3Adapter.class, "neutronSubnetCache").set(neutronL3Adapter , neutronSubnetCache);
- MemberModifier.field(NeutronL3Adapter.class, "neutronNetworkCache").set(neutronL3Adapter , neutronNetworkCache);
- MemberModifier.field(NeutronL3Adapter.class, "nodeCacheManager").set(neutronL3Adapter , nodeCacheManager);
- PowerMockito.when(neutronL3Adapter, "getDpidForIntegrationBridge", any(Node.class)).thenReturn(45L);
-
- int networkIdToRouterMacCacheSize, networkIdToRouterIpListCacheSize, subnetIdToRouterInterfaceCacheSize;
- networkIdToRouterMacCacheSize = networkIdToRouterMacCache.size();
- networkIdToRouterIpListCacheSize = networkIdToRouterIpListCache.size();
- subnetIdToRouterInterfaceCacheSize = subnetIdToRouterInterfaceCache.size();
-
- Whitebox.invokeMethod(neutronL3Adapter, "programFlowsForNeutronRouterInterface", intf, false);
-
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("getDpidForIntegrationBridge", any(Node.class));
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("programFlowsForNeutronRouterInterfacePair", any(Node.class), anyLong(), any(NeutronRouter_Interface.class), any(NeutronRouter_Interface.class), any(NeutronNetwork.class), anyString(), anyString(), anyString(), anyInt(), eq(Action.ADD), anyBoolean());
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("programFlowForNetworkFromExternal", any(Node.class), anyLong(), anyString(), anyString(), anyString(), anyInt(), eq(Action.ADD));
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("programIpRewriteExclusionStage1", any(Node.class), anyLong(), anyString(), anyString(), eq(Action.ADD));
- assertEquals("Error, did not add the RouterMac", networkIdToRouterMacCacheSize, networkIdToRouterMacCache.size() -1);
- assertEquals("Error, did not add the RouterIP", networkIdToRouterIpListCacheSize, networkIdToRouterIpListCache.size() -1);
- assertEquals("Error, did not add the RouterInterface", subnetIdToRouterInterfaceCacheSize, subnetIdToRouterInterfaceCache.size() -1);
-
- networkIdToRouterMacCache.put(UUID, MAC_ADDRESS);
- networkIdToRouterIpListCache.put(UUID, ips);
- subnetIdToRouterInterfaceCache.put(UUID, intf);
- networkIdToRouterMacCacheSize = networkIdToRouterMacCache.size();
- networkIdToRouterIpListCacheSize = networkIdToRouterIpListCache.size();
- subnetIdToRouterInterfaceCacheSize = subnetIdToRouterInterfaceCache.size();
-
- Whitebox.invokeMethod(neutronL3Adapter, "handleNeutronRouterInterfaceEvent", neutronRouter, intf, Action.DELETE);
-
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("programFlowsForNeutronRouterInterface", intf, true);
- PowerMockito.verifyPrivate(neutronL3Adapter, times(2)).invoke("getDpidForIntegrationBridge", any(Node.class));
- PowerMockito.verifyPrivate(neutronL3Adapter, times(2)).invoke("programFlowsForNeutronRouterInterfacePair", any(Node.class), anyLong(), any(NeutronRouter_Interface.class), any(NeutronRouter_Interface.class), any(NeutronNetwork.class), anyString(), anyString(), anyString(), anyInt(), eq(Action.DELETE), anyBoolean());
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("programFlowForNetworkFromExternal", any(Node.class), anyLong(), anyString(), anyString(), anyString(), anyInt(), eq(Action.DELETE));
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("programIpRewriteExclusionStage1", any(Node.class), anyLong(), anyString(), anyString(), eq(Action.DELETE));
- assertEquals("Error, did not remove the RouterMac", networkIdToRouterMacCacheSize, networkIdToRouterMacCache.size() +1);
- assertEquals("Error, did not remove the RouterIP", networkIdToRouterIpListCacheSize, networkIdToRouterIpListCache.size() +1);
- assertEquals("Error, did not remove the RouterInterface", subnetIdToRouterInterfaceCacheSize, subnetIdToRouterInterfaceCache.size() +1);
- }
-
- @Test
- public void testProgramFlowForNetworkFromExternal() throws Exception {
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "programRouterInterfaceStage1", Node.class, Long.class, String.class, String.class, String.class, String.class, int.class, Action.class));
-
- Whitebox.invokeMethod(neutronL3Adapter, "programFlowForNetworkFromExternal", mock(Node.class), 12L, "", "", "", 4, Action.ADD);
-
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("programRouterInterfaceStage1", any(Node.class), anyLong(), anyString(), anyString(), anyString(), anyString(), anyInt(), any(Action.class));
- }
-
- @Test
- public void testProgramFlowsForNeutronRouterInterfacePair() throws Exception {
- NeutronRouter_Interface srcNeutronRouterInterface = mock(NeutronRouter_Interface.class);
- when(srcNeutronRouterInterface.getSubnetUUID()).thenReturn(UUID);
- when(srcNeutronRouterInterface.getID()).thenReturn(ID);
- when(srcNeutronRouterInterface.getPortUUID()).thenReturn(UUID);
- NeutronRouter_Interface dstNeutronRouterInterface = mock(NeutronRouter_Interface.class);
- NeutronNetwork neutronNetwork = mock(NeutronNetwork.class);
- when(neutronNetwork.getTenantID()).thenReturn(ID);
- when(neutronNetwork.getProviderSegmentationID()).thenReturn(ID);
- Neutron_IPs ip = mock(Neutron_IPs.class);
- when(ip.getIpAddress()).thenReturn(IP);
- List<Neutron_IPs> ips = new ArrayList<>();
- ips.add(ip);
- ips.add(ip);
- ips.add(ip);
- NeutronPort neutronPort = mock(NeutronPort.class);
- when(neutronPort.getMacAddress()).thenReturn(MAC_ADDRESS);
- when(neutronPort.getFixedIPs()).thenReturn(ips);
- NeutronSubnet neutronSubnet = mock(NeutronSubnet.class);
- when(neutronSubnet.getNetworkUUID()).thenReturn(UUID);
- when(neutronSubnet.getCidr()).thenReturn(CIDR);
-
- INeutronSubnetCRUD neutronSubnetCache = mock(INeutronSubnetCRUD.class);
- PowerMockito.when(neutronSubnetCache.getSubnet(anyString())).thenReturn(neutronSubnet);
- MemberModifier.field(NeutronL3Adapter.class, "neutronSubnetCache").set(neutronL3Adapter , neutronSubnetCache);
- INeutronNetworkCRUD neutronNetworkCache = mock(INeutronNetworkCRUD.class);
- PowerMockito.when(neutronNetworkCache.getNetwork(anyString())).thenReturn(neutronNetwork);
- MemberModifier.field(NeutronL3Adapter.class, "neutronNetworkCache").set(neutronL3Adapter , neutronNetworkCache);
- INeutronPortCRUD neutronPortCache = mock(INeutronPortCRUD.class);
- PowerMockito.when(neutronPortCache.getPort(anyString())).thenReturn(neutronPort);
- MemberModifier.field(NeutronL3Adapter.class, "neutronPortCache").set(neutronL3Adapter , neutronPortCache);
-
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "programRouterInterfaceStage1", Node.class, Long.class, String.class, String.class, String.class, String.class, int.class, Action.class));
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "getMaskLenFromCidr", String.class));
-
- Whitebox.invokeMethod(neutronL3Adapter, "programFlowsForNeutronRouterInterfacePair", mock(Node.class), 12L, srcNeutronRouterInterface, dstNeutronRouterInterface, neutronNetwork, SEG_ID, MAC_ADDRESS, IP, 4, Action.ADD, false);
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("programRouterInterfaceStage1", any(Node.class), anyLong(), anyString(), anyString(), anyString(), anyString(), anyInt(), any(Action.class));
-
- Whitebox.invokeMethod(neutronL3Adapter, "programFlowsForNeutronRouterInterfacePair", mock(Node.class), 12L, srcNeutronRouterInterface, dstNeutronRouterInterface, neutronNetwork, SEG_ID, MAC_ADDRESS, IP, 4, Action.ADD, true);
- PowerMockito.verifyPrivate(neutronL3Adapter, times(2)).invoke("programRouterInterfaceStage1", any(Node.class), anyLong(), anyString(), anyString(), anyString(), anyString(), anyInt(), any(Action.class));
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("getMaskLenFromCidr", anyString());
- PowerMockito.verifyPrivate(neutronL3Adapter, times(4)).invoke("programFlowsForNeutronRouterInterfacePair", any(Node.class), anyLong(), any(NeutronRouter_Interface.class), any(NeutronRouter_Interface.class), any(NeutronNetwork.class), anyString(), anyString(), anyString(), anyInt(), any(Action.class), eq(false)); //3 + 1 above
- }
-
- @Test
- public void testProgramRouterInterfaceStage1() throws Exception {
-
- NodeId nodeId = mock(NodeId.class);
- when(nodeId.getValue()).thenReturn(ID);
- Node node = mock(Node.class);
- when(node.getNodeId()).thenReturn(nodeId);
-
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "programRouterInterfaceStage2", Node.class, Long.class, String.class, String.class, String.class, String.class, int.class, Action.class));
-
- PowerMockito.when(neutronL3Adapter, "programRouterInterfaceStage2", any(Node.class), anyLong(), anyString(), anyString(), anyString(), anyString(), anyInt(), any(Action.class)).thenReturn(new Status(StatusCode.SUCCESS));
-
-
- Whitebox.invokeMethod(neutronL3Adapter, "programRouterInterfaceStage1", node, 12L, SEG_ID, SEG_ID, MAC_ADDRESS, IP, 4, Action.ADD);
-
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("programRouterInterfaceStage1", any(Node.class), anyLong(), anyString(), anyString(), anyString(), anyString(), anyInt(), eq(Action.ADD));
-
- Whitebox.invokeMethod(neutronL3Adapter, "programRouterInterfaceStage1", node, 12L, SEG_ID, SEG_ID, MAC_ADDRESS, IP, 4, Action.DELETE);
-
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("programRouterInterfaceStage1", any(Node.class), anyLong(), anyString(), anyString(), anyString(), anyString(), anyInt(), eq(Action.DELETE));
- }
-
- @Test
- public void testProgramRouterInterfaceStage2() throws Exception {
- NodeId nodeId = mock(NodeId.class);
- when(nodeId.getValue()).thenReturn(ID);
- Node node = mock(Node.class);
- when(node.getNodeId()).thenReturn(nodeId);
-
- assertEquals("Error, this not return the correct status code", new Status(StatusCode.BADREQUEST), Whitebox.invokeMethod(neutronL3Adapter, "programRouterInterfaceStage2", node,
- 45L, SEG_ID, SEG_ID , MAC_ADDRESS, MALFORM_IP, 4, Action.ADD));
-
- PowerMockito.mockStatic(InetAddress.class);
- InetAddress inetAddress = mock(InetAddress.class);
- PowerMockito.when(InetAddress.getByName(anyString())).thenReturn(inetAddress);
-
- assertEquals("Error, this not return the correct status code", new Status(StatusCode.SUCCESS), Whitebox.invokeMethod(neutronL3Adapter, "programRouterInterfaceStage2", node,
- 45L, SEG_ID, SEG_ID, MAC_ADDRESS, IP, 4, Action.ADD));
-
- }
-
- @Test
- public void testProgramInboundIpRewriteStage1() throws Exception {
-
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "programInboundIpRewriteStage2", Long.class, Long.class, String.class, String.class, String.class, Action.class));
-
- PowerMockito.when(neutronL3Adapter, "programInboundIpRewriteStage2", anyLong(), anyLong(), anyString(), anyString(), anyString(), any(Action.class)).thenReturn(new Status(StatusCode.SUCCESS));
-
-
- Whitebox.invokeMethod(neutronL3Adapter, "programInboundIpRewriteStage1", 12L, 12L, PORT_INT, MAC_ADDRESS, IP, Action.ADD);
-
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("programInboundIpRewriteStage2", anyLong(), anyLong(), anyString(), anyString(), anyString(), eq(Action.ADD));
-
- Whitebox.invokeMethod(neutronL3Adapter, "programInboundIpRewriteStage1", 12L, 12L,PORT_INT, MAC_ADDRESS, IP, Action.DELETE);
-
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("programInboundIpRewriteStage2", anyLong(), anyLong(), anyString(), anyString(), anyString(), eq(Action.DELETE));
- }
-
- @Test
- public void testProgramInboundIpRewriteStage2() throws Exception {
- assertEquals("Error, this not return the correct status code", new Status(StatusCode.BADREQUEST), Whitebox.invokeMethod(neutronL3Adapter, "programInboundIpRewriteStage2",
- 45L, 45L, SEG_ID, MAC_ADDRESS, IP, Action.ADD));
-
- PowerMockito.mockStatic(InetAddress.class);
- InetAddress inetAddress = mock(InetAddress.class);
- PowerMockito.when(InetAddress.getByName(anyString())).thenReturn(inetAddress);
-
- assertEquals("Error, this not return the correct status code", new Status(StatusCode.SUCCESS), Whitebox.invokeMethod(neutronL3Adapter, "programInboundIpRewriteStage2",
- 45L, 45L, SEG_ID, MAC_ADDRESS, IP, Action.ADD));
- }
-
- @Test
- public void testProgramIpRewriteExclusionStage1() throws Exception {
-
- NodeId nodeId = mock(NodeId.class);
- when(nodeId.getValue()).thenReturn(ID);
- Node node = mock(Node.class);
- when(node.getNodeId()).thenReturn(nodeId);
-
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "programIpRewriteExclusionStage2", Node.class, Long.class, String.class, String.class, Action.class));
-
- PowerMockito.when(neutronL3Adapter, "programIpRewriteExclusionStage2", any(Node.class), anyLong(), anyString(), anyString(), any(Action.class)).thenReturn(new Status(StatusCode.SUCCESS));
-
-
- Whitebox.invokeMethod(neutronL3Adapter, "programIpRewriteExclusionStage1", node, 12L, SEG_ID, CIDR, Action.ADD);
-
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("programIpRewriteExclusionStage2", any(Node.class), anyLong(), anyString(), anyString(), eq(Action.ADD));
-
- Whitebox.invokeMethod(neutronL3Adapter, "programIpRewriteExclusionStage1", node, 12L, SEG_ID, CIDR, Action.DELETE);
-
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("programIpRewriteExclusionStage2", any(Node.class), anyLong(), anyString(), anyString(), eq(Action.DELETE));
- }
-
- @Test
- public void testProgramIpRewriteExclusionStage2() throws Exception {
- NodeId nodeId = mock(NodeId.class);
- when(nodeId.getValue()).thenReturn(ID);
- Node node = mock(Node.class);
- when(node.getNodeId()).thenReturn(nodeId);
-
- assertEquals("Error, this not return the correct status code", new Status(StatusCode.SUCCESS), Whitebox.invokeMethod(neutronL3Adapter, "programIpRewriteExclusionStage2", node,
- 45L, SEG_ID, CIDR, Action.ADD));
- }
-
- @SuppressWarnings("unchecked")
- @Test
- public void testProgramOutboundIpRewriteStage1() throws Exception{
-
- MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "programOutboundIpRewriteStage2", floatingIpClass, Action.class));
-
- PowerMockito.when(neutronL3Adapter, "programOutboundIpRewriteStage2", any(floatingIpClass), any(Action.class)).thenReturn(new Status(StatusCode.SUCCESS));
-
-
- Whitebox.invokeMethod(neutronL3Adapter, "programOutboundIpRewriteStage1", floatingIpObject, Action.ADD);
-
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("programOutboundIpRewriteStage2", any(floatingIpClass), eq(Action.ADD));
-
- Whitebox.invokeMethod(neutronL3Adapter, "programOutboundIpRewriteStage1", floatingIpObject, Action.DELETE);
-
- PowerMockito.verifyPrivate(neutronL3Adapter, times(1)).invoke("programOutboundIpRewriteStage2", any(floatingIpClass), eq(Action.DELETE));
- }
-
- /*@Test
- public void testPrepareProgramOutboundIpRewriteStage2() throws Exception {
- assertEquals("Error, did not return the correct status code", new Status(StatusCode.BADREQUEST), Whitebox.invokeMethod(neutronL3Adapter, "programOutboundIpRewriteStage2", floatingIpObject, Action.ADD));
-
- PowerMockito.mockStatic(InetAddress.class);
- InetAddress inetAddress = mock(InetAddress.class);
- PowerMockito.when(InetAddress.getByName(anyString())).thenReturn(inetAddress);
-
- assertEquals("Error, did not return the correct status code", new Status(StatusCode.SUCCESS), Whitebox.invokeMethod(neutronL3Adapter, "programOutboundIpRewriteStage2", floatingIpObject, Action.ADD));
- }*/
-
- @Test
- public void testGetMaskLenFromCidr() throws Exception {
- assertEquals("Error, did not return the correct mask", 32, (int) Whitebox.invokeMethod(neutronL3Adapter, "getMaskLenFromCidr", IP_MASK));
- }
-
- @Test
- public void testGetDpidForIntegrationBridge() throws Exception {
- Southbound southbound = mock(Southbound.class);
- ConfigurationService configurationService = mock(ConfigurationService.class);
-
- MemberModifier.field(NeutronL3Adapter.class, "southbound").set(neutronL3Adapter , southbound);
- MemberModifier.field(NeutronL3Adapter.class, "configurationService").set(neutronL3Adapter , configurationService);
-
- PowerMockito.when(southbound.getBridge(any(Node.class), anyString())).thenReturn(mock(OvsdbBridgeAugmentation.class));
- PowerMockito.when(configurationService.getIntegrationBridgeName()).thenReturn("");
- PowerMockito.when(southbound.getDataPathId(any(Node.class))).thenReturn(45L);
-
- assertEquals("Error, did not return the correct Dpid", 45L, (long) Whitebox.invokeMethod(neutronL3Adapter, "getDpidForIntegrationBridge", mock(Node.class)));
- }
-
- @Test
- public void testencodeExcplicitOFPort() throws Exception {
- assertEquals("Error, did not correctly encode the port", OFPort, NeutronL3Adapter.encodeExcplicitOFPort(45L));
- }
-
- @Test
- public void testSetDependencies() throws Exception {
- ConcurrentMap<String,NeutronNetwork> networkCleanupCache = new ConcurrentHashMap<>();
- INeutronNetworkCRUD neutronNetworkCache = mock(INeutronNetworkCRUD.class);
- NeutronNetwork neutronNetwork = mock(NeutronNetwork.class);
- List <NeutronNetwork> neutronNetworkList = new ArrayList<>();
- neutronNetworkList.add(neutronNetwork);
- when(neutronNetworkCache.getAllNetworks()).thenReturn(neutronNetworkList);
-
- ConcurrentMap<String,NeutronPort> portCleanupCache = new ConcurrentHashMap<>();
- INeutronPortCRUD neutronPortCache = mock(INeutronPortCRUD.class);
- NeutronPort neutronPort = mock(NeutronPort.class);
- List <NeutronPort> neutronPortList = new ArrayList<>();
- neutronPortList.add(neutronPort);
- when(neutronPortCache.getAllPorts()).thenReturn(neutronPortList);
- // Mock variables
- MemberModifier.field(NeutronL3Adapter.class, "networkCleanupCache").set(neutronL3Adapter , networkCleanupCache);
- MemberModifier.field(NeutronL3Adapter.class, "neutronNetworkCache").set(neutronL3Adapter , neutronNetworkCache);
- MemberModifier.field(NeutronL3Adapter.class, "portCleanupCache").set(neutronL3Adapter , portCleanupCache);
- MemberModifier.field(NeutronL3Adapter.class, "neutronPortCache").set(neutronL3Adapter , neutronPortCache);
-
-
- when(neutronPort.getDeviceOwner()).thenReturn(OWNER_ROUTER_INTERFACE);
- MemberModifier.field(NeutronL3Adapter.class, "portCleanupCache").set(neutronL3Adapter , portCleanupCache);
-
-
-
- EventDispatcher eventDispatcher = mock(EventDispatcher.class);
- TenantNetworkManager tenantNetworkManager = mock(TenantNetworkManager.class);
- ConfigurationService configurationService = mock(ConfigurationService.class);
- ArpProvider arpProvider = mock(ArpProvider.class);
- DistributedArpService distributedArpService = mock(DistributedArpService.class);
- InboundNatProvider inboundNatProvider = mock(InboundNatProvider.class);
- OutboundNatProvider outboundNatProvider = mock(OutboundNatProvider.class);
- RoutingProvider routingProvider = mock(RoutingProvider.class);
- L3ForwardingProvider l3ForwardingProvider = mock(L3ForwardingProvider.class);
- NodeCacheManager nodeCacheManager = mock(NodeCacheManager.class);
- Southbound southbound = mock(Southbound.class);
-
- ServiceHelper.overrideGlobalInstance(EventDispatcher.class, eventDispatcher);
- ServiceHelper.overrideGlobalInstance(TenantNetworkManager.class, tenantNetworkManager);
- ServiceHelper.overrideGlobalInstance(ConfigurationService.class, configurationService);
- ServiceHelper.overrideGlobalInstance(ArpProvider.class, arpProvider);
- ServiceHelper.overrideGlobalInstance(DistributedArpService.class, distributedArpService);
- ServiceHelper.overrideGlobalInstance(InboundNatProvider.class, inboundNatProvider);
- ServiceHelper.overrideGlobalInstance(OutboundNatProvider.class, outboundNatProvider);
- ServiceHelper.overrideGlobalInstance(RoutingProvider.class, routingProvider);
- ServiceHelper.overrideGlobalInstance(L3ForwardingProvider.class, l3ForwardingProvider);
- ServiceHelper.overrideGlobalInstance(NodeCacheManager.class, nodeCacheManager);
- ServiceHelper.overrideGlobalInstance(Southbound.class, southbound);
-
- neutronL3Adapter.setDependencies(mock(ServiceReference.class));
-
- assertEquals("Error, did not return the correct object", getAbstractHandlerField("eventDispatcher"),
- eventDispatcher);
- assertEquals("Error, did not return the correct object", getField("tenantNetworkManager"), tenantNetworkManager);
- assertEquals("Error, did not return the correct object", getField("configurationService"), configurationService);
- assertEquals("Error, did not return the correct object", getField("arpProvider"), arpProvider);
- assertEquals("Error, did not return the correct object", getField("distributedArpService"), distributedArpService);
- assertEquals("Error, did not return the correct object", getField("inboundNatProvider"), inboundNatProvider);
- assertEquals("Error, did not return the correct object", getField("outboundNatProvider"), outboundNatProvider);
- assertEquals("Error, did not return the correct object", getField("routingProvider"), routingProvider);
- assertEquals("Error, did not return the correct object", getField("l3ForwardingProvider"), l3ForwardingProvider);
- assertEquals("Error, did not return the correct object", getField("nodeCacheManager"), nodeCacheManager);
- assertEquals("Error, did not return the correct object", getField("southbound"), southbound);
- }
-
- @Test
- public void testSetDependenciesObject() throws Exception{
- MemberModifier.field(NeutronL3Adapter.class, "enabled").set(neutronL3Adapter , false);
-
- INeutronNetworkCRUD iNeutronNetworkCRUD = mock(INeutronNetworkCRUD.class);
- neutronL3Adapter.setDependencies(iNeutronNetworkCRUD);
- assertEquals("Error, did not return the correct object", getField("neutronNetworkCache"), iNeutronNetworkCRUD);
-
- INeutronPortCRUD iNeutronPortCRUD = mock(INeutronPortCRUD.class);
- neutronL3Adapter.setDependencies(iNeutronPortCRUD);
- assertEquals("Error, did not return the correct object", getField("neutronPortCache"), iNeutronPortCRUD);
-
- INeutronSubnetCRUD iNeutronSubnetCRUD = mock(INeutronSubnetCRUD.class);
- neutronL3Adapter.setDependencies(iNeutronSubnetCRUD);
- assertEquals("Error, did not return the correct object", getField("neutronSubnetCache"), iNeutronSubnetCRUD);
-
- ArpProvider arpProvider = mock(ArpProvider.class);
- neutronL3Adapter.setDependencies(arpProvider);
- assertEquals("Error, did not return the correct object", getField("arpProvider"), arpProvider);
-
- InboundNatProvider inboundNatProvider = mock(InboundNatProvider.class);
- neutronL3Adapter.setDependencies(inboundNatProvider);
- assertEquals("Error, did not return the correct object", getField("inboundNatProvider"), inboundNatProvider);
-
- OutboundNatProvider outboundNatProvider = mock(OutboundNatProvider.class);
- neutronL3Adapter.setDependencies(outboundNatProvider);
- assertEquals("Error, did not return the correct object", getField("outboundNatProvider"), outboundNatProvider);
-
- RoutingProvider routingProvider = mock(RoutingProvider.class);
- neutronL3Adapter.setDependencies(routingProvider);
- assertEquals("Error, did not return the correct object", getField("routingProvider"), routingProvider);
-
- L3ForwardingProvider l3ForwardingProvider = mock(L3ForwardingProvider.class);
- neutronL3Adapter.setDependencies(l3ForwardingProvider);
- assertEquals("Error, did not return the correct object", getField("l3ForwardingProvider"), l3ForwardingProvider);
-
- MemberModifier.field(NeutronL3Adapter.class, "enabled").set(neutronL3Adapter , true);
- }
-
- private Object getAbstractHandlerField(String fieldName) throws Exception {
- Field field = AbstractHandler.class.getDeclaredField(fieldName);
- field.setAccessible(true);
- return field.get(neutronL3Adapter);
- }
-
- private Object getField(String fieldName) throws Exception {
- Field field = NeutronL3Adapter.class.getDeclaredField(fieldName);
- field.setAccessible(true);
- return field.get(neutronL3Adapter);
- }
-
- @SuppressWarnings("rawtypes")
- private Object createFloatingIpObject() throws Exception{
- Class clazz = Whitebox.getInnerClassType(NeutronL3Adapter.class, "FloatIpData");
- Constructor [] constructors = clazz.getConstructors();
- Constructor c = constructors[0];
- return c.newInstance(neutronL3Adapter, 415L, 415L, "a", "b", "c", "d", "e");
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2016 Inocybe 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.netvirt.openstack.netvirt.impl;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-import java.lang.reflect.Field;
-import java.util.HashMap;
-import java.util.Map;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.Spy;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.netvirt.openstack.netvirt.NodeCacheManagerEvent;
-import org.opendaylight.netvirt.openstack.netvirt.api.Action;
-import org.opendaylight.netvirt.openstack.netvirt.api.EventDispatcher;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheListener;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation;
-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.network.topology.topology.Node;
-import org.osgi.framework.ServiceReference;
-
-/**
- * Unit test for {@link NodeCacheManagerImpl}
- */
-@RunWith(MockitoJUnitRunner.class)
-public class NodeCacheManagerImplTest {
-
- @InjectMocks private NodeCacheManagerImpl nodeCacheManagerImpl;
- @Spy private Map<Long, NodeCacheListener> handlers = new HashMap<>();
-
- @Mock private Southbound southbound;
-
- @Test
- public void testProcessEvent() {
- NodeCacheManagerEvent ev = mock(NodeCacheManagerEvent.class);
- Node node = mock(Node.class);
- when(node.getNodeId()).thenReturn(mock(NodeId.class));
- when(ev.getNode()).thenReturn(node);
-
- when(ev.getAction()).thenReturn(Action.UPDATE);
- nodeCacheManagerImpl.processEvent(ev);
- assertEquals("Error, did not delete the event", 1, nodeCacheManagerImpl.getNodes().size());
-
- when(ev.getAction()).thenReturn(Action.DELETE);
- nodeCacheManagerImpl.processEvent(ev);
- assertEquals("Error, did not delete the event", 0, nodeCacheManagerImpl.getNodes().size());
- }
-
- @Test
- public void testCacheListenerAddedAndRemoved() {
- ServiceReference ref = mock(ServiceReference.class);
- when(ref.getProperty(org.osgi.framework.Constants.SERVICE_ID)).thenReturn(1L);
-
- // add
- nodeCacheManagerImpl.cacheListenerAdded(ref, mock(NodeCacheListener.class));
- assertEquals("Error, cacheListenerAdded() did not add any listener", 1, handlers.size());
- // remove
- nodeCacheManagerImpl.cacheListenerRemoved(ref);
- assertEquals("Error, cacheListenerAdded() did not remove any listener", 0, handlers.size());
- }
-
- @Test
- public void testGetOvsdbNodes() {
- addItem();
-
- when(southbound.extractOvsdbNode(any(Node.class))).thenReturn(mock(OvsdbNodeAugmentation.class));
-
- assertEquals("Error, getOvsdbNodes() did not return the correct value", 1, nodeCacheManagerImpl.getOvsdbNodes().size());
- }
-
- @Test
- public void testGetBridgeNodes() {
- addItem();
-
- when(southbound.getBridge(any(Node.class))).thenReturn(mock(OvsdbBridgeAugmentation.class));
-
- assertEquals("Error, getBridgeNodes() did not return the correct value", 1, nodeCacheManagerImpl.getBridgeNodes().size());
- }
-
- @Test
- public void testGetNodes() {
- addItem();
-
- assertEquals("Error, getNodes() did not return the correct value", 1, nodeCacheManagerImpl.getNodes().size());
- }
-
- private void addItem() {
- NodeCacheManagerEvent ev = mock(NodeCacheManagerEvent.class);
- Node node = mock(Node.class);
- when(node.getNodeId()).thenReturn(mock(NodeId.class));
- when(ev.getNode()).thenReturn(node);
-
- when(ev.getAction()).thenReturn(Action.UPDATE);
- nodeCacheManagerImpl.processEvent(ev);
- }
-
- @Test
- public void testSetDependencies() throws Exception {
- Southbound southbound = mock(Southbound.class);
- EventDispatcher eventDispatcher = mock(EventDispatcher.class);
-
- ServiceHelper.overrideGlobalInstance(Southbound.class, southbound);
- ServiceHelper.overrideGlobalInstance(EventDispatcher.class, eventDispatcher);
-
- nodeCacheManagerImpl.setDependencies(mock(ServiceReference.class));
-
- assertEquals("Error, did not return the correct object", getField("southbound"), southbound);
- assertEquals("Error, did not return the correct object", getSuperField("eventDispatcher"), eventDispatcher);
- }
-
- private Object getField(String fieldName) throws Exception {
- Field field = NodeCacheManagerImpl.class.getDeclaredField(fieldName);
- field.setAccessible(true);
- return field.get(nodeCacheManagerImpl);
- }
-
- private Object getSuperField(String fieldName) throws Exception {
- Field field = NodeCacheManagerImpl.class.getSuperclass().getDeclaredField(fieldName);
- field.setAccessible(true);
- return field.get(nodeCacheManagerImpl);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Inocybe 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.netvirt.openstack.netvirt.impl;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.mock;
-
-import java.util.Set;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.netvirt.openstack.netvirt.api.OvsdbInventoryListener;
-
-/**
- * Unit test for {@link NodeCacheManagerImpl}
- */
-@RunWith(MockitoJUnitRunner.class)
-public class OvsdbInventoryServiceImplTest {
-
- @InjectMocks private OvsdbInventoryServiceImpl ovsdbInventoryServiceImpl = new OvsdbInventoryServiceImpl(mock(DataBroker.class));
-
-
- @Test
- public void testListenerAdded() throws Exception{
- Set<OvsdbInventoryListener> listeners = OvsdbInventoryServiceImpl.getOvsdbInventoryListeners();
- OvsdbInventoryListener listener = mock(OvsdbInventoryListener.class);
-
- ovsdbInventoryServiceImpl.listenerAdded(listener);
- assertEquals("Error, did not add the listener", 1, listeners.size());
-
- ovsdbInventoryServiceImpl.listenerRemoved(listener);
- assertEquals("Error, did not delete the listener", 0, listeners.size());
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2016 Inocybe 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.netvirt.openstack.netvirt.impl;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-import java.lang.reflect.Field;
-import java.util.HashMap;
-import java.util.Map;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.Spy;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.netvirt.openstack.netvirt.api.NetworkingProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.OvsdbInventoryService;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-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.network.topology.topology.Node;
-import org.osgi.framework.ServiceReference;
-
-/**
- * Unit test for {@link ProviderNetworkManagerImpl}
- */
-@RunWith(MockitoJUnitRunner.class)
-public class ProviderNetworkManagerImplTest {
-
- @InjectMocks private ProviderNetworkManagerImpl providerNetworkManagerImpl;
-
- @Mock private OvsdbInventoryService ovsdbInventoryService;
-
- @Spy private Map<NodeId, NetworkingProvider> nodeToProviderMapping = new HashMap<>();
-
- /**
- * Test method {@link ProviderNetworkManagerImpl#getProvider(Node)}
- */
- @Test
- public void testGetProvider(){
- // TODO test the method with no networkingProvider in the map
- // Could not be done as ProviderEntry is a private inner class of ProviderNetworkManagerImpl
- Node node = mock(Node.class);
- NodeId nodeId = mock(NodeId.class);
- NetworkingProvider networkingProvider = mock(NetworkingProvider.class);
- when(node.getNodeId()).thenReturn(nodeId);
- nodeToProviderMapping.put(nodeId, networkingProvider);
- assertEquals("Error, did not return the networkingProvider of the specified node", networkingProvider, providerNetworkManagerImpl.getProvider(node));
- }
-
- /**
- * Test methods {@link ProviderNetworkManagerImpl#providerRemoved(ServiceReference)}
- * and {@link ProviderNetworkManagerImpl#providerAdded(ServiceReference, NetworkingProvider)}
- */
- @Test
- public void testProviderAddedAndRemoved() throws Exception {
- Map<?, ?> map = (HashMap<?, ?>) getField("providers");
-
- ServiceReference<?> ref = mock(ServiceReference.class);
- when(ref.getProperty(org.osgi.framework.Constants.SERVICE_ID)).thenReturn(1L);
-
- providerNetworkManagerImpl.providerAdded(ref, mock(NetworkingProvider.class));
-
- assertEquals("Error, providerAdded() did not add the provider", 1, map.size());
-
- providerNetworkManagerImpl.providerRemoved(ref);
-
- assertEquals("Error, providerRemoved() did not remove the provider", 0, map.size());
- }
-
- @Test
- public void testSetDependencies() throws Exception {
- OvsdbInventoryService ovsdbInventoryService = mock(OvsdbInventoryService.class);
-
- ServiceHelper.overrideGlobalInstance(OvsdbInventoryService.class, ovsdbInventoryService);
-
- providerNetworkManagerImpl.setDependencies(mock(ServiceReference.class));
-
- assertEquals("Error, did not return the correct object", getField("ovsdbInventoryService"), ovsdbInventoryService);
- }
-
- private Object getField(String fieldName) throws Exception {
- Field field = ProviderNetworkManagerImpl.class.getDeclaredField(fieldName);
- field.setAccessible(true);
- return field.get(providerNetworkManagerImpl);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2016 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.netvirt.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.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.netvirt.openstack.netvirt.api.SecurityServicesManager;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityGroup;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityRule;
-import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronPortCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSecurityGroupCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSecurityRuleCRUD;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
-
-/**
- * Unit test fort {@link SecurityGroupCacheManagerImpl}
- */
-@RunWith(MockitoJUnitRunner.class)
-public class SecurityGroupCacheManagerImplTest {
-
- @InjectMocks private SecurityGroupCacheManagerImpl securityGroupCacheManagerImpl;
- @Mock private INeutronPortCRUD neutronPortCache;
- @Mock private INeutronSecurityGroupCRUD securityGroupCache;
- @Mock private INeutronSecurityRuleCRUD neutronSecurityRuleCache;
- @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;
- @Mock NodeId nodeId_1;
- @Mock NeutronL3Adapter neutronL3Adapter;
- @Mock SecurityServicesImpl securityServicesImpl;
-
- 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 = new ArrayList<>();
- securityRule.add(neutronSecurityRule_1);
- securityRule.add(neutronSecurityRule_2);
- securityRule.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(neutronSecurityRuleCache.getAllNeutronSecurityRules()).thenReturn(securityRule);
- 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(neutronSecurityGroup_1.getID()).thenReturn(SECURITY_GROUP_ID_1);
- when(neutronSecurityGroup_2.getID()).thenReturn(SECURITY_GROUP_ID_2);
- when(neutronSecurityGroup_3.getID()).thenReturn(SECURITY_GROUP_ID_3);
- when(neutronSecurityRule_1.getSecurityRuleGroupID()).thenReturn(SECURITY_GROUP_ID_1);
- when(neutronSecurityRule_2.getSecurityRuleGroupID()).thenReturn(SECURITY_GROUP_ID_2);
- when(neutronSecurityRule_3.getSecurityRuleGroupID()).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);
- when(neutronL3Adapter.getPortPreferablyFromCleanupCache(NEUTRON_PORT_ID_VM_1)).thenReturn(neutronPort_Vm1);
- }
-
- /**
- * 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), any(NodeId.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, nodeId_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), any(NodeId.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, nodeId_1);
- securityGroupCacheManagerImpl.portAdded(SECURITY_GROUP_ID_1, NEUTRON_PORT_ID_VM_1);
- securityGroupCacheManagerImpl.addToCache(SECURITY_GROUP_ID_1, NEUTRON_PORT_ID_VM_2, nodeId_1);
- securityGroupCacheManagerImpl.portAdded(SECURITY_GROUP_ID_1, NEUTRON_PORT_ID_VM_2);
- securityServicesManager.syncSecurityRule(neutronPort_Vm1, neutronSecurityRule_1, neutron_ip_2, nodeId_1, true);
- verify(securityServicesManager, times(1)).syncSecurityRule(eq(neutronPort_Vm1), eq(neutronSecurityRule_1), eq(neutron_ip_2), eq(nodeId_1), 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, nodeId_1);
- securityGroupCacheManagerImpl.addToCache(SECURITY_GROUP_ID_1, NEUTRON_PORT_ID_VM_2, nodeId_1);
- securityGroupCacheManagerImpl.portRemoved(SECURITY_GROUP_ID_1, NEUTRON_PORT_ID_VM_2);
- securityServicesManager.syncSecurityRule(neutronPort_Vm1, neutronSecurityRule_1, neutron_ip_2, nodeId_1, false);
- verify(securityServicesManager, times(1)).syncSecurityRule(eq(neutronPort_Vm1), eq(neutronSecurityRule_1), eq(neutron_ip_2), eq(nodeId_1), 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, nodeId_1);
- securityGroupCacheManagerImpl.portAdded(SECURITY_GROUP_ID_2, NEUTRON_PORT_ID_VM_2);
- securityServicesManager.syncSecurityRule(neutronPort_Vm3, neutronSecurityRule_3, neutron_ip_2, nodeId_1, true);
- verify(securityServicesManager, times(1)).syncSecurityRule(eq(neutronPort_Vm3), eq(neutronSecurityRule_3), eq(neutron_ip_2), eq(nodeId_1), 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, nodeId_1);
- securityGroupCacheManagerImpl.portRemoved(SECURITY_GROUP_ID_2, NEUTRON_PORT_ID_VM_2);
- securityServicesManager.syncSecurityRule(neutronPort_Vm3, neutronSecurityRule_3, neutron_ip_2, nodeId_1, false);
- verify(securityServicesManager, times(1)).syncSecurityRule(eq(neutronPort_Vm3), eq(neutronSecurityRule_3), eq(neutron_ip_2), eq(nodeId_1), eq(false));
- }
-
- /**
- * A port is removed from the cache.
- */
- @Test
- public void testPortRemovedFromCache() {
- securityGroupCacheManagerImpl.addToCache(SECURITY_GROUP_ID_2, NEUTRON_PORT_ID_VM_3, nodeId_1);
- securityGroupCacheManagerImpl.removeFromCache(SECURITY_GROUP_ID_2, NEUTRON_PORT_ID_VM_3, nodeId_1);
- 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),any(NodeId.class), anyBoolean());
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2016 Inocybe 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.netvirt.openstack.netvirt.impl;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-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;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronNetworkCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.api.ConfigurationService;
-import org.opendaylight.netvirt.openstack.netvirt.api.EgressAclProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.IngressAclProvider;
-import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityGroup;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityRule;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSubnet;
-import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronPortCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSecurityRuleCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSubnetCRUD;
-import org.opendaylight.netvirt.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.NodeId;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology
- .Node;
-import org.osgi.framework.ServiceReference;
-
-/**
- * Unit test for {@link SecurityServicesImpl}
- */
-@RunWith(MockitoJUnitRunner.class)
-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 private INeutronSecurityRuleCRUD neutronSecurityRuleCache;
- @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 NeutronL3Adapter neutronL3Adapter;
- @Mock NodeId nodeId_1;
- @Mock NodeCacheManager nodeCacheManager;
- @Mock SecurityGroupCacheManagerImpl securityGroupCacheManagerImpl;
-
- 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(){
- 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 = new ArrayList<>();
- securityRule.add(neutronSecurityRule_1);
- securityRule.add(neutronSecurityRule_2);
- securityRule.add(neutronSecurityRule_3);
-
- neutron_IPs_1.add(neutron_ip_1);
- neutron_IPs_2.add(neutron_ip_2);
- neutron_IPs_3.add(neutron_ip_3);
-
- 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(neutronSecurityRuleCache.getAllNeutronSecurityRules()).thenReturn(securityRule);
- 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(neutronSecurityGroup_1.getID()).thenReturn(SECURITY_GROUP_ID_1);
- when(neutronSecurityGroup_2.getID()).thenReturn(SECURITY_GROUP_ID_2);
- when(neutronSecurityGroup_3.getID()).thenReturn(SECURITY_GROUP_ID_3);
- when(neutronSecurityRule_1.getSecurityRuleGroupID()).thenReturn(SECURITY_GROUP_ID_1);
- when(neutronSecurityRule_2.getSecurityRuleGroupID()).thenReturn(SECURITY_GROUP_ID_2);
- when(neutronSecurityRule_3.getSecurityRuleGroupID()).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);
-
- List<Node> nodeList = new ArrayList<>();
- nodeList.add(node);
- List<OvsdbTerminationPointAugmentation> tpList = new ArrayList<>();
- tpList.add(tp);
- when(nodeCacheManager.getNode(nodeId_1)).thenReturn(node);
- when(node.getNodeId()).thenReturn(nodeId_1);
- 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);
- when(neutronPort_Vm1.getMacAddress()).thenReturn("attached-mac");
- when(neutronL3Adapter.getPortPreferablyFromCleanupCache(NEUTRON_PORT_ID_VM_1)).thenReturn(neutronPort_Vm1);
- }
-
- /**
- * Test method {@link SecurityServicesImpl#isPortSecurityReady(OvsdbTerminationPointAugmentation)}
- */
- @Test
- public void testIsPortSecurityReady(){
- assertTrue("Error, did not return expected boolean for isPortSecurityReady", securityServicesImpl.isPortSecurityReady(mock(OvsdbTerminationPointAugmentation.class)));
- }
-
- /**
- * Test method {@link SecurityServicesImpl#getSecurityGroupInPortList(OvsdbTerminationPointAugmentation)}
- */
- @Test
- public void testSecurityGroupInPort(){
- assertEquals("Error, did not return the good neutronSecurityGroup of securityGroups",
- 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, neutronPort_Dhcp);
- }
-
- /**
- * 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<>());
- 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 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, null);
- }
-
- /**
- * 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, true);
- }
-
- /**
- * 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, neutron_IPs_1);
- }
-
-
- /**
- * 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() {
- Map<String,NeutronPort> portMap = new HashMap<>();
- portMap.put("Uuid1",neutronPort_Vm1);
- portMap.put("Uuid2",neutronPort_Vm2);
- portMap.put("Uuid3",neutronPort_Vm3);
- portMap.put("Uuid4",neutronPort_Dhcp);
- when(neutronL3Adapter.getPortCleanupCache()).thenReturn(portMap);
- 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);
- securityGroupCacheManagerImpl.portAdded(SECURITY_GROUP_ID_1, NEUTRON_PORT_ID_VM_1);
- 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(nodeId_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(nodeId_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);
- securityGroupCacheManagerImpl.portAdded(SECURITY_GROUP_ID_1, NEUTRON_PORT_ID_VM_1);
- when(node.getNodeId()).thenReturn(nodeId_1);
-
- 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(nodeId_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(nodeId_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(nodeId_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(nodeId_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(nodeId_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(nodeId_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(nodeId_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(nodeId_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(NeutronSecurityRule.DIRECTION_EGRESS);
- when(neutronSecurityRule_1.getSecurityRuleEthertype()).thenReturn(NeutronSecurityRule.ETHERTYPE_IPV4);
- when(nodeCacheManager.getNode(nodeId_1)).thenReturn(node);
- when(neutronPort_Vm1.getMacAddress()).thenReturn("attached-mac");
- securityServicesImpl.syncSecurityRule(neutronPort_Vm1, neutronSecurityRule_1, neutron_ip_1, nodeId_1, true);
- verify(egressAclService, times(1)).programPortSecurityRule(eq(new Long(1)), eq("1000"), eq("attached-mac"), 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(NeutronSecurityRule.DIRECTION_INGRESS);
- when(neutronSecurityRule_1.getSecurityRuleEthertype()).thenReturn(NeutronSecurityRule.ETHERTYPE_IPV4);
- securityServicesImpl.syncSecurityRule(neutronPort_Vm1, neutronSecurityRule_1, neutron_ip_1, nodeId_1, true);
- verify(ingressAclService, times(1)).programPortSecurityRule(eq(new Long(1)), eq("1000"), eq("attached-mac"), 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(NeutronSecurityRule.DIRECTION_EGRESS);
- when(neutronSecurityRule_1.getSecurityRuleEthertype()).thenReturn(NeutronSecurityRule.ETHERTYPE_IPV4);
- securityServicesImpl.syncSecurityRule(neutronPort_Vm1, neutronSecurityRule_1, neutron_ip_1, nodeId_1, false);
- verify(egressAclService, times(1)).programPortSecurityRule(eq(new Long(1)), eq("1000"), eq("attached-mac"), 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(NeutronSecurityRule.DIRECTION_INGRESS);
- when(neutronSecurityRule_1.getSecurityRuleEthertype()).thenReturn(NeutronSecurityRule.ETHERTYPE_IPV4);
- securityServicesImpl.syncSecurityRule(neutronPort_Vm1, neutronSecurityRule_1, neutron_ip_1, nodeId_1, false);
- verify(ingressAclService, times(1)).programPortSecurityRule(eq(new Long(1)), eq("1000"), eq("attached-mac"), 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(NeutronSecurityRule.DIRECTION_INGRESS);
- when(neutronSecurityRule_1.getSecurityRuleEthertype()).thenReturn(NeutronSecurityRule.ETHERTYPE_IPV4);
- securityServicesImpl.syncSecurityRule(null, neutronSecurityRule_1, neutron_ip_1, nodeId_1, false);
- verify(ingressAclService, times(0)).programPortSecurityRule(eq(new Long(1)), eq("1000"), eq("attached-mac"), 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(NeutronSecurityRule.DIRECTION_INGRESS);
- when(neutronSecurityRule_1.getSecurityRuleEthertype()).thenReturn(NeutronSecurityRule.ETHERTYPE_IPV4);
- securityServicesImpl.syncSecurityRule(neutronPort_Vm1, neutronSecurityRule_1, neutron_ip_1, nodeId_1, false);
- verify(ingressAclService, times(0)).programPortSecurityRule(eq(new Long(1)), eq("1000"), eq("attached-mac"), 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(NeutronSecurityRule.DIRECTION_INGRESS);
- when(neutronSecurityRule_1.getSecurityRuleEthertype()).thenReturn(NeutronSecurityRule.ETHERTYPE_IPV4);
- when(southbound.getInterfaceExternalIdsValue(any(OvsdbTerminationPointAugmentation.class),eq("attached-mac"))).thenReturn(null);
- securityServicesImpl.syncSecurityRule(neutronPort_Vm1, neutronSecurityRule_1, neutron_ip_1, nodeId_1, false);
- verify(ingressAclService, times(1)).programPortSecurityRule(eq(new Long(1)), eq("1000"), eq("attached-mac"), 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(NeutronSecurityRule.DIRECTION_INGRESS);
- when(neutronSecurityRule_1.getSecurityRuleEthertype()).thenReturn(NeutronSecurityRule.ETHERTYPE_IPV6);
- securityServicesImpl.syncSecurityRule(neutronPort_Vm1, neutronSecurityRule_1, neutron_ip_1, nodeId_1, false);
- verify(ingressAclService, times(0)).programPortSecurityRule(eq(new Long(1)), eq("1000"), eq("attached-mac"), 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(NeutronSecurityRule.ETHERTYPE_IPV4);
- securityServicesImpl.syncSecurityRule(neutronPort_Vm1, neutronSecurityRule_1, neutron_ip_1, nodeId_1, false);
- verify(ingressAclService, times(0)).programPortSecurityRule(eq(new Long(1)), eq("1000"), eq("attached-mac"), eq(neutronSecurityRule_1), eq(neutron_ip_1), eq(false));
- }
-
- @Test
- public void testSetDependencies() throws Exception {
- Southbound southbound = mock(Southbound.class);
-
- ServiceHelper.overrideGlobalInstance(Southbound.class, southbound);
-
- securityServicesImpl.setDependencies(mock(ServiceReference.class));
-
- assertEquals("Error, did not return the correct object", getField("southbound"), southbound);
- }
-
- @Test
- public void testSetDependenciesObject() throws Exception{
- INeutronPortCRUD neutronPortCache = mock(INeutronPortCRUD.class);
- securityServicesImpl.setDependencies(neutronPortCache);
- assertEquals("Error, did not return the correct object", getField("neutronPortCache"), neutronPortCache);
- }
-
- private Object getField(String fieldName) throws Exception {
- Field field = SecurityServicesImpl.class.getDeclaredField(fieldName);
- field.setAccessible(true);
- return field.get(securityServicesImpl);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2016 Inocybe 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.netvirt.openstack.netvirt.impl;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-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;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronNetworkCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.api.NetworkingProviderManager;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.openstack.netvirt.api.VlanConfigurationCache;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronPortCRUD;
-import org.opendaylight.netvirt.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.osgi.framework.ServiceReference;
-
-/**
- * Unit test for {@link TenantNetworkManagerImpl}
- */
-@RunWith(MockitoJUnitRunner.class)
-public class TenantNetworkManagerImplTest {
-
- @InjectMocks private TenantNetworkManagerImpl tenantNetworkManagerImpl;
-
- @Mock private INeutronPortCRUD neutronPortCache;
- @Mock private INeutronNetworkCRUD neutronNetworkCache;
- @Mock private VlanConfigurationCache vlanConfigurationCache;
- @Mock private NeutronL3Adapter neutronL3Adapter;
- @Mock private NetworkingProviderManager networkingProviderManager;
- @Mock private Southbound southbound;
-
- private static final String NETWORK_ID= "networkId";
- private static final String SEG_ID = "segId";
- private static final String INTERFACE_ID = "intId";
- /**
- * Test method {@link TenantNetworkManagerImpl#getInternalVlan(Node, String)}
- */
- @Test
- public void testGetInternalVlan() {
- when(vlanConfigurationCache.getInternalVlan(any(Node.class), eq(NETWORK_ID))).thenReturn(10);
-
- assertEquals("Error, did not return the correct internalVlan" , 10, tenantNetworkManagerImpl.getInternalVlan(mock(Node.class), NETWORK_ID));
- assertEquals("Error, did not return the correct internalVlan", 0, tenantNetworkManagerImpl.getInternalVlan(mock(Node.class), "unexistingNetwork"));
-
- verify(vlanConfigurationCache, times(2)).getInternalVlan(any(Node.class), anyString());
- }
-
- /**
- * Test method {@link TenantNetworkManagerImpl#reclaimInternalVlan(Node, NeutronNetwork)}
- */
- @Test
- public void testReclaimInternalVlan() {
- when(vlanConfigurationCache.reclaimInternalVlan(any(Node.class), eq(NETWORK_ID))).thenReturn(10);
-
- tenantNetworkManagerImpl.reclaimInternalVlan(mock(Node.class), mock(NeutronNetwork.class));
- tenantNetworkManagerImpl.reclaimInternalVlan(mock(Node.class), mock(NeutronNetwork.class));
-
- verify(vlanConfigurationCache, times(2)).reclaimInternalVlan(any(Node.class), anyString());
- }
-
- /**
- * Test method {@link TenantNetworkManagerImpl#programInternalVlan(Node, OvsdbTerminationPointAugmentation, NeutronNetwork)}
- */
- @Test
- public void testProgramInternalVlan(){
- when(vlanConfigurationCache.getInternalVlan(any(Node.class), anyString())).thenReturn(10);
-
- tenantNetworkManagerImpl.programInternalVlan(mock(Node.class), mock(OvsdbTerminationPointAugmentation.class), mock(NeutronNetwork.class));
-
- verify(vlanConfigurationCache, times(1)).getInternalVlan(any(Node.class), anyString());
- }
-
- /**
- * Test method {@link TenantNetworkManagerImpl#isTenantNetworkPresentInNode(Node, String)}
- */
- @Test
- public void testIsTenantNetworkPresentInNode() {
- NeutronNetwork neutronNetwork = mock(NeutronNetwork.class);
- when(neutronNetwork.getProviderSegmentationID()).thenReturn(SEG_ID);
- when(neutronNetwork.getNetworkUUID()).thenReturn(NETWORK_ID);
- List<NeutronNetwork> listNeutronNetwork = new ArrayList<>();
- listNeutronNetwork.add(neutronNetwork);
- when(neutronNetworkCache.getAllNetworks()).thenReturn(listNeutronNetwork);
-
- when(southbound.getInterfaceExternalIdsValue(any(OvsdbTerminationPointAugmentation.class), anyString())).thenReturn(INTERFACE_ID);
- NeutronPort neutronPort = mock(NeutronPort.class);
- when(neutronPort.getNetworkUUID()).thenReturn(NETWORK_ID);
- when(neutronL3Adapter.getPortPreferablyFromCleanupCache(anyString())).thenReturn(neutronPort);
-
- List<OvsdbTerminationPointAugmentation> ports = new ArrayList<>();
- ports.add(mock(OvsdbTerminationPointAugmentation.class));
- when(southbound.readTerminationPointAugmentations(any(Node.class))).thenReturn(ports);
-
- assertTrue("Error, did not return correct boolean for isTenantNetworkPresentInNode", tenantNetworkManagerImpl.isTenantNetworkPresentInNode(mock(Node.class), SEG_ID));
- }
-
- /**
- * Test method {@link TenantNetworkManagerImpl#getNetworkId(String)}
- */
- @Test
- public void testGetNetworkId() {
- NeutronNetwork neutronNetwork = mock(NeutronNetwork.class);
- List<NeutronNetwork> listNeutronNetwork = new ArrayList<>();
- listNeutronNetwork.add(neutronNetwork);
-
- when(neutronNetwork.getProviderSegmentationID()).thenReturn("segId");
- when(neutronNetwork.getNetworkUUID()).thenReturn("networkUUID");
- when(neutronNetworkCache.getAllNetworks()).thenReturn(listNeutronNetwork);
-
- assertEquals("Error, did not return the UUID of the correct network", listNeutronNetwork.get(0).getNetworkUUID(), tenantNetworkManagerImpl.getNetworkId("segId"));
-
- verify(neutronNetworkCache, times(1)).getAllNetworks();
- }
-
- /**
- * Test method {@link TenantNetworkManagerImpl#getTenantNetwork(OvsdbTerminationPointAugmentation)}
- */
- @Test
- public void testGetTenantNetwork() {
- when(southbound.getInterfaceExternalIdsValue(any(OvsdbTerminationPointAugmentation.class), anyString())).thenReturn(INTERFACE_ID);
- NeutronPort neutronPort = mock(NeutronPort.class);
- when(neutronL3Adapter.getPortPreferablyFromCleanupCache(anyString())).thenReturn(neutronPort);
- NeutronNetwork neutronNetwork = mock(NeutronNetwork.class);
- when(neutronNetworkCache.getNetwork(anyString())).thenReturn(neutronNetwork);
-
- assertEquals("Error, did not return the correct tenant", neutronNetwork, tenantNetworkManagerImpl.getTenantNetwork(mock(OvsdbTerminationPointAugmentation.class)));
- }
-
- @Test
- public void testGetTenantPort() {
- when(southbound.getInterfaceExternalIdsValue(any(OvsdbTerminationPointAugmentation.class), anyString())).thenReturn(INTERFACE_ID);
- NeutronPort neutronPort = mock(NeutronPort.class);
- when(neutronL3Adapter.getPortPreferablyFromCleanupCache(anyString())).thenReturn(neutronPort);
-
- assertEquals("Error, did not return the correct tenant", neutronPort, tenantNetworkManagerImpl.getTenantPort(mock(OvsdbTerminationPointAugmentation.class)));
- }
-
- @Test
- public void testNetworkCreated() {
- tenantNetworkManagerImpl.networkCreated(mock(Node.class), NETWORK_ID);
- verify(vlanConfigurationCache, times(1)).assignInternalVlan(any(Node.class), anyString());
- }
-
- @Test
- public void testSetDependencies() throws Exception {
- VlanConfigurationCache vlanConfigurationCache = mock(VlanConfigurationCache.class);
- Southbound southbound = mock(Southbound.class);
-
- ServiceHelper.overrideGlobalInstance(VlanConfigurationCache.class, vlanConfigurationCache);
- ServiceHelper.overrideGlobalInstance(Southbound.class, southbound);
-
- tenantNetworkManagerImpl.setDependencies(mock(ServiceReference.class));
-
- assertEquals("Error, did not return the correct object", getField("vlanConfigurationCache"), vlanConfigurationCache);
- assertEquals("Error, did not return the correct object", getField("southbound"), southbound);
- }
-
- @Test
- public void testSetDependenciesObject() throws Exception{
- INeutronNetworkCRUD neutronNetworkCache = mock(INeutronNetworkCRUD.class);
- tenantNetworkManagerImpl.setDependencies(neutronNetworkCache);
- assertEquals("Error, did not return the correct object", getField("neutronNetworkCache"), neutronNetworkCache);
-
- INeutronPortCRUD neutronPortCache = mock(INeutronPortCRUD.class);
- tenantNetworkManagerImpl.setDependencies(neutronPortCache);
- assertEquals("Error, did not return the correct object", getField("neutronPortCache"), neutronPortCache);
- }
-
- private Object getField(String fieldName) throws Exception {
- Field field = TenantNetworkManagerImpl.class.getDeclaredField(fieldName);
- field.setAccessible(true);
- return field.get(tenantNetworkManagerImpl);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2016 Inocybe 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.netvirt.openstack.netvirt.impl;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-import java.lang.reflect.Field;
-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.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.netvirt.openstack.netvirt.api.Southbound;
-import org.opendaylight.netvirt.openstack.netvirt.api.TenantNetworkManager;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.VlanId;
-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.osgi.framework.ServiceReference;
-
-/**
- * Unit test for {@link VlanConfigurationCacheImpl}
- */
-@RunWith(MockitoJUnitRunner.class)
-public class VlanConfigurationCacheImplTest {
-
- @InjectMocks public VlanConfigurationCacheImpl vlanConfigurationCacheImpl;
-
- @Mock private TenantNetworkManager tenantNetworkManager;
- @Mock private Southbound southbound;
-
- private static final String NODE_UUID = "nodeUUID";
- private static final String NETWORK_ID= "networkId";
- private static final int VLAN_ID = 4;
- /**
- * Function configuring the node
- */
- @Before
- public void setUp(){
- when(southbound.getOvsdbNodeUUID(any(Node.class))).thenReturn(NODE_UUID);
- List<OvsdbTerminationPointAugmentation> ports = new ArrayList<>();
- OvsdbTerminationPointAugmentation port = mock(OvsdbTerminationPointAugmentation.class);
- VlanId vlanId = mock(VlanId.class);
- when(vlanId.getValue()).thenReturn(VLAN_ID);
- when(port.getVlanTag()).thenReturn(vlanId);
- when(southbound.getTerminationPointsOfBridge(any(Node.class))).thenReturn(ports );
- NeutronNetwork neutronNetwork = mock(NeutronNetwork.class);
- when(neutronNetwork.getNetworkUUID()).thenReturn(NETWORK_ID);
- when(tenantNetworkManager.getTenantNetwork(any(OvsdbTerminationPointAugmentation.class))).thenReturn(neutronNetwork );
- }
-
- /**
- * Test method {@link VlanConfigurationCacheImpl#assignInternalVlan(Node, String)}
- */
- @Test
- public void testAssignReclaimAndGetInternalVlan() {
- assertEquals("Error, assignInternalVlan() did not return the correct internalVlanId (first added)", 1, (int) vlanConfigurationCacheImpl.assignInternalVlan(any(Node.class), NETWORK_ID));
- assertEquals("Error, assignInternalVlan () did not return the correct internalVlanId (second added)", 2, (int) vlanConfigurationCacheImpl.assignInternalVlan(any(Node.class), NETWORK_ID + "1"));
-
- assertEquals("Error, getInternalVlan() did not return the correct internalVlan", 1, (int) vlanConfigurationCacheImpl.getInternalVlan(any(Node.class), NETWORK_ID));
-
- assertEquals("Error, reclaimInternalVlan() did not return the correct internalVlanId", 1, (int) vlanConfigurationCacheImpl.reclaimInternalVlan(any(Node.class), NETWORK_ID));
- assertEquals("Error, reclaimInternalVlan() did not return the correct internalVlanId", 2, (int) vlanConfigurationCacheImpl.reclaimInternalVlan(any(Node.class), NETWORK_ID + "1"));
- }
-
- @Test
- public void testSetDependencies() throws Exception {
- TenantNetworkManager tenantNetworkManager = mock(TenantNetworkManager.class);
- Southbound southbound = mock(Southbound.class);
-
- ServiceHelper.overrideGlobalInstance(TenantNetworkManager.class, tenantNetworkManager);
- ServiceHelper.overrideGlobalInstance(Southbound.class, southbound);
-
- vlanConfigurationCacheImpl.setDependencies(mock(ServiceReference.class));
-
- assertEquals("Error, did not return the correct object", getField("tenantNetworkManager"), tenantNetworkManager);
- assertEquals("Error, did not return the correct object", getField("southbound"), southbound);
- }
-
- private Object getField(String fieldName) throws Exception {
- Field field = VlanConfigurationCacheImpl.class.getDeclaredField(fieldName);
- field.setAccessible(true);
- return field.get(vlanConfigurationCacheImpl);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2016 NEC Corporation 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.netvirt.openstack.netvirt.translator.crud.impl;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.anyCollection;
-import static org.mockito.Mockito.after;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.verify;
-
-import java.util.List;
-import org.junit.Test;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
-import org.opendaylight.controller.md.sal.binding.test.AbstractDataBrokerTest;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronFloatingIP;
-import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.impl.NeutronFloatingIPDataTreeChangeListener;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.floatingips.attributes.floatingips.Floatingip;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.floatingips.attributes.floatingips.FloatingipBuilder;
-
-/**
- * Unit test for {@link NeutronFloatingIPInterface}
- */
-public class NeutronFloatingIPInterfaceTest extends AbstractDataBrokerTest {
- /**
- * UUID_VALUE used for testing different scenarios.
- */
- private static final String UUID_VALUE = "b9a13232-525e-4d8c-be21-cd65e3436034";
- /**
- * FIXED_IP_ADDRESS used for testing different scenarios.
- */
- private static final String FIXED_IP_ADDRESS = "10.0.0.3";
- /**
- * FLOATING_IP_ADDRESS used for testing different scenarios.
- */
- private static final String FLOATING_IP_ADDRESS = "172.24.4.228";
- /**
- * STATUS used for testing different scenarios.
- */
- private static final String STATUS = "ACTIVE";
-
- private NeutronFloatingIPInterface getTestInterface(DataBroker broker) {
- return new NeutronFloatingIPInterface(broker);
- }
-
- /**
- * Test that checks if @{NeutronFloatingIPInterface#floatingIPExists} is called
- * and then checks that floating Ip exists or not.
- */
- @Test
- public void testFloatingIPExists() throws TransactionCommitFailedException {
- // floatingIPExists() returns true if the underlying data broker contains the node, false otherwise
- DataBroker broker = getDataBroker();
- NeutronFloatingIPInterface testInterface = getTestInterface(broker);
-
- // First case: the underlying data broker returns nothing (we haven't inserted the IP yet)
- assertFalse(testInterface.floatingIPExists(UUID_VALUE));
-
- // Add an IP
- addTestFloatingIP(broker, testInterface);
-
- // Second case: the underlying data broker returns something
- assertTrue(testInterface.floatingIPExists(UUID_VALUE));
- }
-
- private void addTestFloatingIP(DataBroker broker, NeutronFloatingIPInterface testInterface)
- throws TransactionCommitFailedException {
- WriteTransaction writeTransaction = broker.newWriteOnlyTransaction();
- Floatingip floatingip = new FloatingipBuilder().setUuid(new Uuid(UUID_VALUE)).build();
- writeTransaction.put(LogicalDatastoreType.CONFIGURATION,
- testInterface.createInstanceIdentifier(floatingip), floatingip);
- writeTransaction.submit().checkedGet();
- }
-
- /**
- * Test that checks if @{NeutronFloatingIPInterface#getFloatingIP} is called
- * and then checks that it gets floating Ip or not.
- */
- @Test
- public void testGetFloatingIP() throws TransactionCommitFailedException {
- // getFloatingIP() returns the floating IP if the underlying data broker contains the node, null otherwise
- DataBroker broker = getDataBroker();
- NeutronFloatingIPInterface testInterface = getTestInterface(broker);
-
- // First case: the underlying data broker returns nothing (we haven't inserted the IP yet)
- assertNull(testInterface.getFloatingIP(UUID_VALUE));
-
- // Add an IP
- addTestFloatingIP(broker, testInterface);
-
- // Second case: the underlying data broker returns something
- final NeutronFloatingIP returnedFloatingIp = testInterface.getFloatingIP(UUID_VALUE);
- assertNotNull(returnedFloatingIp);
- assertEquals("UUID mismatch", UUID_VALUE, returnedFloatingIp.getID());
- }
-
- /**
- * Test that checks if @{NeutronFloatingIPInterface#getAllFloatingIPs} is called
- * and then checks that it gets all floating Ips in a list or not.
- */
- @Test
- public void testGetAllFloatingIPs() throws TransactionCommitFailedException {
- // getAllFloatingIPs() returns all the floating IPs in the underlying data broker
- DataBroker broker = getDataBroker();
- NeutronFloatingIPInterface testInterface = getTestInterface(broker);
-
- // First case: the underlying data broker returns nothing (we haven't inserted the IP yet)
- assertTrue("Non-empty list of floating IPs", testInterface.getAllFloatingIPs().isEmpty());
-
- // Add an IP
- addTestFloatingIP(broker, testInterface);
-
- // Second case: the underlying data broker returns something
- final List<NeutronFloatingIP> allFloatingIPs = testInterface.getAllFloatingIPs();
- assertFalse("Empty list of floating IPs", allFloatingIPs.isEmpty());
- assertEquals("Incorrect number of floating IPs", 1, allFloatingIPs.size());
- assertEquals("UUID mismatch", UUID_VALUE, allFloatingIPs.get(0).getID());
- }
-
- /**
- * Test that checks if @{NeutronFloatingIPInterface#addFloatingIP} is called
- * and then verifies whether floating Ip already exists in datastore if not then
- * ensures floating ip addition by invoking MD-SAL add.
- */
- @Test
- public void testAddFloatingIP() throws TransactionCommitFailedException {
- // addFloatingIP() adds the given floating IP if it isn't already in the data store
- DataBroker broker = getDataBroker();
- NeutronFloatingIPInterface testInterface = getTestInterface(broker);
-
- // First case: addFloatingIP() adds the floating IP
- NeutronFloatingIP insertedFloatingIp = new NeutronFloatingIP();
- insertedFloatingIp.setID(UUID_VALUE);
- assertTrue("Floating IP already present", testInterface.addFloatingIP(insertedFloatingIp));
-
- // TODO Retrieve the floating IP directly and make sure it's correct
-
- // Second case: the floating IP is already present
- assertFalse("Floating IP missing", testInterface.addFloatingIP(insertedFloatingIp));
- }
-
- /**
- * Test that checks if @{NeutronFloatingIPInterface#removeFloatingIP} is called
- * and then verifies by reading floating ip from datastore and ensures floating ip
- * removal by invoking MD-SAL remove.
- */
- @Test
- public void testRemoveFloatingIP() throws TransactionCommitFailedException {
- // removeFloatingIP() removes the given floating IP if it's present in the data store
- DataBroker broker = getDataBroker();
- NeutronFloatingIPInterface testInterface = getTestInterface(broker);
-
- // First case: the floating IP isn't present
- assertFalse("Floating IP present", testInterface.removeFloatingIP(UUID_VALUE));
-
- // Add an IP
- addTestFloatingIP(broker, testInterface);
-
- // Second case: the floating IP is present
- assertTrue("Floating IP absent", testInterface.removeFloatingIP(UUID_VALUE));
-
- // TODO Attempt to retrieve the floating IP and make sure it's absent
- }
-
- /**
- * Test that checks if @{NeutronFloatingIPInterface#updateFloatingIP} is called
- * and then verifies by reading floating ip from datastore and ensures floating ip
- * updation by invoking MD-SAL update.
- */
- @Test
- public void testUpdateFloatingIP() throws TransactionCommitFailedException {
- // updateFloatingIP() updates the given floating IP only if it's already in the data store
- DataBroker broker = getDataBroker();
- NeutronFloatingIPInterface testInterface = getTestInterface(broker);
-
- // First case: the floating IP isn't present
- NeutronFloatingIP testFloatingIp = new NeutronFloatingIP();
- testFloatingIp.setID(UUID_VALUE);
- assertFalse("Floating IP present", testInterface.updateFloatingIP(UUID_VALUE, testFloatingIp));
-
- // Add an IP
- addTestFloatingIP(broker, testInterface);
-
- // Second case: the floating IP is present
- assertTrue("Floating IP absent", testInterface.updateFloatingIP(UUID_VALUE, testFloatingIp));
-
- // TODO Change some attributes and make sure they're updated
- }
-
- @Test
- public void testListener() throws TransactionCommitFailedException {
- // Given a databroker, test interface and floating IP listener ...
- DataBroker broker = getDataBroker();
- NeutronFloatingIPInterface testInterface = getTestInterface(broker);
- NeutronFloatingIPDataTreeChangeListener listener = spy(new NeutronFloatingIPDataTreeChangeListener(broker));
- listener.init();
-
- // When we add a floating IP ...
- addTestFloatingIP(broker, testInterface);
-
- // ... the listener is called
- verify(listener, after(5000).atLeastOnce()).onDataTreeChanged(anyCollection());
-
- // This test currently logs NullPointerExceptions, but we don't care about them —
- // the listener needs an OSGi context to find NeutronIAware implementations
-
- // Remove the listener to avoid polluting other tests
- listener.close();
- }
-
- /**
- * Test that checks if @{NeutronFloatingIPInterface#toMd} is called
- * and then checks that it sets vales into floating Ip.
- */
- @Test
- public void testToMd() throws Exception {
- DataBroker broker = getDataBroker();
- NeutronFloatingIPInterface testInterface = getTestInterface(broker);
- NeutronFloatingIP neutronFloatingIP = new NeutronFloatingIP();
- neutronFloatingIP.setID(UUID_VALUE);
- neutronFloatingIP.setFloatingNetworkUUID(UUID_VALUE);
- neutronFloatingIP.setPortUUID(UUID_VALUE);
- neutronFloatingIP.setFixedIPAddress(FIXED_IP_ADDRESS);
- neutronFloatingIP.setFloatingIPAddress(FLOATING_IP_ADDRESS);
- neutronFloatingIP.setTenantUUID(UUID_VALUE);
- neutronFloatingIP.setRouterUUID(UUID_VALUE);
- neutronFloatingIP.setStatus(STATUS);
- Floatingip floatingipReceived = testInterface.toMd(neutronFloatingIP);
- assertEquals("UUID mismatch", UUID_VALUE, floatingipReceived.getUuid().getValue());
- assertEquals("FloatingNetworkId mismatch", UUID_VALUE, floatingipReceived.getFloatingNetworkId().getValue());
- assertEquals("Port ID mismatch", UUID_VALUE, floatingipReceived.getPortId().getValue());
- assertEquals("Fixed IP Address mismatch", FIXED_IP_ADDRESS, String.valueOf(floatingipReceived.getFixedIpAddress().getValue()));
- assertEquals("Floating IP Address mismatch", FLOATING_IP_ADDRESS, String.valueOf(floatingipReceived.getFloatingIpAddress().getValue()));
- assertEquals("Tenant Id mismatch", UUID_VALUE, floatingipReceived.getTenantId().getValue());
- assertEquals("Router Id mismatch", UUID_VALUE, floatingipReceived.getRouterId().getValue());
- assertEquals("Status mismatch", STATUS, floatingipReceived.getStatus());
- }
-
- /**
- * Test that checks if @{NeutronFloatingIPInterface#fromMd} is called
- * and then checks that it gets values from Floating Ip.
- */
- @Test
- public void testFromMd() throws Exception {
- DataBroker broker = getDataBroker();
- NeutronFloatingIPInterface testInterface = getTestInterface(broker);
- Floatingip actualfloatingip = new FloatingipBuilder()
- .setUuid(new Uuid(UUID_VALUE))
- .setFixedIpAddress(
- new IpAddress(FIXED_IP_ADDRESS.toCharArray()))
- .setFloatingIpAddress(
- new IpAddress(FLOATING_IP_ADDRESS.toCharArray()))
- .setFloatingNetworkId(new Uuid(UUID_VALUE))
- .setPortId(new Uuid(UUID_VALUE))
- .setRouterId(new Uuid(UUID_VALUE)).setStatus(STATUS)
- .setTenantId(new Uuid(UUID_VALUE)).build();
- NeutronFloatingIP neutronFloatingIPReceived = testInterface.fromMd(actualfloatingip);
- assertEquals("UUID mismatch", UUID_VALUE, neutronFloatingIPReceived.getID());
- assertEquals("FloatingNetworkId mismatch", UUID_VALUE, neutronFloatingIPReceived.getFloatingNetworkUUID());
- assertEquals("Port ID mismatch", UUID_VALUE, neutronFloatingIPReceived.getPortUUID());
- assertEquals("Fixed IP Address mismatch", FIXED_IP_ADDRESS, neutronFloatingIPReceived.getFixedIPAddress());
- assertEquals("Floating IP Address mismatch", FLOATING_IP_ADDRESS, neutronFloatingIPReceived.getFloatingIPAddress());
- assertEquals("Tenant Id mismatch", UUID_VALUE, neutronFloatingIPReceived.getTenantUUID());
- assertEquals("Router Id mismatch", UUID_VALUE, neutronFloatingIPReceived.getRouterUUID());
- assertEquals("Status mismatch", STATUS, neutronFloatingIPReceived.getStatus());
- }
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-Copyright (C) 2015 Red Hat, Inc. and others. All rights reserved.
-
-This program and the accompanying materials are made available under the
-terms of the Eclipse Public License v1.0 which accompanies this distribution,
-and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>odlparent-lite</artifactId>
- <version>2.0.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>netvirt-artifacts</artifactId>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>pom</packaging>
- <description>The OVSDB Plugin integration project is a project for OpenDaylight that will implement the Open vSwitch Database RFC 7047 management protocol allowing the Southbound configuration of vSwitches and a network virtualization implementation.</description>
- <licenses>
- <license>
- <name>Eclipse Public License v1.0</name>
- <url>http://www.eclipse.org/legal/epl-v10.html</url>
- </license>
- </licenses>
- <developers>
- <developer>
- <name>Sam Hague</name>
- <email>shague@gmail.com</email>
- <url>https://github.com/shague</url>
- </developer>
- </developers>
- <scm>
- <connection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</connection>
- <developerConnection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</developerConnection>
- <tag>HEAD</tag>
- <url>https://wiki.opendaylight.org/view/OVSDB_Integration:Main</url>
- </scm>
-
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>features-netvirt</artifactId>
- <version>${project.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- </dependencies>
- </dependencyManagement>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-Copyright (c) 2015 Red Hat, Inc. and others. All rights reserved.
-
-This program and the accompanying materials are made available under the
-terms of the Eclipse Public License v1.0 which accompanies this distribution,
-and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <parent>
- <groupId>org.opendaylight.mdsal</groupId>
- <artifactId>binding-parent</artifactId>
- <version>0.11.0-SNAPSHOT</version>
- <relativePath/>
- </parent>
-
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>ietf-inet-types-2013-07-15</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>ietf-yang-types-20130715</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>yang-ext</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>opendaylight-l2-types</artifactId>
- </dependency>
- </dependencies>
-
- <modelVersion>4.0.0</modelVersion>
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>netvirt-api</artifactId>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>bundle</packaging>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <extensions>true</extensions>
- <configuration>
- <instructions>
- <Export-Package>
- org.opendaylight.yang.gen.v1.*,
- org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.*,
- org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.common.rev151227,
- org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.devices.rev151227,
- org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l2.networks.rev151227,
- org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.ports.rev151227,
- org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.ports.rev151227.port,
- </Export-Package>
- </instructions>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-module netvirt-common {
- yang-version 1;
- namespace "urn:opendaylight:netvirt:common";
- prefix "common";
-
- revision "2015-12-27" {
- description "Initial revision of netvirt common attributes";
- }
-
- import ietf-yang-types { prefix yang; }
-
- identity network-type-base {
- description "Base network type";
- }
-
- identity network-type-flat {
- base network-type-base;
- description "network type flat";
- }
-
- identity network-type-gre {
- base network-type-base;
- description "network type gre";
- }
-
- identity network-type-vlan {
- base network-type-base;
- description "network type vlan";
- }
-
- identity network-type-vxlan {
- base network-type-base;
- description "network type vxlan";
- }
-
- identity network-type-vxlan-gpe {
- base network-type-base;
- description "network type vxlan-gpe";
- }
-
- typedef network-type {
- type identityref {
- base network-type-base;
- }
- description "This type is used to refer to a network Type.";
- }
-
- grouping base-attributes {
- leaf uuid {
- type yang:uuid;
- description "UUID to index this object.";
- }
-
- leaf name {
- type string;
- description "Optional human-readable name for the item. Might not be unique.";
- }
-
- leaf description {
- type string;
- description "Optional human-readable description for the item. Might not be unique.";
- }
-
- list other-config {
- description "This is used to store information needed by the renderer(s). In general,
- it might be used as a cookie to relate external objects or configuration with
- the given NetVirt object. For example, we may store neutron logical port
- information here so that the OVS southbound renderer can match up the port
- reported by OVSDB with the Neutron port configured by Neutron.";
- key config-key;
- leaf config-key {
- description "Key to identify the piece of config info.
- This needs to be unique both within and between renderers.
- Format: <renderer-name>:<renderer-unique-key>";
- type string;
- }
- leaf config-value {
- type string;
- }
- }
- }
-
- grouping admin-attributes {
- leaf admin-state-up {
- type boolean;
- description "The administrative state of the object, which is up (true) or down (false).";
- }
- leaf status {
- type string;
- description "The object status.";
- }
- }
-
- grouping device-locator-ref {
- leaf device-uuid {
- type yang:uuid;
- description "Reference to the the device for this port";
- }
-
- leaf device-locator-uuid {
- type yang:uuid;
- description "Reference to the the device locator for this port";
- }
- }
-}
+++ /dev/null
-module netvirt-devices {
- yang-version 1;
- namespace "urn:opendaylight:netvirt:devices";
- prefix "devices";
-
- revision "2015-12-27" {
- description "Initial revision of netvirt devices definition";
- }
-
- import ietf-yang-types { prefix yang; }
- import ietf-inet-types { prefix inet; }
- import netvirt-common { prefix "common"; }
- import opendaylight-l2-types { prefix l2types; }
-
-
-
- grouping flat-attributes {
- }
-
- grouping vlan-attributes {
- }
-
- grouping gre-attributes {
- leaf ip-addr {
- type inet:ip-address;
- }
- leaf port {
- type inet:port-number;
- }
- }
-
- grouping vxlan-attributes {
- leaf ip-addr {
- type inet:ip-address;
- }
- leaf port {
- type inet:port-number;
- }
- }
-
- grouping vxlan-gpe-attributes {
- leaf ip-addr {
- type inet:ip-address;
- }
- leaf port {
- type inet:port-number;
- }
- }
-
- grouping device-locator {
- uses common:base-attributes;
-
- leaf locator-type {
- type common:network-type;
- }
-
- choice locator-attr {
- case flat {
- uses flat-attributes;
- }
- case vlan {
- uses vlan-attributes;
- }
- case gre {
- uses gre-attributes;
- }
- case vxlan {
- uses vxlan-attributes;
- }
- case vxlan-gpe {
- uses vxlan-gpe-attributes;
- }
- }
- }
-
- grouping device {
- uses common:base-attributes;
-
- leaf device-type {
- type enumeration {
- enum ovs;
- enum hwgw;
- }
- }
-
- // TODO: Need to look at info needed per bridge.
- list bridges {
- leaf name {
- type string;
- }
- }
-
- list device-locators {
- key uuid;
- uses device-locator;
- }
- }
-
- container devices {
- list device {
- key uuid;
- uses device;
- }
- }
-}
+++ /dev/null
-module netvirt-l2-networks {
- yang-version 1;
- namespace "urn:opendaylight:netvirt:l2-networks";
- prefix "l2-networks";
-
- revision "2015-12-27" {
- description "Initial revision of netvirt l2-networks definition";
- }
-
- import ietf-inet-types { prefix inet; revision-date 2013-07-15; }
- import ietf-yang-types { prefix yang; }
- import netvirt-common { prefix "common"; }
-
- container l2-networks {
- list l2-network {
- uses common:base-attributes;
- uses common:admin-attributes;
-
- description "Description: Logical Layer 2 Networks. E.g., a Neutron Network. Typically, an l2-network
- defines an L2 broadcast domain and, unless otherwise prohibited, endpoints attached to ports
- on an l2-network can communicate with each other. All l2-network are independent, and
- communication between l2-network is only allowed via other means, such as through an
- l3-router.";
-
- key uuid;
-
- leaf network-type {
- type common:network-type;
- description "The type of physical network that maps to this network resource.";
- }
-
- leaf segmentation-id {
- type string;
- description "An isolated segment on the physical network. The network-type
- attribute defines the segmentation model. For example, if network-type
- is vlan, this ID is a vlan identifier. If network-type is gre,
- this ID is a gre key.";
- }
-
- leaf shared {
- type boolean;
- default "false";
- description "Indicates whether this network or subnet is shared across all
- tenants. By default, only administrative users can change this
- value.";
- }
-
- list device-locators {
- uses common:device-locator-ref;
- }
- }
- }
-}
+++ /dev/null
-module netvirt-ports {
- yang-version 1;
- namespace "urn:opendaylight:netvirt:ports";
- prefix "ports";
-
- revision "2015-12-27" {
- description "Initial revision of netvirt ports definition";
- }
-
- import ietf-inet-types { prefix inet; revision-date 2013-07-15;}
- import ietf-yang-types { prefix yang; revision-date "2013-07-15";}
- import netvirt-common { prefix "common"; }
-
-
- identity port-type-base {
- description "Base port type";
- }
-
- identity port-type-l2-network {
- base port-type-base;
- description "port type l2-network";
- }
-
- identity port-type-router {
- base port-type-base;
- description "port type router";
- }
-
- identity port-type-router-interface-distributed {
- base port-type-base;
- description "port type router interface distributed";
- }
-
- identity port-type-router-gateway {
- base port-type-base;
- description "port type router gateway";
- }
-
- identity port-type-dhcp {
- base port-type-base;
- description "port type dhcp";
- }
-
- identity port-type-floating-ip {
- base port-type-base;
- description "port type floatingip";
- }
-
- identity port-type-compute-nova {
- base port-type-base;
- description "port type compute nova";
- }
-
- typedef port-type {
- type identityref {
- base port-type-base;
- }
- description "This type is used to refer to an port Type.";
- }
-
- identity port-binding-type-base {
- description "Base port-binding type";
- }
-
- identity port-binding-type-vlan {
- base port-binding-type-base;
- description "port-binding type vlan";
- }
-
- identity port-binding-type-vxlan {
- base port-binding-type-base;
- description "port-binding type vxlan";
- }
-
- typedef port-binding-type {
- type identityref {
- base port-binding-type-base;
- }
- description "The port binding is used to bind one port to another in a hierarchical.";
- }
-
- grouping end-point {
- uses common:base-attributes;
-
- leaf macaddr {
- type yang:mac-address;
- description "MAC address entry";
- }
-
- leaf-list ipaddrs {
- description "Mechanism used to bind ports.";
- type inet:ip-address;
- }
- }
-
- grouping parent-port-binding {
- description "Optional. Used to bind one port to another hierarchically. For example, a port
- binding may be used to support multiple containers in a single VM. In this model
- each container could use a VLAN-based sub-port on a single tap port.";
-
- leaf type {
- description "How is this port bound to the other. E.g., VLAN";
- type port-binding-type;
- }
-
- leaf id {
- description "Depends on binding type. E.g., if the type is VLAN, this would be the VLAN ID";
- type string;
- }
-
- leaf parent-port {
- description "Must be the UUID of another port.";
- type yang:uuid;
- }
- }
-
- grouping port {
- uses common:base-attributes;
- uses common:admin-attributes;
-
- leaf port-type {
- type port-type;
- description "The type of port.";
- }
-
- leaf parent {
- type yang:uuid;
- description "The UUID of the object this port is a member of. For example, if the type is
- port-type-l2-network, this will be the UUID of the l2-network";
- }
-
- uses parent-port-binding;
-
- // TODO: Can we use a leafref for the device locator?
- leaf device-uuid {
- type yang:uuid;
- description "Reference to the the device for this port";
- }
-
- leaf device-locator-uuid {
- type yang:uuid;
- description "Reference to the the device locator for this port";
- }
-
- list end-points {
-
- key macaddr;
-
- uses end-point;
- }
- }
-
- container ports {
- list port {
- description "List of ports. Each port entry contains both logical and physical information.";
-
- key uuid;
- uses port;
- }
- }
-}
+++ /dev/null
-module netvirt {
- yang-version 1;
- namespace "urn:opendaylight:netvirt";
- prefix "netvirt";
-
- revision "2015-12-27" {
- description "Initial revision of netvirt model";
- }
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-Copyright © 2016 Red Hat, Inc. and others. All rights reserved.
-
-This program and the accompanying materials are made available under the
-terms of the Eclipse Public License v1.0 which accompanies this distribution,
-and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
-
- <parent>
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>it</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <relativePath>../../commons/it</relativePath>
- </parent>
-
- <modelVersion>4.0.0</modelVersion>
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>netvirt-it</artifactId>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>jar</packaging>
-
- <properties>
- <controller.mdsal.version>1.6.0-SNAPSHOT</controller.mdsal.version>
- <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>
- <ovsdb.version>1.5.0-SNAPSHOT</ovsdb.version>
- </properties>
-
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-binding-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-common-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-util</artifactId>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>features-netvirt</artifactId>
- <version>${project.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.ovsdb</groupId>
- <artifactId>southbound-api</artifactId>
- <version>${ovsdb.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>utils.netvirt-it-utils</artifactId>
- <version>${project.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>utils.mdsal-openflow</artifactId>
- <version>${project.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>utils.mdsal-utils</artifactId>
- <version>${project.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>utils.neutron-utils</artifactId>
- <version>${project.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>openstack.net-virt</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.ovsdb</groupId>
- <artifactId>utils.mdsal-utils</artifactId>
- <version>${ovsdb.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.ovsdb</groupId>
- <artifactId>utils.southbound-utils</artifactId>
- <version>${ovsdb.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.codehaus.sonar-plugins.java</groupId>
- <artifactId>sonar-jacoco-listeners</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.jacoco</groupId>
- <artifactId>jacoco-maven-plugin</artifactId>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-failsafe-plugin</artifactId>
- <configuration>
- <!--<excludes>
- <exclude>**/NetvirtIT.java</exclude>
- </excludes>-->
- </configuration>
- </plugin>
- </plugins>
- </build>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-/*
- * Copyright © 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.netvirt.it;
-
-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.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.keepRuntimeFolder;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Properties;
-import java.util.concurrent.atomic.AtomicBoolean;
-import javax.inject.Inject;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-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.netvirt.openstack.netvirt.NeutronModelsDataStoreHelper;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.NeutronNetwork;
-import org.opendaylight.netvirt.utils.netvirt.it.utils.ItConstants;
-import org.opendaylight.netvirt.utils.netvirt.it.utils.NetvirtItUtils;
-import org.opendaylight.netvirt.utils.neutron.utils.NeutronUtils;
-import org.opendaylight.ovsdb.utils.mdsal.utils.MdsalUtils;
-import org.opendaylight.ovsdb.utils.mdsal.utils.NotifyingDataChangeListener;
-import org.opendaylight.ovsdb.utils.southbound.utils.SouthboundUtils;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.networks.Network;
-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.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.ops4j.pax.exam.util.Filter;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-@RunWith(PaxExam.class)
-@ExamReactorStrategy(PerClass.class)
-public class NetvirtIT extends AbstractMdsalTestBase {
- private static final Logger LOG = LoggerFactory.getLogger(NetvirtIT.class);
- private static final String FEATURE = "odl-netvirt-it";
- private static NetvirtItUtils itUtils;
- 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 SouthboundUtils southboundUtils;
- private static NeutronUtils neutronUtils = new NeutronUtils();
- private static NeutronModelsDataStoreHelper neutronModelsDataStoreHelper;
- private static final String NETWORK_TYPE_VXLAN = "vxlan";
- @Inject @Filter(timeout=60000)
- private static DataBroker dataBroker = null;
-
-
- @Override
- public String getModuleName() {
- return "netvirt-neutron";
- }
-
- @Override
- public String getInstanceName() { return "netvirt-neutron"; }
-
- @Override
- public MavenUrlReference getFeatureRepo() {
- return maven()
- .groupId("org.opendaylight.netvirt")
- .artifactId("features-netvirt")
- .classifier("features")
- .type("xml")
- .versionAsInProject();
- }
-
- @Override
- public String getFeatureName() {
- return FEATURE;
- }
-
- @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.netvirt", "utils.mdsal-openflow")
- .version(asInProject())
- .type("jar")),
- configureConsole().startLocalConsole(),
- //vmOption("-verbose:class"),
- vmOption("-javaagent:../jars/org.jacoco.agent.jar=destfile=../../jacoco-it.exec"),
- keepRuntimeFolder()
- };
- }
-
- private Option[] getPropertiesOptions() {
- return new Option[] {
- propagateSystemProperties(ItConstants.SERVER_IPADDRESS, ItConstants.SERVER_PORT,
- ItConstants.CONNECTION_TYPE, ItConstants.CONTROLLER_IPADDRESS,
- ItConstants.USERSPACE_ENABLED),
- };
- }
-
- @Override
- public Option getLoggingOption() {
- return composite(
- editConfigurationFilePut(ItConstants.ORG_OPS4J_PAX_LOGGING_CFG,
- "log4j.logger.org.opendaylight.ovsdb",
- LogLevelOption.LogLevel.TRACE.name()),
- editConfigurationFilePut(ItConstants.ORG_OPS4J_PAX_LOGGING_CFG,
- logConfiguration(NetvirtIT.class),
- LogLevelOption.LogLevel.INFO.name()),
- editConfigurationFilePut(ItConstants.ORG_OPS4J_PAX_LOGGING_CFG,
- "log4j.logger.org.opendaylight.neutron",
- LogLevelOption.LogLevel.TRACE.name()),
- super.getLoggingOption());
- }
-
- 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";
- }
-
- private void getProperties() {
- Properties props = System.getProperties();
- addressStr = props.getProperty(ItConstants.SERVER_IPADDRESS);
- portStr = props.getProperty(ItConstants.SERVER_PORT, ItConstants.DEFAULT_SERVER_PORT);
- connectionType = props.getProperty(ItConstants.CONNECTION_TYPE, "active");
- controllerStr = props.getProperty(ItConstants.CONTROLLER_IPADDRESS, "0.0.0.0");
- String userSpaceEnabled = props.getProperty(ItConstants.USERSPACE_ENABLED, "no");
- LOG.info("setUp: Using the following properties: mode= {}, ip:port= {}:{}, controller ip: {}, " +
- "userspace.enabled: {}",
- connectionType, addressStr, portStr, controllerStr, userSpaceEnabled);
- if (connectionType.equalsIgnoreCase(ItConstants.CONNECTION_TYPE_ACTIVE)) {
- if (addressStr == null) {
- fail(usage());
- }
- }
- }
-
- @After
- public void teardown() {
- closeWaitFors();
- }
-
- @Before
- @Override
- public void setup() throws InterruptedException {
- if (setup.get()) {
- LOG.info("Skipping setUp, already initialized");
- return;
- }
-
- try {
- super.setup();
- } catch (Exception e) {
- LOG.warn("Failed to setup test", e);
- fail("Failed to setup test: " + e);
- }
-
- getProperties();
-
- if (connectionType.equalsIgnoreCase(ItConstants.CONNECTION_TYPE_ACTIVE)) {
- if (addressStr == null) {
- fail(usage());
- }
- }
-
- assertNotNull("dataBroker should not be null", dataBroker);
- itUtils = new NetvirtItUtils(dataBroker);
- mdsalUtils = new MdsalUtils(dataBroker);
- assertNotNull("mdsalUtils should not be null", mdsalUtils);
- // TODO: Not used yet since openstack is not running to write the netvirt:1 to mdsal
- // Only need neutron northbound right now
- //assertTrue("Did not find " + ItConstants.NETVIRT_TOPOLOGY_ID, itUtils.getNetvirtTopology());
- southboundUtils = new SouthboundUtils(mdsalUtils);
- neutronModelsDataStoreHelper = new NeutronModelsDataStoreHelper(dataBroker);
- setup.set(true);
- }
-
- @Test
- public void testNetvirtFeatureLoad() {
- assertTrue("Feature " + FEATURE + " was not loaded", true);
- }
-
- private List<NotifyingDataChangeListener> waitList = new ArrayList<>();
- private void closeWaitFors() {
- for (Iterator<NotifyingDataChangeListener> iterator = waitList.iterator(); iterator.hasNext();) {
- NotifyingDataChangeListener listener = iterator.next();
- iterator.remove();
- try {
- listener.close();
- } catch (Exception ex) {
- LOG.warn("Failed to close registration {}", listener, ex);
- }
- }
- LOG.info("waitList size {}", waitList.size());
- }
-
- @Test
- public void testNetvirtNeutron() throws InterruptedException {
- final String networkId = "521e29d6-67b8-4b3c-8633-027d21195111";
- final String tenantId = "521e29d6-67b8-4b3c-8633-027d21195100";
-
- InstanceIdentifier<Network> path = neutronModelsDataStoreHelper.getNeutronNetworkPath(new Uuid(networkId));
- final NotifyingDataChangeListener networkOperationalListener =
- new NotifyingDataChangeListener(LogicalDatastoreType.CONFIGURATION, path, waitList);
- networkOperationalListener.registerDataChangeListener(dataBroker);
-
- NeutronNetwork nn = neutronUtils.createNeutronNetwork(networkId, tenantId,
- NETWORK_TYPE_VXLAN, "100");
-
- networkOperationalListener.waitForCreation();
-
- Network network = mdsalUtils.read(LogicalDatastoreType.CONFIGURATION, path);
- assertNotNull("the network was not found in mdsal", network);
- }
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-Copyright (c) 2015 Red Hat, Inc. and others. All rights reserved.
-This program and the accompanying materials are made available under the
-terms of the Eclipse Public License v1.0 which accompanies this distribution,
-and is available at http://www.eclipse.org/legal/epl-v10.html INTERNAL
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>odlparent-lite</artifactId>
- <version>2.0.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>netvirt-aggregator</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <packaging>pom</packaging>
- <modelVersion>4.0.0</modelVersion>
- <modules>
- <module>api</module>
- <module>renderers</module>
- </modules>
- <!-- DO NOT install or deploy the repo root pom as it's only needed to initiate a build -->
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-deploy-plugin</artifactId>
- <configuration>
- <skip>true</skip>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-install-plugin</artifactId>
- <configuration>
- <skip>true</skip>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
- <scm>
- <connection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</connection>
- <developerConnection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</developerConnection>
- <tag>HEAD</tag>
- <url>https://wiki.opendaylight.org/view/OVSDB_Integration:Main</url>
- </scm>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- vi: set et smarttab sw=4 tabstop=4: --><!--
-Copyright (c) 2015 Red Hat, Inc. and others. All rights reserved.
-This program and the accompanying materials are made available under the
-terms of the Eclipse Public License v1.0 which accompanies this distribution,
-and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
-
- <parent>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-parent</artifactId>
- <version>0.7.0-SNAPSHOT</version>
- <relativePath/>
- </parent>
-
- <modelVersion>4.0.0</modelVersion>
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>hwgw</artifactId>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>bundle</packaging>
- <dependencies>
- <!-- Testing Dependencies -->
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-core</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- vi: set et smarttab sw=4 tabstop=4: -->
-<!--
-Copyright (c) 2015 Red Hat, Inc. and others. All rights reserved.
-
-This program and the accompanying materials are made available under the
-terms of the Eclipse Public License v1.0 which accompanies this distribution,
-and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-<snapshot>
- <required-capabilities>
- <capability>urn:opendaylight:params:xml:ns:yang:netvirt:hwgw?module=hwgw&revision=2015-12-27</capability>
- <capability>urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding?module=opendaylight-md-sal-binding&revision=2013-10-28</capability>
- </required-capabilities>
- <configuration>
-
- <data xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
- <modules xmlns="urn:opendaylight:params:xml:ns:yang:controller:config">
- <module>
- <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:netvirt:hwgw">prefix:hwgw</type>
- <name>hwgw-default</name>
- <broker>
- <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding">binding:binding-broker-osgi-registry</type>
- <name>binding-osgi-broker</name>
- </broker>
- </module>
- </modules>
- </data>
- </configuration>
-</snapshot>
+++ /dev/null
-/*
- * Copyright (c) 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.netvirt.renderers.hwgw;
-
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.ProviderContext;
-import org.opendaylight.controller.sal.binding.api.BindingAwareProvider;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class HwgwProvider implements BindingAwareProvider, AutoCloseable {
-
- private static final Logger LOG = LoggerFactory.getLogger(HwgwProvider.class);
-
- @Override
- public void onSessionInitiated(ProviderContext session) {
- LOG.info("HwgwProvider Session Initiated");
- }
-
- @Override
- public void close() throws Exception {
- LOG.info("HwgwProvider Closed");
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.hwgw.rev151227;
-
-import org.opendaylight.netvirt.netvirt.renderers.hwgw.HwgwProvider;
-
-public class HwgwModule extends org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.hwgw.rev151227.AbstractHwgwModule {
- public HwgwModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
- super(identifier, dependencyResolver);
- }
-
- public HwgwModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.hwgw.rev151227.HwgwModule oldModule, java.lang.AutoCloseable oldInstance) {
- super(identifier, dependencyResolver, oldModule, oldInstance);
- }
-
- @Override
- public void customValidation() {
- // add custom validation form module attributes here.
- }
-
- @Override
- public java.lang.AutoCloseable createInstance() {
- HwgwProvider provider = new HwgwProvider();
- getBrokerDependency().registerProvider(provider);
- return provider;
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-/*
-* Generated file
-*
-* Generated from: yang module name: hwgw yang module local name: hwgw
-* Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator
-* Generated at: Fri Jan 02 13:49:24 CST 2015
-*
-* Do not modify this file unless it is present under src/main directory
-*/
-package org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.hwgw.rev151227;
-public class HwgwModuleFactory extends org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.hwgw.rev151227.AbstractHwgwModuleFactory {
-
-}
+++ /dev/null
-module hwgw {
- yang-version 1;
- namespace "urn:opendaylight:params:xml:ns:yang:netvirt:hwgw";
- prefix "hwgw";
-
- import config { prefix config; revision-date 2013-04-05; }
- import opendaylight-md-sal-binding { prefix md-sal-binding; revision-date 2013-10-28;}
-
- description
- "Service definition for hwgw project";
-
- revision "2015-12-27" {
- description
- "Initial revision";
- }
-
- identity hwgw {
- base config:module-type;
- config:java-name-prefix Hwgw;
- }
-
- augment "/config:modules/config:module/config:configuration" {
- case hwgw {
- when "/config:modules/config:module/config:type = 'hwgw'";
- container broker {
- uses config:service-ref {
- refine type {
- mandatory true;
- config:required-identity md-sal-binding:binding-broker-osgi-registry;
- }
- }
- }
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.netvirt.renderers.hwgw;
-
-import org.junit.Test;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
-
-import static org.mockito.Mockito.mock;
-
-public class HwgwProviderTest {
- @Test
- public void testOnSessionInitiated() {
- HwgwProvider provider = new HwgwProvider();
-
- // ensure no exceptions
- // currently this method is empty
- provider.onSessionInitiated(mock(BindingAwareBroker.ProviderContext.class));
- }
-
- @Test
- public void testClose() throws Exception {
- HwgwProvider provider = new HwgwProvider();
-
- // ensure no exceptions
- // currently this method is empty
- provider.close();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.hwgw.rev151227;
-
-import org.junit.Test;
-
-public class HwgwModuleFactoryTest {
- @Test
- public void testFactoryConstructor() {
- // ensure no exceptions on construction
- new HwgwModuleFactory();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.hwgw.rev151227;
-
-import org.junit.Test;
-import org.opendaylight.controller.config.api.DependencyResolver;
-import org.opendaylight.controller.config.api.JmxAttribute;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
-import org.opendaylight.netvirt.netvirt.renderers.hwgw.HwgwProvider;
-
-import javax.management.ObjectName;
-
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-public class HwgwModuleTest {
- @Test
- public void testCustomValidation() {
- HwgwModule module = new HwgwModule(mock(ModuleIdentifier.class), mock(DependencyResolver.class));
-
- // ensure no exceptions on validation
- // currently this method is empty
- module.customValidation();
- }
-
- @Test
- public void testCreateInstance() throws Exception {
- // configure mocks
- DependencyResolver dependencyResolver = mock(DependencyResolver.class);
- BindingAwareBroker broker = mock(BindingAwareBroker.class);
- when(dependencyResolver.resolveInstance(eq(BindingAwareBroker.class), any(ObjectName.class), any(JmxAttribute.class))).thenReturn(broker);
-
- // create instance of module with injected mocks
- HwgwModule module = new HwgwModule(mock(ModuleIdentifier.class), dependencyResolver);
-
- // getInstance calls resolveInstance to get the broker dependency and then calls createInstance
- AutoCloseable closeable = module.getInstance();
-
- // verify that the module registered the returned provider with the broker
- verify(broker).registerProvider((HwgwProvider)closeable);
-
- // ensure no exceptions on close
- closeable.close();
- }
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- vi: set et smarttab sw=4 tabstop=4: --><!--
-Copyright (c) 2016 Red Hat, Inc. and others. All rights reserved.
-This program and the accompanying materials are made available under the
-terms of the Eclipse Public License v1.0 which accompanies this distribution,
-and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
-
- <parent>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-parent</artifactId>
- <version>0.7.0-SNAPSHOT</version>
- <relativePath/>
- </parent>
-
- <modelVersion>4.0.0</modelVersion>
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>neutron</artifactId>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>bundle</packaging>
-
- <properties>
- <neutron.model.version>0.9.0-SNAPSHOT</neutron.model.version>
- </properties>
-
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.neutron</groupId>
- <artifactId>model</artifactId>
- <version>${neutron.model.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>utils.mdsal-utils</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>netvirt-api</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>ietf-inet-types-2013-07-15</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>ietf-yang-types-20130715</artifactId>
- </dependency>
- <!-- Testing Dependencies -->
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-core</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-binding-broker-impl</artifactId>
- <type>test-jar</type>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>mdsal-it-base</artifactId>
- <version>1.6.0-SNAPSHOT</version>
- <scope>test</scope>
- </dependency>
- </dependencies>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-/*
- * Copyright (c) 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.netvirt.renderers.neutron;
-
-import com.google.common.collect.ImmutableBiMap;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.common.rev151227.NetworkTypeBase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.common.rev151227.NetworkTypeFlat;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.common.rev151227.NetworkTypeGre;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.common.rev151227.NetworkTypeVlan;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.common.rev151227.NetworkTypeVxlan;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.ports.rev151227.PortTypeBase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.ports.rev151227.PortTypeComputeNova;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.ports.rev151227.PortTypeDhcp;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.ports.rev151227.PortTypeFloatingIp;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.ports.rev151227.PortTypeRouter;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.ports.rev151227.PortTypeRouterGateway;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.ports.rev151227.PortTypeRouterInterfaceDistributed;
-
-/**
- * A collection of configuration constants
- */
-public final class Constants {
-
- /*
- * Port owner descriptions used by Openstack Neutron
- */
- public static final String OWNER_ROUTER_INTERFACE = "network:router_interface";
- public static final String OWNER_ROUTER_INTERFACE_DISTRIBUTED = "network:router_interface_distributed";
- public static final String OWNER_ROUTER_GATEWAY = "network:router_gateway";
- public static final String OWNER_NETWORK_DHCP = "network:dhcp";
- public static final String OWNER_FLOATING_IP = "network:floatingip";
- public static final String OWNER_COMPUTE_NOVA = "compute:nova";
-
-
- public static final ImmutableBiMap<String, Class<? extends PortTypeBase>> NETVIRT_NEUTRON_PORT_TYPE_MAP
- = new ImmutableBiMap.Builder<String, Class<? extends PortTypeBase>>()
- .put(OWNER_ROUTER_INTERFACE, PortTypeRouter.class)
- .put(OWNER_ROUTER_INTERFACE_DISTRIBUTED, PortTypeRouterInterfaceDistributed.class)
- .put(OWNER_ROUTER_GATEWAY, PortTypeRouterGateway.class)
- .put(OWNER_NETWORK_DHCP, PortTypeDhcp.class)
- .put(OWNER_FLOATING_IP, PortTypeFloatingIp.class)
- .put(OWNER_COMPUTE_NOVA, PortTypeComputeNova.class)
- .build();
-
- /*
- * Network type descriptions used by Openstack Neutron
- */
- public static final String NETWORK_TYPE_FLAT = "NetworkTypeFlat";
- public static final String NETWORK_TYPE_VLAN = "NetworkTypeVlan";
- public static final String NETWORK_TYPE_VXLAN = "NetworkTypeVxlan";
- public static final String NETWORK_TYPE_GRE = "NetworkTypeGre";
-
- public static final ImmutableBiMap<String, Class<? extends NetworkTypeBase>> NETVIRT_NEUTRON_NETWORK_TYPE_MAP
- = new ImmutableBiMap.Builder<String, Class<? extends NetworkTypeBase>>()
- .put(NETWORK_TYPE_FLAT, NetworkTypeFlat.class)
- .put(NETWORK_TYPE_VLAN, NetworkTypeVlan.class)
- .put(NETWORK_TYPE_VXLAN, NetworkTypeVxlan.class)
- .put(NETWORK_TYPE_GRE, NetworkTypeGre.class)
- .build();
-
- public static final String NETVIRT_NEUTRON_OWNER_ENTITY_TYPE = "ovsdb-netvirt-neutron-provider";
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.netvirt.renderers.neutron;
-
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-
-/**
- * netvirt data processor
- * org.opendaylight.ovsdb.netvirt
- */
-public interface DataProcessor<D extends DataObject> {
-
- /**
- * Method removes DataObject which is identified by InstanceIdentifier.
- *
- * @param identifier - the whole path to DataObject
- * @param del - DataObject for removing
- */
- void remove(InstanceIdentifier<D> identifier, D del);
-
- /**
- * Method updates the original DataObject to the update DataObject.
- * Both are identified by same InstanceIdentifier.
- *
- * @param identifier - the whole path to DataObject
- * @param original - original DataObject (for update)
- * @param update - changed DataObject (contain updates)
- */
- void update(InstanceIdentifier<D> identifier, D original, D update);
-
- /**
- * Method adds the DataObject which is identified by InstanceIdentifier
- * to device.
- *
- * @param identifier - the whole path to new DataObject
- * @param add - new DataObject
- */
- void add(InstanceIdentifier<D> identifier, D add);
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.netvirt.renderers.neutron;
-
-import com.google.common.base.Preconditions;
-import java.util.Collection;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ThreadFactory;
-import javax.annotation.Nonnull;
-
-import com.google.common.util.concurrent.ThreadFactoryBuilder;
-import org.opendaylight.controller.md.sal.binding.api.*;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Data-tree listener which delegates data processing to a {@link DataProcessor}.
- */
-public class DelegatingDataTreeListener<T extends DataObject> implements AutoCloseable, ClusteredDataTreeChangeListener<T> {
- private static final Logger LOG = LoggerFactory.getLogger(DelegatingDataTreeListener.class);
- protected DataBroker db;
- private static final ThreadFactory threadFactory = new ThreadFactoryBuilder()
- .setNameFormat("NV-NeutronDTL-%d").build();
- private final ExecutorService executorService = Executors.newFixedThreadPool(1, threadFactory);
- private final DataProcessor<T> dataProcessor;
- private ListenerRegistration<DelegatingDataTreeListener<T>> listenerRegistration;
-
- public DelegatingDataTreeListener(DataProcessor<T> dataProcessor,
- DataBroker db, DataTreeIdentifier<T> treeId) {
- this.dataProcessor = Preconditions.checkNotNull(dataProcessor, "Data processor can not be null!");
- registerListener(Preconditions.checkNotNull(db, "Data broker can not be null!"),
- Preconditions.checkNotNull(treeId, "Tree identifier can not be null!"));
- }
-
- private void registerListener(final DataBroker db, DataTreeIdentifier<T> treeId) {
- try {
- LOG.info("Registering Data Change Listener for {}", getClass().getSimpleName());
- this.db = db;
- listenerRegistration = db.registerDataTreeChangeListener(treeId, this);
- } catch (final Exception e) {
- LOG.warn("{} DataChange listener registration fail!", getClass().getSimpleName(), e);
- throw new IllegalStateException("DataTreeListener startup fail! System needs restart.", e);
- }
- }
-
- private void processChanges(Collection<DataTreeModification<T>> changes) {
- for (DataTreeModification<T> change : changes) {
- final InstanceIdentifier<T> key = change.getRootPath().getRootIdentifier();
- final DataObjectModification<T> mod = change.getRootNode();
- switch (mod.getModificationType()) {
- case DELETE:
- dataProcessor.remove(key, mod.getDataBefore());
- break;
- case SUBTREE_MODIFIED:
- dataProcessor.update(key, mod.getDataBefore(), mod.getDataAfter());
- break;
- case WRITE:
- if (mod.getDataBefore() == null) {
- dataProcessor.add(key, mod.getDataAfter());
- } else {
- dataProcessor.update(key, mod.getDataBefore(), mod.getDataAfter());
- }
- break;
- default:
- throw new IllegalArgumentException("Unhandled modification type " + mod.getModificationType());
- }
- }
- }
-
- @Override
- public void onDataTreeChanged(@Nonnull final Collection<DataTreeModification<T>> changes) {
- Preconditions.checkNotNull(changes, "Changes may not be null!");
- executorService.submit(new Runnable() {
- @Override
- public void run() {
- processChanges(changes);
- }
- });
- }
-
- @Override
- public void close() {
- if (listenerRegistration != null) {
- listenerRegistration.close();
- listenerRegistration = null;
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Red Hat Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.netvirt.renderers.neutron;
-
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.devices.rev151227.Devices;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.devices.rev151227.devices.Device;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.devices.rev151227.devices.DeviceKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l2.networks.rev151227.L2Networks;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l2.networks.rev151227.l2.networks.L2Network;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l2.networks.rev151227.l2.networks.L2NetworkKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.ports.rev151227.Ports;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.ports.rev151227.ports.Port;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.ports.rev151227.ports.PortKey;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-
-public class MdsalHelper {
- public static InstanceIdentifier<Port> createPortInstanceIdentifier(Uuid portUuid) {
- return InstanceIdentifier.create(Ports.class)
- .child(Port.class, new PortKey(portUuid));
- }
-
- public static InstanceIdentifier<L2Network> createL2NetworkInstanceIdentifier(Uuid networkUuid) {
- return InstanceIdentifier.create(L2Networks.class)
- .child(L2Network.class, new L2NetworkKey(networkUuid));
- }
-
- public static InstanceIdentifier<Device> createDeviceInstanceIdentifier(Uuid deviceUuid) {
- return InstanceIdentifier.create(Devices.class)
- .child(Device.class, new DeviceKey(deviceUuid));
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.netvirt.renderers.neutron;
-
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.Networks;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.networks.Network;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-
-/**
- * Data tree listener for Neutron Network
- */
-public class NeutronNetworkChangeListener extends DelegatingDataTreeListener<Network> {
- /**
- * {@link NeutronNetworkChangeListener} constructor.
- * @param db MdSal {@link DataBroker}
- */
- public NeutronNetworkChangeListener(final DataBroker db) {
- super(new NeutronNetworkDataProcessor(db), db,
- new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION,
- InstanceIdentifier.create(Neutron.class).child(Networks.class).child(Network.class)));
- }
-}
+++ /dev/null
-/*
- * Copyright © 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.netvirt.renderers.neutron;
-
-import com.google.common.base.Preconditions;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.netvirt.utils.mdsal.utils.MdsalUtils;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.common.rev151227.NetworkTypeBase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l2.networks.rev151227.l2.networks.L2Network;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l2.networks.rev151227.l2.networks.L2NetworkBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l2.networks.rev151227.l2.networks.L2NetworkKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.networks.Network;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.provider.ext.rev150712.NetworkProviderExtension;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Data processor for Neutron Network
- */
-public class NeutronNetworkDataProcessor implements DataProcessor<Network> {
- private static final Logger LOG = LoggerFactory.getLogger(NeutronNetworkDataProcessor.class);
- private final MdsalUtils mdsalUtils;
-
- /**
- *
- * @param db - mdsal
- */
- public NeutronNetworkDataProcessor(DataBroker db) {
- mdsalUtils = new MdsalUtils(db);
- }
-
- /**
- * Remove a netvirt network from mdsal
- *
- * @param identifier - the whole path to DataObject
- * @param change - port to be removed
- */
- @Override
- public void remove(final InstanceIdentifier<Network> identifier,
- final Network change) {
- Preconditions.checkNotNull(change, "Removed object can not be null!");
- LOG.debug("Delete Neutron Network model data changes for key: {} delete: {}", identifier, change);
-
- InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l2.networks.rev151227.l2.networks.L2Network> networkIid =
- MdsalHelper.createL2NetworkInstanceIdentifier(change.getUuid());
-
- LOG.debug("Remove netvirt network uuid {} from mdsal", change.getUuid());
- try {
- boolean result = mdsalUtils.delete(LogicalDatastoreType.CONFIGURATION, networkIid);
- if (result) {
- LOG.debug("Remove netvirt network from mdsal success. Result: {}", result);
- } else {
- LOG.warn("Remove nevtirt network failed. Result: {}", result);
- }
- } catch (Exception e) {
- LOG.warn("Remove netvirt network failed: exception {}", e);
- }
- }
-
- /**
- * Update a netvirt network in mdsal
- *
- * @param identifier - the whole path to DataObject
- * @param original - original DataObject (for update)
- * @param change - network to be updated
- */
-
- @Override
- public void update(final InstanceIdentifier<Network> identifier,
- final Network original, final Network change) {
- Preconditions.checkNotNull(original, "Updated original object can not be null!");
- Preconditions.checkNotNull(change, "Updated change object can not be null!");
- LOG.debug("Update Neutron Network model data changes for key: {} delete: {}", identifier, change);
- remove(identifier, original);
- add(identifier, change);
- }
-
- private void addExtensions(L2NetworkBuilder l2NetworkBuilder, Network network)
- {
- NetworkProviderExtension providerExtension = network.getAugmentation(NetworkProviderExtension.class);
- if (providerExtension != null) {
- if (providerExtension.getSegmentationId() != null) {
- l2NetworkBuilder.setSegmentationId(providerExtension.getSegmentationId());
- }
-
- if (Constants.NETVIRT_NEUTRON_NETWORK_TYPE_MAP.get(providerExtension.getNetworkType().getSimpleName()) != null) {
- l2NetworkBuilder.setNetworkType(Constants.NETVIRT_NEUTRON_NETWORK_TYPE_MAP.get(providerExtension.getNetworkType().getSimpleName()));
- } else {
- LOG.warn("Neutron Network Type not supported.. using Flat for network {}", network);
- l2NetworkBuilder.setNetworkType(NetworkTypeBase.class);
- }
- }
- }
-
- /**
- * Add a netvirt Network to mdsal
- *
- * @param identifier - the whole path to new DataObject
- * @param change - port to be added
- */
- @Override
- public void add(final InstanceIdentifier<Network> identifier,
- final Network change) {
- Preconditions.checkNotNull(change, "Added object can not be null!");
- LOG.debug("Create Neutron Network model data changes for identifier: {} change: {}", identifier, change);
- L2NetworkBuilder l2NetworkBuilder = new L2NetworkBuilder();
-
- InstanceIdentifier<L2Network> networkIid = MdsalHelper.createL2NetworkInstanceIdentifier(change.getUuid());
- addExtensions(l2NetworkBuilder, change);
-
- if (change.isAdminStateUp() != null) {
- l2NetworkBuilder.setAdminStateUp(change.isAdminStateUp());
- }
- if (change.getName() != null) {
- l2NetworkBuilder.setName(change.getName());
- }
- if (change.isShared() != null) {
- l2NetworkBuilder.setShared(change.isShared());
- }
- if (change.getStatus() != null) {
- l2NetworkBuilder.setStatus(change.getStatus());
- }
- if (change.getTenantId() != null) {
- // TODO
- //l2NetworkBuilder.setTenantId(change.getTenantId());
- }
- if (change.getUuid() != null) {
- l2NetworkBuilder.setUuid(change.getUuid());
- l2NetworkBuilder.setKey(new L2NetworkKey(change.getUuid()));
- }
-
- LOG.debug("Add Netvirt network {} to mdsal", l2NetworkBuilder.build().toString());
- try {
- boolean result = mdsalUtils.put(LogicalDatastoreType.CONFIGURATION, networkIid, l2NetworkBuilder.build());
- if (result) {
- LOG.debug("createNetwork:addToMdSal success. Result: {}", result);
- } else {
- LOG.warn("createNetwork:addToMdSal failed. Result: {}", result);
- }
- } catch (Exception e) {
- LOG.warn("create Netvirt Network : addToMdSal exception {}", e);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.netvirt.renderers.neutron;
-
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.Ports;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-
-/**
- * Data tree listener for Neutron Port
- */
-public class NeutronPortChangeListener extends DelegatingDataTreeListener<Port> {
- /**
- * {@link NeutronPortChangeListener} constructor.
- * @param db MdSal {@link DataBroker}
- */
- public NeutronPortChangeListener(final DataBroker db) {
- super(new NeutronPortDataProcessor(db), db,
- new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION,
- InstanceIdentifier.create(Neutron.class).child(Ports.class).child(Port.class)));
- }
-}
+++ /dev/null
-/*
- * Copyright © 2015, 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.netvirt.renderers.neutron;
-
-import com.google.common.base.Preconditions;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.netvirt.utils.mdsal.utils.MdsalUtils;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.ports.rev151227.PortTypeBase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.ports.rev151227.port.EndPoints;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.ports.rev151227.port.EndPointsBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.ports.rev151227.ports.PortBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.ports.rev151227.ports.PortKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.FixedIps;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Data processor for Neutron Port
- */
-public class NeutronPortDataProcessor implements DataProcessor<Port> {
- private static final Logger LOG = LoggerFactory.getLogger(NeutronPortDataProcessor.class);
- private MdsalUtils mdsalUtils;
-
- /**
- *
- * @param db - mdsal
- */
- public NeutronPortDataProcessor(DataBroker db) {
- mdsalUtils = new MdsalUtils(db);
- }
-
- /**
- * Remove a netvirt from mdsal
- *
- * @param identifier - the whole path to DataObject
- * @param change - port to be removed
- */
- @Override
- public void remove(final InstanceIdentifier<Port> identifier,
- final Port change) {
- Preconditions.checkNotNull(change, "Removed object can not be null!");
- LOG.debug("Delete Neutron Port model data changes for key: {} delete: {}", identifier, change);
-
- InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.ports.rev151227.ports.Port> portIid =
- MdsalHelper.createPortInstanceIdentifier(change.getUuid());
-
- LOG.debug("Remove netvirt Port uuid {} from mdsal", change.getUuid());
- try {
- boolean result = mdsalUtils.delete(LogicalDatastoreType.CONFIGURATION, portIid);
- if (result) {
- LOG.debug("Remove netvirt port from mdsal success. Result: {}", result);
- } else {
- LOG.warn("Remove nevtirt port failed. Result: {}", result);
- }
- } catch (Exception e) {
- LOG.warn("Remove netvirt port failed: exception {}", e);
- }
- }
-
- /**
- * Update a netvirt port in mdsal
- *
- * @param identifier - the whole path to DataObject
- * @param original - original DataObject (for update)
- * @param change - port to be updated
- */
-
- @Override
- public void update(final InstanceIdentifier<Port> identifier,
- final Port original, final Port change) {
- Preconditions.checkNotNull(original, "Updated original object can not be null!");
- Preconditions.checkNotNull(original, "Updated update object can not be null!");
- remove(identifier, original);
- LOG.debug("Update Neutron Port model data changes for key: {} delete: {}", identifier, change);
- remove(identifier, original);
- add(identifier, change);
- }
-
- /**
- * Add a netvirt port to mdsal
- *
- * @param identifier - the whole path to new DataObject
- * @param change - port to be added
- */
- @Override
- public void add(final InstanceIdentifier<Port> identifier,
- final Port change) {
- Preconditions.checkNotNull(change, "Added object can not be null!");
- LOG.debug("Create Neutron Port model data changes for identifier: {} change: {}", identifier, change);
- PortBuilder portBuilder = new PortBuilder();
-
- InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.ports.rev151227.ports.Port> portIid =
- MdsalHelper.createPortInstanceIdentifier(change.getUuid());
-
- portBuilder.setStatus(change.getStatus());
- if (change.isAdminStateUp() != null) {
- portBuilder.setAdminStateUp(change.isAdminStateUp());
- }
- portBuilder.setName(change.getName());
-
- // TODO
- // Some neutron fields to consider for netvirt model
- // tenant-id
- // network-id
- // extra-dhcp-opts list
- // fixed-ips list
- // security groups
- // vif-details list
- // vif-type
- // vnic-type
- // profile
- // port-security-enabled
- // host-id
-
- if (Constants.NETVIRT_NEUTRON_PORT_TYPE_MAP.get(change.getDeviceOwner()) != null) {
- portBuilder.setPortType(Constants.NETVIRT_NEUTRON_PORT_TYPE_MAP.get(change.getDeviceOwner()));
- } else {
- LOG.warn("Unsupported device owner for neutron port identifier: {} port: {}", identifier, change);
- portBuilder.setPortType(PortTypeBase.class);
- }
-
- // TODO - set parent when applicable
- //portB.setParent(change.getParent());
-
- portBuilder.setDeviceUuid(new Uuid(change.getDeviceId()));
- portBuilder.setDeviceLocatorUuid(change.getNetworkId());
- portBuilder.setKey(new PortKey(change.getUuid()));
-
- if (change.getFixedIps() != null) {
- List<IpAddress> ipAddressList = new ArrayList<>();
- for (FixedIps ips : change.getFixedIps()) {
- ipAddressList.add(new IpAddress(ips.getIpAddress().getValue()));
- }
- EndPoints endPoint = new EndPointsBuilder()
- .setMacaddr(new MacAddress(change.getMacAddress()))
- .setIpaddrs(ipAddressList)
- .build();
- portBuilder.setEndPoints(Collections.singletonList(endPoint));
- }
-
- LOG.debug("Add Netvirt Port {} to mdsal", portBuilder.build().toString());
- try {
- boolean result = mdsalUtils.put(LogicalDatastoreType.CONFIGURATION, portIid, portBuilder.build());
- if (result) {
- LOG.debug("createPort:addToMdSal success. Result: {}", result);
- } else {
- LOG.warn("createPort:addToMdSal failed. Result: {}", result);
- }
- } catch (Exception e) {
- LOG.warn("create Netvirt Port : addToMdSal exception {}", e);
- }
- }
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
- xmlns:odl="http://opendaylight.org/xmlns/blueprint/v1.0.0"
- odl:use-default-for-reference-types="true">
-
- <reference id="dataBroker"
- interface="org.opendaylight.controller.md.sal.binding.api.DataBroker"
- odl:type="default" />
-
- <bean id="neutronPortChangeListener"
- class="org.opendaylight.netvirt.netvirt.renderers.neutron.NeutronPortChangeListener"
- destroy-method="close">
- <argument ref="dataBroker" />
- </bean>
-
- <bean id="neutronNetworkChangeListener"
- class="org.opendaylight.netvirt.netvirt.renderers.neutron.NeutronNetworkChangeListener"
- destroy-method="close">
- <argument ref="dataBroker" />
- </bean>
-</blueprint>
\ No newline at end of file
+++ /dev/null
-package org.opendaylight.netvirt.netvirt.renderers.neutron;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-import com.google.common.base.Optional;
-import java.util.ArrayList;
-import java.util.List;
-import org.junit.Test;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.test.AbstractDataBrokerTest;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.ProviderContext;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.FixedIps;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.FixedIpsBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.Ports;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.PortBuilder;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-
-/**
- * Unit test for {@link NeutronPortDataProcessor}
- */
-public class NeutronPortDataProcessorTest extends AbstractDataBrokerTest {
- private static final Uuid portId = new Uuid("aaaaaaaa-bbbb-cccc-dddd-123456789012");
- private static final Uuid portId2 = new Uuid("11111111-2222-3333-4444-555555555555");
- private static final Uuid portId3 = new Uuid("33333333-3333-3333-3333-333333333333");
- ProviderContext session;
- NeutronPortDataProcessor neutronPortDataProcessor;
- boolean initialized = false;
-
- private org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.ports.rev151227.ports.Port readFromMdSal(Uuid uuid) throws Exception {
- InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.ports.rev151227.ports.Port> portIid =
- MdsalHelper.createPortInstanceIdentifier(uuid);
-
- Optional<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.ports.rev151227.ports.Port> data =
- getDataBroker()
- .newReadOnlyTransaction()
- .read(LogicalDatastoreType.CONFIGURATION, portIid)
- .get();
- return data.orNull();
- }
-
- private Port createNeutronPort(Uuid uuid, String name, boolean adminStateUp ) throws Exception {
- String addr = "100.100.100.100";
- List<FixedIps> ips = new ArrayList<>();
- FixedIpsBuilder fixedIpsBuilder = new FixedIpsBuilder()
- .setIpAddress(new IpAddress(addr.toCharArray()))
- .setSubnetId(new Uuid("12345678-1234-1234-1234-222222222222"));
- ips.add(fixedIpsBuilder.build());
-
-
- return (new PortBuilder()
- .setStatus("Up")
- .setAdminStateUp(adminStateUp)
- .setName(name)
- .setDeviceOwner("compute:nova")
- .setDeviceId("12345678-1234-1234-1234-123456789012")
- .setUuid(uuid)
- .setMacAddress(new MacAddress("00:00:01:02:03:04"))
- .setFixedIps(ips)
- .build());
- }
-
- private void initialize() {
- if (!initialized) {
- session = mock(ProviderContext.class);
- when(session.getSALService(DataBroker.class)).thenReturn(getDataBroker());
- neutronPortDataProcessor = new NeutronPortDataProcessor(getDataBroker());
- initialized = true;
- }
- }
-
- @Test
- public void testRemove() throws Exception {
- //Do some setup and initialization
- initialize();
-
- //Create Neutron port
- Port neutronPort = createNeutronPort(portId2, "testRemovePort", true);
- InstanceIdentifier<Port> instanceIdentifier = InstanceIdentifier.create(Ports.class).child(Port.class);
-
- //Add the Neutron port.This should result in a Netvirt port being created, and added to mdsal.
- neutronPortDataProcessor.add(instanceIdentifier, neutronPort);
-
- //Verify the Netvirt port was added to mdsal
- assertNotNull(readFromMdSal(neutronPort.getUuid()));
-
- //Delete the Netvirt port that was just put into mdsal, and verify that it was removed from mdsal.
- neutronPortDataProcessor.remove(instanceIdentifier, neutronPort);
- assertNull(readFromMdSal(neutronPort.getUuid()));
- }
-
- @Test
- public void testUpdate() throws Exception {
- //Do some setup and initialization
- initialize();
-
- //Create Neutron port
- Port neutronPort = createNeutronPort(portId3, "testUpdatePort", true);
- InstanceIdentifier<Port> instanceIdentifier = InstanceIdentifier.create(Ports.class).child(Port.class);
-
- //Add the Neutron port. This should result in a Netvirt port being created, and added to mdsal.
- neutronPortDataProcessor.add(instanceIdentifier, neutronPort);
-
- //Verify the Netvirt port was added to mdsal
- assertNotNull(readFromMdSal(neutronPort.getUuid()));
-
- //Create a second Neutron port, with different values for "name" and "AdminStateUp"
- Port neutronPort1 = createNeutronPort(portId3, "portUpdatedTest", false);
-
- //Update the Neutron port. This should result in the netvirt port in mdsal being updated, with a new name and
- //admin state
- neutronPortDataProcessor.update(instanceIdentifier, neutronPort, neutronPort1);
-
- //Verify that the netvirt port was updated in mdsal
- org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.ports.rev151227.ports.Port netvirtPort = readFromMdSal(neutronPort1.getUuid());
- assertNotNull(netvirtPort);
- assertEquals("Error, name not updated", netvirtPort.getName(), neutronPort1.getName());
- assertEquals("Error, admin state not updated", netvirtPort.isAdminStateUp(), neutronPort1.isAdminStateUp());
- }
-
- @Test
- public void testAdd() throws Exception {
- //Do some setup and initialization
- initialize();
-
- //Create Neutron port.
- Port neutronPort = createNeutronPort(portId, "testAddPort", true);
- InstanceIdentifier<Port> instanceIdentifier = InstanceIdentifier.create(Ports.class).child(Port.class);
-
- //Add the Neutron port.This should result in a Netvirt port being created, and added to mdsal.
- neutronPortDataProcessor.add(instanceIdentifier, neutronPort);
-
- //Verify that the Netvirt port was added to mdsal, and that the contents of the Netvirt port are correct.
- org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.ports.rev151227.ports.Port netvirtPort = readFromMdSal(neutronPort.getUuid());
- assertNotNull(netvirtPort);
- assertEquals("Error, status not correct", netvirtPort.getStatus(), neutronPort.getStatus());
- assertEquals("Error, name not correct", netvirtPort.getName(), neutronPort.getName());
- assertEquals("Error, admin state not correct", netvirtPort.isAdminStateUp(), neutronPort.isAdminStateUp());
- assertEquals("Error, dev id is not correct", netvirtPort.getDeviceUuid().getValue(), neutronPort.getDeviceId());
- assertEquals("Error, uuid is not correct", netvirtPort.getUuid().getValue(), neutronPort.getUuid().getValue());
- }
-
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-Copyright (c) 2015 Red Hat, Inc. and others. All rights reserved.
-This program and the accompanying materials are made available under the
-terms of the Eclipse Public License v1.0 which accompanies this distribution,
-and is available at http://www.eclipse.org/legal/epl-v10.html INTERNAL
---><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>odlparent-lite</artifactId>
- <version>2.0.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>renderers-aggregator</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <packaging>pom</packaging>
- <modelVersion>4.0.0</modelVersion>
- <modules>
- <module>hwgw</module>
- <module>neutron</module>
- </modules>
-
- <!-- DO NOT install or deploy the repo root pom as it's only needed to initiate a build -->
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-deploy-plugin</artifactId>
- <configuration>
- <skip>true</skip>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-install-plugin</artifactId>
- <configuration>
- <skip>true</skip>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
- <scm>
- <connection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</connection>
- <developerConnection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</developerConnection>
- <tag>HEAD</tag>
- <url>https://wiki.opendaylight.org/view/OVSDB_Integration:Main</url>
- </scm>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-Copyright (C) 2015 Red Hat, Inc. and others. All rights reserved.
-
-This program and the accompanying materials are made available under the
-terms of the Eclipse Public License v1.0 which accompanies this distribution,
-and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>odlparent-lite</artifactId>
- <version>2.0.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>openstack</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <packaging>pom</packaging>
- <description>The OVSDB Plugin integration project is a project for OpenDaylight that will implement the Open vSwitch Database RFC 7047 management protocol allowing the Southbound configuration of vSwitches and a network virtualization implementation.</description>
- <licenses>
- <license>
- <name>Eclipse Public License v1.0</name>
- <url>http://www.eclipse.org/legal/epl-v10.html</url>
- </license>
- </licenses>
- <developers>
- <developer>
- <name>Sam Hague</name>
- <email>shague@gmail.com</email>
- <url>https://github.com/shague</url>
- </developer>
- </developers>
- <scm>
- <connection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</connection>
- <developerConnection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</developerConnection>
- <tag>HEAD</tag>
- <url>https://wiki.opendaylight.org/view/OVSDB_Integration:Main</url>
- </scm>
-
- <modules>
- <module>commons</module>
- <module>features</module>
- <module>karaf</module>
- <module>netvirt-artifacts</module>
- <module>utils</module>
- <module>net-virt</module>
- <module>net-virt-it</module>
- <module>net-virt-providers</module>
- <module>net-virt-sfc</module>
- <module>sfc-translator</module>
- </modules>
-
- <!-- DO NOT install or deploy the repo root pom as it's only needed to initiate a build -->
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-deploy-plugin</artifactId>
- <configuration>
- <skip>true</skip>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-install-plugin</artifactId>
- <configuration>
- <skip>true</skip>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
-
- This program and the accompanying materials are made available under the
- terms of the Eclipse Public License v1.0 which accompanies this distribution,
- and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>odlparent-lite</artifactId>
- <version>2.0.0</version>
- <relativePath/>
- </parent>
-
- <modelVersion>4.0.0</modelVersion>
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>openstack.sfc-translator-artifacts</artifactId>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>pom</packaging>
-
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>openstack.sfc-translator-impl</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>openstack.sfc-translator-features</artifactId>
- <version>${project.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- </dependencies>
- </dependencyManagement>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright © 2017 Red Hat, Inc. and others.
-
- 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
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>single-feature-parent</artifactId>
- <version>1.9.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>odl-netvirt-openstack-sfc-translator-rest</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>feature</packaging>
-
- <name>OpenStack SFC to OpenDaylight SFC API data translator with RestConf</name>
-
- <dependencies>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-netvirt-openstack-sfc-translator</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.netconf</groupId>
- <artifactId>odl-restconf</artifactId>
- <version>1.6.0-SNAPSHOT</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- </dependencies>
-</project>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright © 2017 Red Hat, Inc. and others.
-
- 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
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>single-feature-parent</artifactId>
- <version>1.9.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>odl-netvirt-openstack-sfc-translator</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>feature</packaging>
-
- <name>OpenStack SFC to OpenDaylight SFC API data translator</name>
-
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>odl-mdsal-broker</artifactId>
- <version>1.6.0-SNAPSHOT</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.neutron</groupId>
- <artifactId>odl-neutron-service</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.sfc</groupId>
- <artifactId>odl-sfc-provider</artifactId>
- <version>0.6.0-SNAPSHOT</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-ovsdb-sfc-api</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>utils.mdsal-utils</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>openstack.sfc-translator-impl</artifactId>
- <version>${project.version}</version>
- </dependency>
- </dependencies>
-</project>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright © 2017 Red Hat, Inc. and others.
-
- 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
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>odlparent-lite</artifactId>
- <version>2.0.0</version>
- <relativePath/>
- </parent>
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>openstack.sfc-translator-features-aggregator</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <packaging>pom</packaging>
-
- <modules>
- <module>sfc-translator-features</module>
- <module>sfc-translator-features4</module>
- <module>odl-netvirt-openstack-sfc-translator</module>
- <module>odl-netvirt-openstack-sfc-translator-rest</module>
- </modules>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
-
- This program and the accompanying materials are made available under the
- terms of the Eclipse Public License v1.0 which accompanies this distribution,
- and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>features-parent</artifactId>
- <version>1.9.0</version>
- <relativePath/>
- </parent>
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>openstack.sfc-translator-features</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <modelVersion>4.0.0</modelVersion>
- <properties>
- <configfile.directory>etc/opendaylight/karaf</configfile.directory>
- <neutron.version>0.9.0-SNAPSHOT</neutron.version>
- <controller.mdsal.version>1.6.0-SNAPSHOT</controller.mdsal.version>
- <dlux.version>0.6.0-SNAPSHOT</dlux.version>
- <mdsal.model.version>0.11.0-SNAPSHOT</mdsal.model.version>
- <restconf.version>1.6.0-SNAPSHOT</restconf.version>
- <sfc.version>0.6.0-SNAPSHOT</sfc.version>
- </properties>
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.dlux</groupId>
- <artifactId>features-dlux</artifactId>
- <classifier>features</classifier>
- <version>${dlux.version}</version>
- <type>xml</type>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>features-mdsal</artifactId>
- <version>${controller.mdsal.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>features-mdsal-model</artifactId>
- <version>${mdsal.model.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.netconf</groupId>
- <artifactId>features-restconf</artifactId>
- <version>${restconf.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.neutron</groupId>
- <artifactId>features-neutron</artifactId>
- <version>${neutron.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>features-netvirt</artifactId>
- <version>${project.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>openstack.net-virt-sfc-features</artifactId>
- <version>${project.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.sfc</groupId>
- <artifactId>features-sfc</artifactId>
- <version>${sfc.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>openstack.sfc-translator-impl</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>utils.mdsal-utils</artifactId>
- <version>${project.version}</version>
- </dependency>
- </dependencies>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- vi: set et smarttab sw=4 tabstop=4: -->
-<!--
- Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
-
- This program and the accompanying materials are made available under the
- terms of the Eclipse Public License v1.0 which accompanies this distribution,
- and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-<features name="odl-ovsdb-sfc-${project.version}" xmlns="http://karaf.apache.org/xmlns/features/v1.2.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://karaf.apache.org/xmlns/features/v1.2.0 http://karaf.apache.org/xmlns/features/v1.2.0">
- <repository>mvn:org.opendaylight.controller/features-mdsal/{{VERSION}}/xml/features</repository>
- <repository>mvn:org.opendaylight.mdsal.model/features-mdsal-model/{{VERSION}}/xml/features</repository>
- <repository>mvn:org.opendaylight.netconf/features-restconf/{{VERSION}}/xml/features</repository>
- <repository>mvn:org.opendaylight.neutron/features-neutron/{{VERSION}}/xml/features</repository>
- <repository>mvn:org.opendaylight.sfc/features-sfc/{{VERSION}}/xml/features</repository>
- <repository>mvn:org.opendaylight.netvirt/features-netvirt/{{VERSION}}/xml/features</repository>
- <repository>mvn:org.opendaylight.netvirt/openstack.net-virt-sfc-features/{{VERSION}}/xml/features</repository>
- <feature name='odl-netvirt-openstack-sfc-translator' version='${project.version}'
- description=''>
- <feature version='${controller.mdsal.version}'>odl-mdsal-broker</feature>
- <feature version="${neutron.version}">odl-neutron-service</feature>
- <feature version='${sfc.version}'>odl-sfc-provider</feature>
- <feature version='${project.version}'>odl-ovsdb-sfc-api</feature>
- <bundle>mvn:org.opendaylight.netvirt/utils.mdsal-utils/{{VERSION}}</bundle>
- <bundle>mvn:org.opendaylight.netvirt/openstack.sfc-translator-impl/{{VERSION}}</bundle>
- </feature>
- <feature name='odl-netvirt-openstack-sfc-translator-rest' version='${project.version}'
- description='OpenStack SFC to OpenDaylight SFC API data translator with RestConf'>
- <feature version="${project.version}">odl-netvirt-openstack-sfc-translator</feature>
- <feature version="${restconf.version}">odl-restconf</feature>
- </feature>
-</features>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright © 2017 Red Hat, Inc. and others.
-
- 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
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>feature-repo-parent</artifactId>
- <version>1.9.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>openstack.sfc-translator-features4</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>feature</packaging>
-
- <name>ODL :: netvirt :: ${project.artifactId}</name>
-
- <dependencies>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-netvirt-openstack-sfc-translator</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-netvirt-openstack-sfc-translator-rest</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- </dependencies>
-</project>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- vi: set et smarttab sw=4 tabstop=4: -->
-<!--
- Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
-
- This program and the accompanying materials are made available under the
- terms of the Eclipse Public License v1.0 which accompanies this distribution,
- and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
-
- <parent>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-parent</artifactId>
- <version>0.7.0-SNAPSHOT</version>
- <relativePath/>
- </parent>
-
- <modelVersion>4.0.0</modelVersion>
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>openstack.sfc-translator-impl</artifactId>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>bundle</packaging>
-
- <description>
- This project provide a translation layer that converts OpenStack SFC API's neutron northbound yang model
- to OpenDaylight SFC yang models.
- </description>
- <licenses>
- <license>
- <name>Eclipse Public License v1.0</name>
- <url>http://www.eclipse.org/legal/epl-v10.html</url>
- </license>
- </licenses>
- <developers>
- <developer>
- <name>Anil Vishnoi</name>
- <email>vishnoianil@gmail.com</email>
- </developer>
- </developers>
-
- <properties>
- <neutron.model.version>0.9.0-SNAPSHOT</neutron.model.version>
- <sfc.version>0.6.0-SNAPSHOT</sfc.version>
- </properties>
-
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>ietf-topology</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>ietf-packet-fields</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>iana-if-type-2014-05-08</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.neutron</groupId>
- <artifactId>model</artifactId>
- <version>${neutron.model.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.sfc</groupId>
- <artifactId>sfc-model</artifactId>
- <version>${sfc.version}</version>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-simple</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>openstack.net-virt-sfc-api</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>utils.mdsal-utils</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-core</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <extensions>true</extensions>
- <configuration>
- <instructions>
- <Embed-Transitive>true</Embed-Transitive>
- <Export-Package>
- </Export-Package>
- </instructions>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <!--<propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>-->
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
- <configuration>
- <properties>
- <property>
- <name>listener</name>
- <value>org.sonar.java.jacoco.JUnitListener</value>
- </property>
- </properties>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-/*
- * Copyright (c) 2013, 2016 Dell, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.sfc.translator;
-
-import com.google.common.base.Preconditions;
-import com.google.common.util.concurrent.ThreadFactoryBuilder;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
-import org.opendaylight.controller.md.sal.binding.api.DataTreeChangeListener;
-import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
-import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.annotation.Nonnull;
-import java.util.Collection;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ThreadFactory;
-
-/**
- * Data-tree listener which delegates data processing to a {@link INeutronSfcDataProcessor}.
- */
-public abstract class DelegatingDataTreeListener<T extends DataObject> implements AutoCloseable,
- DataTreeChangeListener<T>,
- INeutronSfcDataProcessor<T> {
- private static final Logger LOG = LoggerFactory.getLogger(DelegatingDataTreeListener.class);
- private static final ThreadFactory threadFactory = new ThreadFactoryBuilder()
- .setNameFormat("NeutronSfcListener-%d").build();
- private final ExecutorService executorService = Executors.newFixedThreadPool(1, threadFactory);
- private final INeutronSfcDataProcessor<T> dataProcessor;
- private ListenerRegistration<DelegatingDataTreeListener<T>> listenerRegistration;
-
- public DelegatingDataTreeListener(DataBroker db, DataTreeIdentifier<T> treeId) {
- this.dataProcessor = Preconditions.checkNotNull(this, "Data processor can not be null!");
- registerListener(Preconditions.checkNotNull(db, "Data broker can not be null!"),
- Preconditions.checkNotNull(treeId, "Tree identifier can not be null!"));
- }
-
- private void registerListener(final DataBroker db, DataTreeIdentifier<T> treeId) {
- try {
- LOG.info("Registering Data Change Listener for {}", getClass().getSimpleName());
- listenerRegistration = db.registerDataTreeChangeListener(treeId, this);
- } catch (final Exception e) {
- LOG.warn("{} DataChange listener registration fail!", getClass().getSimpleName(), e);
- throw new IllegalStateException("DataTreeListener startup fail! System needs restart.", e);
- }
- }
-
- private void processChanges(Collection<DataTreeModification<T>> changes) {
- LOG.info("onDataTreeChanged: Received Data Tree Changed {}", changes);
- for (DataTreeModification<T> change : changes) {
- final InstanceIdentifier<T> key = change.getRootPath().getRootIdentifier();
- final DataObjectModification<T> mod = change.getRootNode();
- LOG.info("onDataTreeChanged: Received Data Tree Changed Update of Type={} for Key={}",
- mod.getModificationType(), key);
- switch (mod.getModificationType()) {
- case DELETE:
- dataProcessor.remove(key, mod.getDataBefore());
- break;
- case SUBTREE_MODIFIED:
- dataProcessor.update(key, mod.getDataBefore(), mod.getDataAfter());
- break;
- case WRITE:
- if (mod.getDataBefore() == null) {
- dataProcessor.add(key, mod.getDataAfter());
- } else {
- dataProcessor.update(key, mod.getDataBefore(), mod.getDataAfter());
- }
- break;
- default:
- throw new IllegalArgumentException("Unhandled modification type " + mod.getModificationType());
- }
- }
- }
-
- @Override
- public void onDataTreeChanged(@Nonnull final Collection<DataTreeModification<T>> changes) {
- Preconditions.checkNotNull(changes, "Changes may not be null!");
- executorService.submit(() -> processChanges(changes));
- }
-
- @Override
- public void close() {
- if (listenerRegistration != null) {
- listenerRegistration.close();
- listenerRegistration = null;
- }
- if (executorService != null) {
- executorService.shutdownNow();
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2016 Dell, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.sfc.translator;
-
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-
-/**
- * Neutron SFC yang model processor
- */
-public interface INeutronSfcDataProcessor<D extends DataObject> {
-
- /**
- * Method removes DataObject which is identified by InstanceIdentifier.
- *
- * @param identifier - the whole path to DataObject
- * @param del - DataObject for removing
- */
- void remove(InstanceIdentifier<D> identifier, D del);
-
- /**
- * Method updates the original DataObject to the update DataObject.
- * Both are identified by same InstanceIdentifier.
- *
- * @param identifier - the whole path to DataObject
- * @param original - original DataObject (for update)
- * @param update - changed DataObject (contain updates)
- */
- void update(InstanceIdentifier<D> identifier, D original, D update);
-
- /**
- * Method adds the DataObject which is identified by InstanceIdentifier
- * to device.
- *
- * @param identifier - the whole path to new DataObject
- * @param add - new DataObject
- */
- void add(InstanceIdentifier<D> identifier, D add);
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.sfc.translator;
-
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.netvirt.utils.mdsal.utils.MdsalUtils;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.Ports;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.PortKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.sfc.flow.classifier.rev160511.sfc.flow.classifiers.attributes.SfcFlowClassifiers;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.sfc.flow.classifier.rev160511.sfc.flow.classifiers.attributes.sfc.flow.classifiers.SfcFlowClassifier;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.sfc.flow.classifier.rev160511.sfc.flow.classifiers.attributes.sfc.flow.classifiers.SfcFlowClassifierKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.sfc.rev160511.sfc.attributes.PortPairGroups;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.sfc.rev160511.sfc.attributes.PortPairs;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.sfc.rev160511.sfc.attributes.port.pair.groups.PortPairGroup;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.sfc.rev160511.sfc.attributes.port.pair.groups.PortPairGroupKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.sfc.rev160511.sfc.attributes.port.pairs.PortPair;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.sfc.rev160511.sfc.attributes.port.pairs.PortPairKey;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Utility functions to read Neutron models (e.g network, subnet, port, sfc flow classifier
- * port pair, port group, port chain) from md-sal data store.
- */
-public class NeutronMdsalHelper {
- private static final Logger LOG = LoggerFactory.getLogger(NeutronMdsalHelper.class);
- private static final InstanceIdentifier<SfcFlowClassifiers> fcIid =
- InstanceIdentifier.create(Neutron.class).child(SfcFlowClassifiers.class);
- private static final InstanceIdentifier<Ports> portsIid =
- InstanceIdentifier.create(Neutron.class).child(Ports.class);
- private static final InstanceIdentifier<PortPairs> portPairsIid =
- InstanceIdentifier.create(Neutron.class).child(PortPairs.class);
- private static final InstanceIdentifier<PortPairGroups> portPairGroupsIid =
- InstanceIdentifier.create(Neutron.class).child(PortPairGroups.class);
-
- private final DataBroker dataBroker;
- private final MdsalUtils mdsalUtils;
-
- public NeutronMdsalHelper(DataBroker dataBroker) {
- this.dataBroker = dataBroker;
- mdsalUtils = new MdsalUtils(this.dataBroker);
- }
-
- public Port getNeutronPort(Uuid portId) {
- Port neutronPort = mdsalUtils.read(LogicalDatastoreType.CONFIGURATION , getNeutronPortPath(portId));
- return neutronPort;
- }
-
- public PortPair getNeutronPortPair(Uuid portPairId) {
- PortPair neutronPortPair
- = mdsalUtils.read(LogicalDatastoreType.CONFIGURATION , getNeutronPortPairPath(portPairId));
- return neutronPortPair;
- }
-
- public PortPairGroup getNeutronPortPairGroup(Uuid portPairGroupId) {
- PortPairGroup neutronPortPairGroup
- = mdsalUtils.read(LogicalDatastoreType.CONFIGURATION , getNeutronPortPairGroupPath(portPairGroupId));
- return neutronPortPairGroup;
- }
-
- public SfcFlowClassifier getNeutronFlowClassifier(Uuid flowClassifierId) {
- SfcFlowClassifier sfcFlowClassifier
- = mdsalUtils.read(LogicalDatastoreType.CONFIGURATION , getNeutronSfcFlowClassifierPath(flowClassifierId));
- return sfcFlowClassifier;
- }
-
- private InstanceIdentifier<Port> getNeutronPortPath(Uuid portId) {
- return portsIid.builder().child(Port.class, new PortKey(portId)).build();
- }
-
- private InstanceIdentifier<PortPair> getNeutronPortPairPath(Uuid portPairId) {
- return portPairsIid.builder().child(PortPair.class, new PortPairKey(portPairId)).build();
- }
-
- private InstanceIdentifier<PortPairGroup> getNeutronPortPairGroupPath(Uuid portPairGroupId) {
- return portPairGroupsIid.builder().child(PortPairGroup.class, new PortPairGroupKey(portPairGroupId)).build();
- }
-
- private InstanceIdentifier<SfcFlowClassifier> getNeutronSfcFlowClassifierPath(Uuid portId) {
- return fcIid.builder().child(SfcFlowClassifier.class, new SfcFlowClassifierKey(portId)).build();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.openstack.sfc.translator;
-
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.netvirt.openstack.sfc.translator.flowclassifier.NeutronFlowClassifierListener;
-import org.opendaylight.netvirt.openstack.sfc.translator.portchain.NeutronPortChainListener;
-import org.opendaylight.netvirt.openstack.sfc.translator.portchain.NeutronPortPairGroupListener;
-import org.opendaylight.netvirt.openstack.sfc.translator.portchain.NeutronPortPairListener;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.RenderedServicePathService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.openstack.sfc.translator.config.rev160720.OpenstackSfcTranslatorConfig;
-import org.osgi.framework.BundleContext;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class OpenStackSFCTranslatorProvider implements AutoCloseable {
- private static final Logger LOG = LoggerFactory.getLogger(OpenStackSFCTranslatorProvider.class);
-
- private static BundleContext bundleContext;
- private final DataBroker dataBroker;
- private final RenderedServicePathService rspService;
- private final OpenstackSfcTranslatorConfig openstackSfcTranslatorConfig;
-
- public OpenStackSFCTranslatorProvider(
- final DataBroker dataBroker,
- final RenderedServicePathService rspService,
- final OpenstackSfcTranslatorConfig openstackSfcTranslatorConfig,
- BundleContext bundleContext) {
- this.dataBroker = dataBroker;
- this.rspService = rspService;
- this.openstackSfcTranslatorConfig = openstackSfcTranslatorConfig;
- this.bundleContext = bundleContext;
- }
-
- //This method will be called by blueprint, during bundle initialization.
- public void start() {
- LOG.info("OpenStack SFC Translator Session started");
- new NeutronFlowClassifierListener(dataBroker);
- new NeutronPortPairListener(dataBroker);
- new NeutronPortPairGroupListener(dataBroker);
- new NeutronPortChainListener(dataBroker, rspService);
- if (this.rspService == null) {
- LOG.warn("RenderedServicePath Service is not available. Translation layer might not work as expected.");
- }
- }
-
- @Override
- public void close() throws Exception {
- LOG.info("OpenStack SFC Translator Closed");
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.sfc.translator;
-
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.netvirt.utils.mdsal.utils.MdsalUtils;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeRef;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbTerminationPointAugmentation;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.InterfaceExternalIds;
-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.TopologyId;
-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.NodeKey;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPoint;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.List;
-
-/**
- * Utility methods to read OpenDaylight OVSDB models.
- */
-public class OvsdbMdsalHelper {
- private static final Logger LOG = LoggerFactory.getLogger(SfcMdsalHelper.class);
- private static final String OVSDB_TOPOLOGY_ID = "ovsdb:1";
- private static final InstanceIdentifier<Topology> topologyPath
- = InstanceIdentifier.create(NetworkTopology.class)
- .child(Topology.class, new TopologyKey(new TopologyId(OVSDB_TOPOLOGY_ID)));
-
- private final DataBroker dataBroker;
- private final MdsalUtils mdsalUtils;
-
- public OvsdbMdsalHelper(DataBroker dataBroker) {
- this.dataBroker = dataBroker;
- mdsalUtils = new MdsalUtils(this.dataBroker);
- }
-
- public Topology getOvsdbTopologyTree() {
- LOG.info("Reading OVSDB Topolog Tree (ovsdb:1)");
- return mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, topologyPath);
- }
-
- public OvsdbPortMetadata getOvsdbPortMetadata(Uuid ingressPort) {
- LOG.info("Extract ovsdb port details for neutron port {}", ingressPort.getValue());
- Topology ovsdbTopology = mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, topologyPath);
- return getOvsdbPortMetadata(ingressPort, ovsdbTopology);
- }
- public OvsdbPortMetadata getOvsdbPortMetadata(Uuid ingressPort, Topology ovsdbTopology) {
- LOG.debug("Extract ovsdb port details for neutron port {} from Topology {}",
- ingressPort.getValue(), ovsdbTopology);
- OvsdbPortMetadata ovsdbPortMetadata = new OvsdbPortMetadata();
- OvsdbBridgeAugmentation bridgeAugmentation = null;
- if (ovsdbTopology != null) {
- List<Node> nodes = ovsdbTopology.getNode();
- for (Node node : nodes) {
- if (node.getTerminationPoint() != null) {
- for (TerminationPoint tp : node.getTerminationPoint()) {
- OvsdbTerminationPointAugmentation tpAugmentation
- = tp.getAugmentation(OvsdbTerminationPointAugmentation.class);
- List<InterfaceExternalIds> externalIds = tpAugmentation.getInterfaceExternalIds();
- if (externalIds != null ) {
- for (InterfaceExternalIds externalId : externalIds) {
- if(externalId.getExternalIdValue().equals(ingressPort.getValue())) {
- LOG.info("OVSDB port found for neutron port {} : {}", ingressPort, tpAugmentation);
- ovsdbPortMetadata.setOvsdbPort(tpAugmentation);
- break;
- }
- }
- if (ovsdbPortMetadata.getOvsdbPort() != null) {
- break;
- }
- }
- }
- }
- if (ovsdbPortMetadata.getOvsdbPort() != null) {
- bridgeAugmentation = node.getAugmentation(OvsdbBridgeAugmentation.class);
- if (bridgeAugmentation != null) {
- ovsdbPortMetadata.setOvsdbBridgeNode(bridgeAugmentation);
- } else {
- LOG.warn("Brige augmentation is not present " +
- "for the termination point {}",ovsdbPortMetadata.getOvsdbPort());
- return null;
- }
- break;
- }
- }
- OvsdbNodeRef ovsdbNode = bridgeAugmentation.getManagedBy();
- if (ovsdbNode != null) {
- NodeKey ovsdbNodeKey = ovsdbNode.getValue().firstKeyOf(Node.class);
- for (Node node : nodes) {
- if(node.getKey().equals(ovsdbNodeKey)) {
- OvsdbNodeAugmentation nodeAugmentation = node.getAugmentation(OvsdbNodeAugmentation.class);
- ovsdbPortMetadata.setOvsdbNode(nodeAugmentation);
- break;
- }
- }
- } else {
- LOG.warn("Ovsdb Node not found for ovsdb bridge {}",bridgeAugmentation);
- }
-
- } else {
- LOG.warn("OVSDB Operational topology not avaialble.");
- }
- LOG.info("Neutron port's {} respective Ovsdb metadata {}", ingressPort, ovsdbPortMetadata);
- return ovsdbPortMetadata;
- }
-
- public static String getOvsdbPortName(OvsdbTerminationPointAugmentation ovsdbPort) {
- return ovsdbPort.getName();
- }
-
- public static String getNodeIpAddress(OvsdbNodeAugmentation ovsdbNode) {
- //Currently we support only ipv4
- return ovsdbNode.getConnectionInfo().getRemoteIp().getIpv4Address().getValue();
- }
-
- public static String getNodeKey(InstanceIdentifier<?> node) {
- return node.firstKeyOf(Node.class).getNodeId().getValue();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.sfc.translator;
-
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbTerminationPointAugmentation;
-
-public class OvsdbPortMetadata {
- private OvsdbTerminationPointAugmentation ovsdbPort;
- private OvsdbNodeAugmentation ovsdbNode;
- private OvsdbBridgeAugmentation ovsdbBridgeNode;
-
- public OvsdbPortMetadata() {
-
- }
-
- public OvsdbBridgeAugmentation getOvsdbBridgeNode() {
- return ovsdbBridgeNode;
- }
-
- public void setOvsdbBridgeNode(OvsdbBridgeAugmentation ovsdbBridgeNode) {
- this.ovsdbBridgeNode = ovsdbBridgeNode;
- }
-
- public OvsdbNodeAugmentation getOvsdbNode() {
- return ovsdbNode;
- }
-
- public void setOvsdbNode(OvsdbNodeAugmentation ovsdbNode) {
- this.ovsdbNode = ovsdbNode;
- }
-
- public OvsdbTerminationPointAugmentation getOvsdbPort() {
- return ovsdbPort;
- }
-
- public void setOvsdbPort(OvsdbTerminationPointAugmentation ovsdbPort) {
- this.ovsdbPort = ovsdbPort;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.sfc.translator;
-
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.netvirt.utils.mdsal.utils.MdsalUtils;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sf.rev140701.ServiceFunctions;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sf.rev140701.service.functions.ServiceFunction;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sf.rev140701.service.functions.ServiceFunctionKey;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfc.rev140701.ServiceFunctionChains;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfc.rev140701.service.function.chain.grouping.ServiceFunctionChain;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfc.rev140701.service.function.chain.grouping.ServiceFunctionChainKey;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.ServiceFunctionForwarders;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.service.function.forwarders.ServiceFunctionForwarder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.service.function.forwarders.ServiceFunctionForwarderKey;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfp.rev140701.ServiceFunctionPaths;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfp.rev140701.service.function.paths.ServiceFunctionPath;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfp.rev140701.service.function.paths.ServiceFunctionPathKey;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.AccessLists;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.Acl;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.AclKey;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.List;
-
-/**
- * Utility methods to read OpenDaylight SFC models.
- */
-public class SfcMdsalHelper {
- private static final Logger LOG = LoggerFactory.getLogger(SfcMdsalHelper.class);
- private static InstanceIdentifier<AccessLists> accessListIid = InstanceIdentifier.create(AccessLists.class);
- private static InstanceIdentifier<ServiceFunctions> sfIid = InstanceIdentifier.create(ServiceFunctions.class);
- private static InstanceIdentifier<ServiceFunctionForwarders> sffIid =
- InstanceIdentifier.create(ServiceFunctionForwarders.class);
- private static InstanceIdentifier<ServiceFunctionChains> sfcIid =
- InstanceIdentifier.create(ServiceFunctionChains.class);
- private static InstanceIdentifier<ServiceFunctionPaths> sfpIid
- = InstanceIdentifier.create(ServiceFunctionPaths.class);
-
- private final DataBroker dataBroker;
- private final MdsalUtils mdsalUtils;
-
- public SfcMdsalHelper(DataBroker dataBroker) {
- this.dataBroker = dataBroker;
- mdsalUtils = new MdsalUtils(this.dataBroker);
- }
-
- //ACL Flow Classifier data store utility methods
- public void addAclFlowClassifier(Acl aclFlowClassifier) {
- InstanceIdentifier<Acl> aclIid = getAclPath(aclFlowClassifier.getKey());
- LOG.info("Write ACL FlowClassifier {} to config data store at {}",aclFlowClassifier, aclIid);
- mdsalPutWrapper(LogicalDatastoreType.CONFIGURATION, aclIid, aclFlowClassifier);
- }
-
- public void updateAclFlowClassifier(Acl aclFlowClassifier) {
- InstanceIdentifier<Acl> aclIid = getAclPath(aclFlowClassifier.getKey());
- LOG.info("Update ACL FlowClassifier {} in config data store at {}",aclFlowClassifier, aclIid);
- mdsalUtils.merge(LogicalDatastoreType.CONFIGURATION, aclIid, aclFlowClassifier);
- }
-
- public void removeAclFlowClassifier(Acl aclFlowClassifier) {
- InstanceIdentifier<Acl> aclIid = getAclPath(aclFlowClassifier.getKey());
- LOG.info("Remove ACL FlowClassifier {} from config data store at {}",aclFlowClassifier, aclIid);
- mdsalUtils.delete(LogicalDatastoreType.CONFIGURATION, aclIid);
- }
-
- //Service Function
- public ServiceFunction readServiceFunction(ServiceFunctionKey sfKey) {
- InstanceIdentifier<ServiceFunction> sfIid = getSFPath(sfKey);
- LOG.info("Read Service Function {} from config data store at {}",sfKey, sfIid);
- return mdsalUtils.read(LogicalDatastoreType.CONFIGURATION, sfIid);
- }
-
- public void addServiceFunction(ServiceFunction sf) {
- InstanceIdentifier<ServiceFunction> sfIid = getSFPath(sf.getKey());
- LOG.info("Write Service Function {} to config data store at {}",sf, sfIid);
- mdsalPutWrapper(LogicalDatastoreType.CONFIGURATION, sfIid, sf);
- }
-
- public void updateServiceFunction(ServiceFunction sf) {
- InstanceIdentifier<ServiceFunction> sfIid = getSFPath(sf.getKey());
- LOG.info("Update Service Function {} in config data store at {}",sf, sfIid);
- mdsalUtils.merge(LogicalDatastoreType.CONFIGURATION, sfIid, sf);
- }
-
- public void removeServiceFunction(ServiceFunctionKey sfKey) {
- InstanceIdentifier<ServiceFunction> sfIid = getSFPath(sfKey);
- LOG.info("Remove Service Function {} from config data store at {}",sfKey, sfIid);
- mdsalUtils.delete(LogicalDatastoreType.CONFIGURATION, sfIid);
- }
-
- //Service Function Forwarder
- public ServiceFunctionForwarder readServiceFunctionForwarder(ServiceFunctionForwarderKey sffKey) {
- InstanceIdentifier<ServiceFunctionForwarder> sffIid = getSFFPath(sffKey);
- LOG.info("Read Service Function Forwarder from config data store at {}", sffIid);
- return mdsalUtils.read(LogicalDatastoreType.CONFIGURATION, sffIid);
- }
-
- public void addServiceFunctionForwarder(ServiceFunctionForwarder sff) {
- InstanceIdentifier<ServiceFunctionForwarder> sffIid = getSFFPath(sff.getKey());
- LOG.info("Write Service Function Forwarder {} to config data store at {}",sff, sffIid);
- mdsalPutWrapper(LogicalDatastoreType.CONFIGURATION, sffIid, sff);
- }
-
- public void deleteServiceFunctionForwarder(ServiceFunctionForwarderKey sffKey) {
- InstanceIdentifier<ServiceFunctionForwarder> sffIid = getSFFPath(sffKey);
- LOG.info("Delete Service Function Forwarder from config data store at {}", sffIid);
- mdsalUtils.delete(LogicalDatastoreType.CONFIGURATION, sffIid);
- }
-
- public void addServiceFunctionChain(ServiceFunctionChain sfc) {
- InstanceIdentifier<ServiceFunctionChain> sfcIid = getSFCPath(sfc.getKey());
- LOG.info("Write Service Function Chain {} to config data store at {}",sfc, sfcIid);
- mdsalPutWrapper(LogicalDatastoreType.CONFIGURATION, sfcIid, sfc);
- }
-
- public void deleteServiceFunctionChain(ServiceFunctionChainKey sfcKey) {
- InstanceIdentifier<ServiceFunctionChain> sfcIid = getSFCPath(sfcKey);
- LOG.info("Remove Service Function Chain {} from config data store at {}",sfcKey, sfcIid);
- mdsalUtils.delete(LogicalDatastoreType.CONFIGURATION, sfcIid);
- }
-
- public void addServiceFunctionPath(ServiceFunctionPath sfp) {
- InstanceIdentifier<ServiceFunctionPath> sfpIid = getSFPPath(sfp.getKey());
- LOG.info("Write Service Function Path {} to config data store at {}",sfp, sfpIid);
- mdsalPutWrapper(LogicalDatastoreType.CONFIGURATION, sfpIid, sfp);
- }
-
- public void deleteServiceFunctionPath(ServiceFunctionPathKey sfpKey) {
- InstanceIdentifier<ServiceFunctionPath> sfpIid = getSFPPath(sfpKey);
- LOG.info("Delete Service Function Path from config data store at {}", sfpIid);
- mdsalUtils.delete(LogicalDatastoreType.CONFIGURATION, sfpIid);
- }
-
- private InstanceIdentifier<Acl> getAclPath(AclKey aclKey) {
- return accessListIid.builder().child(Acl.class, aclKey).build();
- }
-
- private InstanceIdentifier<ServiceFunction> getSFPath(ServiceFunctionKey key) {
- return sfIid.builder().child(ServiceFunction.class, key).build();
- }
-
- private InstanceIdentifier<ServiceFunctionForwarder> getSFFPath(ServiceFunctionForwarderKey key) {
- return sffIid.builder().child(ServiceFunctionForwarder.class, key).build();
- }
-
- private InstanceIdentifier<ServiceFunctionChain> getSFCPath(ServiceFunctionChainKey key) {
- return sfcIid.builder().child(ServiceFunctionChain.class, key).build();
- }
-
- private InstanceIdentifier<ServiceFunctionPath> getSFPPath(ServiceFunctionPathKey key) {
- return sfpIid.builder().child(ServiceFunctionPath.class, key).build();
- }
-
- public ServiceFunctionForwarder getExistingSFF(String ipAddress) {
- ServiceFunctionForwarders existingSffs = mdsalUtils.read(LogicalDatastoreType.CONFIGURATION, sffIid);
- if (existingSffs != null
- && existingSffs.getServiceFunctionForwarder() != null
- && !existingSffs.getServiceFunctionForwarder().isEmpty()) {
-
- List<ServiceFunctionForwarder> existingSffList = existingSffs.getServiceFunctionForwarder();
- for (ServiceFunctionForwarder sff : existingSffList) {
- if (sff.getIpMgmtAddress().getIpv4Address().equals(new Ipv4Address(ipAddress))) {
- return sff;
- }
- }
- }
- return null;
- }
-
- private <D extends DataObject> void mdsalPutWrapper(LogicalDatastoreType dataStore, InstanceIdentifier<D> iid, D data) {
- try {
- mdsalUtils.put(dataStore, iid, data);
- } catch (Exception e) {
- LOG.error("Exception while putting data in data store {} : {}",iid, data, e);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.sfc.translator.flowclassifier;
-
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.Ipv4Acl;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.Ipv6Acl;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.Acl;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.AclBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.AclKey;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.AccessListEntriesBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.Ace;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.AceBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.AceKey;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.ActionsBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.MatchesBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.matches.ace.type.AceIpBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.matches.ace.type.ace.ip.ace.ip.version.AceIpv4Builder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.matches.ace.type.ace.ip.ace.ip.version.AceIpv6Builder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpPrefix;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.packet.fields.rev160218.acl.transport.header.fields.DestinationPortRangeBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.packet.fields.rev160218.acl.transport.header.fields.SourcePortRangeBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeV4;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeV6;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolTcp;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolUdp;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.sfc.flow.classifier.rev160511.sfc.flow.classifiers.attributes.sfc.flow.classifiers.SfcFlowClassifier;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.acl.rev150105.RedirectToSfc;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.sfc.acl.rev150105.RedirectToSfcBuilder;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.ArrayList;
-
-/**
- * Class will convert OpenStack Flow Classifier API yang models to
- * OpenDaylight ACL yang models.
- */
-public class FlowClassifierTranslator {
- private static final Logger LOG = LoggerFactory.getLogger(FlowClassifierTranslator.class);
- private static final Short PROTO_TCP = 6;
- private static final Short PROTO_UDP = 17;
- private static final String RULE = "_rule";
-
- public static Acl buildAcl(SfcFlowClassifier flowClassifier) {
- return buildAcl(flowClassifier, null);
- }
- public static Acl buildAcl(SfcFlowClassifier flowClassifier, String rspName) {
- LOG.info("OpenStack Networking SFC pushed Flow classifier : {}", flowClassifier);
- AclBuilder aclBuilder = new AclBuilder();
- AccessListEntriesBuilder accessListEntriesBuilder = new AccessListEntriesBuilder();
- AceBuilder aceBuilder = new AceBuilder();
- MatchesBuilder matchesBuilder = new MatchesBuilder();
-
- ActionsBuilder actionsBuilder = new ActionsBuilder();
- RedirectToSfcBuilder redirectToSfcBuilder = new RedirectToSfcBuilder();
-
- AceIpBuilder aceIpBuilder = new AceIpBuilder();
- DestinationPortRangeBuilder destinationPortRange = new DestinationPortRangeBuilder();
- SourcePortRangeBuilder sourcePortRangeBuilder = new SourcePortRangeBuilder();
-
- if (flowClassifier.getUuid() != null) {
- if (flowClassifier.getName() != null) {
- aclBuilder.setAclName(flowClassifier.getUuid().getValue() + "_" + flowClassifier.getName());
- } else {
- aclBuilder.setAclName(flowClassifier.getUuid().getValue());
- }
-
- }
- if (flowClassifier.getEthertype() != null) {
- IpPrefix sourceIp = null;
- IpPrefix destinationIp = null;
- if (flowClassifier.getSourceIpPrefix() != null) {
- sourceIp = flowClassifier.getSourceIpPrefix();
- }
- if (flowClassifier.getDestinationIpPrefix() != null) {
- destinationIp = flowClassifier.getDestinationIpPrefix();
- }
- if (flowClassifier.getEthertype() == EthertypeV4.class) {
- AceIpv4Builder aceIpv4Builder = new AceIpv4Builder();
- if (sourceIp != null && sourceIp.getIpv4Prefix() != null ) {
- aceIpv4Builder.setSourceIpv4Network(sourceIp.getIpv4Prefix());
- }
- if (destinationIp != null && destinationIp.getIpv4Prefix() != null) {
- aceIpv4Builder.setDestinationIpv4Network(destinationIp.getIpv4Prefix());
- }
- aceIpBuilder.setAceIpVersion(aceIpv4Builder.build());
- aclBuilder.setAclType(Ipv4Acl.class);
- }
- if (flowClassifier.getEthertype() == EthertypeV6.class) {
- AceIpv6Builder aceIpv6Builder = new AceIpv6Builder();
- if (sourceIp != null && sourceIp.getIpv6Prefix() != null ) {
- aceIpv6Builder.setSourceIpv6Network(sourceIp.getIpv6Prefix());
- }
- if (sourceIp != null && destinationIp.getIpv6Prefix() != null) {
- aceIpv6Builder.setDestinationIpv6Network(destinationIp.getIpv6Prefix());
- }
- aceIpBuilder.setAceIpVersion(aceIpv6Builder.build());
- aclBuilder.setAclType(Ipv6Acl.class);
- }
- }
- if (flowClassifier.getProtocol() != null) {
- if (flowClassifier.getProtocol() == ProtocolTcp.class) {
- aceIpBuilder.setProtocol(PROTO_TCP);
- }
- if (flowClassifier.getProtocol() == ProtocolUdp.class) {
- aceIpBuilder.setProtocol(PROTO_UDP);
- }
- }
- if (flowClassifier.getSourcePortRangeMin() != null) {
- sourcePortRangeBuilder.setLowerPort(new PortNumber(flowClassifier.getSourcePortRangeMin()));
- }
- if (flowClassifier.getSourcePortRangeMax() != null) {
- sourcePortRangeBuilder.setUpperPort(new PortNumber(flowClassifier.getSourcePortRangeMax()));
- }
- if (flowClassifier.getDestinationPortRangeMin() != null) {
- destinationPortRange.setLowerPort(new PortNumber(flowClassifier.getDestinationPortRangeMin()));
- }
- if (flowClassifier.getDestinationPortRangeMax() != null) {
- destinationPortRange.setUpperPort(new PortNumber(flowClassifier.getDestinationPortRangeMax()));
- }
- if (flowClassifier.getLogicalSourcePort() != null) {
- // No respective ACL construct for it.
- }
- if (flowClassifier.getLogicalDestinationPort() != null) {
- // No respective ACL construct for it.
- }
- if (flowClassifier.getL7Parameter() != null) {
- //It's currently not supported.
- }
-
- aceIpBuilder.setSourcePortRange(sourcePortRangeBuilder.build());
- aceIpBuilder.setDestinationPortRange(destinationPortRange.build());
-
- matchesBuilder.setAceType(aceIpBuilder.build());
-
- //Set redirect-to-rsp action if rsp name is provided
- if (rspName != null) {
- redirectToSfcBuilder.setRspName(rspName);
- actionsBuilder.addAugmentation(RedirectToSfc.class, redirectToSfcBuilder.build());
- aceBuilder.setActions(actionsBuilder.build());
- }
- aceBuilder.setMatches(matchesBuilder.build());
-
- //OpenStack networking-sfc don't pass action information
- //with flow classifier. It need to be determined using the
- //Port Chain data and then flow calssifier need to be updated
- //with the actions.
-
- aceBuilder.setRuleName(aclBuilder.getAclName() + RULE);
- aceBuilder.setKey(new AceKey(aceBuilder.getRuleName()));
-
- ArrayList<Ace> aceList = new ArrayList<>();
- aceList.add(aceBuilder.build());
- accessListEntriesBuilder.setAce(aceList);
-
- aclBuilder.setAccessListEntries(accessListEntriesBuilder.build());
- aclBuilder.setKey(new AclKey(aclBuilder.getAclName(),aclBuilder.getAclType()));
-
- LOG.info("Translated ACL Flow classfier : {}", aclBuilder.toString());
-
- return aclBuilder.build();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.sfc.translator.flowclassifier;
-
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.netvirt.openstack.sfc.translator.DelegatingDataTreeListener;
-import org.opendaylight.netvirt.openstack.sfc.translator.SfcMdsalHelper;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.Acl;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.sfc.flow.classifier.rev160511.sfc.flow.classifiers.attributes.SfcFlowClassifiers;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.sfc.flow.classifier.rev160511.sfc.flow.classifiers.attributes.sfc.flow.classifiers.SfcFlowClassifier;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-
-/**
- * OpenDaylight Neutron Flow Classifier yang models data change listener
- */
-public class NeutronFlowClassifierListener extends DelegatingDataTreeListener<SfcFlowClassifier> {
-
- private static final InstanceIdentifier<SfcFlowClassifier> flowClassifiersIid =
- InstanceIdentifier.create(Neutron.class).child(SfcFlowClassifiers.class).child(SfcFlowClassifier.class);
-
- private final SfcMdsalHelper sfcMdsalHelper;
-
- public NeutronFlowClassifierListener(DataBroker db) {
- super(db, new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION,flowClassifiersIid));
- sfcMdsalHelper = new SfcMdsalHelper(db);
-
- }
-
- /**
- * Method removes Acl respective to SfcFlowClassifier which is identified by InstanceIdentifier.
- *
- * @param path - the whole path to SfcFlowClassifier
- * @param deletedSfcFlowClassifier - SfcFlowClassifier for removing
- */
- @Override
- public void remove(InstanceIdentifier<SfcFlowClassifier> path, SfcFlowClassifier deletedSfcFlowClassifier) {
- Acl aclFlowClassifier = FlowClassifierTranslator.buildAcl(deletedSfcFlowClassifier);
- sfcMdsalHelper.removeAclFlowClassifier(aclFlowClassifier);
- }
-
- /**
- * Method updates the original SfcFlowClassifier to the update SfcFlowClassifier.
- * Both are identified by same InstanceIdentifier.
- *
- * @param path - the whole path to SfcFlowClassifier
- * @param originalSfcFlowClassifier - original SfcFlowClassifier (for update)
- * @param updatedSfcFlowClassifier - changed SfcFlowClassifier (contain updates)
- */
- @Override
- public void update(InstanceIdentifier<SfcFlowClassifier> path,
- SfcFlowClassifier originalSfcFlowClassifier,
- SfcFlowClassifier updatedSfcFlowClassifier) {
-
- Acl aclFlowClassifier = FlowClassifierTranslator.buildAcl(updatedSfcFlowClassifier);
- sfcMdsalHelper.updateAclFlowClassifier(aclFlowClassifier);
- }
-
- /**
- * Method adds the SfcFlowClassifier which is identified by InstanceIdentifier
- * to device.
- *
- * @param path - the whole path to new SfcFlowClassifier
- * @param sfcFlowClassifier - new SfcFlowClassifier
- */
- @Override
- public void add(InstanceIdentifier<SfcFlowClassifier> path, SfcFlowClassifier sfcFlowClassifier) {
- // Respective ACL classifier will be written in data store, once the chain is created.
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.sfc.translator.portchain;
-
-import com.google.common.util.concurrent.ThreadFactoryBuilder;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.netvirt.openstack.sfc.translator.DelegatingDataTreeListener;
-import org.opendaylight.netvirt.openstack.sfc.translator.NeutronMdsalHelper;
-import org.opendaylight.netvirt.openstack.sfc.translator.OvsdbMdsalHelper;
-import org.opendaylight.netvirt.openstack.sfc.translator.OvsdbPortMetadata;
-import org.opendaylight.netvirt.openstack.sfc.translator.SfcMdsalHelper;
-import org.opendaylight.netvirt.openstack.sfc.translator.flowclassifier.FlowClassifierTranslator;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.CreateRenderedPathInput;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.CreateRenderedPathOutput;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.DeleteRenderedPathInput;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.RenderedServicePathService;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sf.rev140701.service.functions.ServiceFunction;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sf.rev140701.service.functions.ServiceFunctionBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfc.rev140701.service.function.chain.grouping.ServiceFunctionChain;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.service.function.forwarders.ServiceFunctionForwarder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.service.function.forwarders.ServiceFunctionForwarderBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfp.rev140701.service.function.paths.ServiceFunctionPath;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.Acl;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.sfc.flow.classifier.rev160511.sfc.flow.classifiers.attributes.sfc.flow.classifiers.SfcFlowClassifier;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.sfc.rev160511.sfc.attributes.PortChains;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.sfc.rev160511.sfc.attributes.port.chains.PortChain;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.sfc.rev160511.sfc.attributes.port.pair.groups.PortPairGroup;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.sfc.rev160511.sfc.attributes.port.pairs.PortPair;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import java.util.concurrent.ThreadFactory;
-
-/**
- * OpenDaylight Neutron Port Chain yang models data change listener
- */
-public class NeutronPortChainListener extends DelegatingDataTreeListener<PortChain> {
- private static final Logger LOG = LoggerFactory.getLogger(NeutronPortChainListener.class);
-
- private static final InstanceIdentifier<PortChain> portChainIid =
- InstanceIdentifier.create(Neutron.class).child(PortChains.class).child(PortChain.class);
- private final ExecutorService eventProcessor;
- private final SfcMdsalHelper sfcMdsalHelper;
- private final NeutronMdsalHelper neutronMdsalHelper;
- private final OvsdbMdsalHelper ovsdbMdsalHelper;
- private RenderedServicePathService rspService;
-
- public NeutronPortChainListener(DataBroker db, RenderedServicePathService rspService) {
- super(db,new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION, portChainIid));
- this.sfcMdsalHelper = new SfcMdsalHelper(db);
- this.neutronMdsalHelper = new NeutronMdsalHelper(db);
- this.ovsdbMdsalHelper = new OvsdbMdsalHelper(db);
- this.rspService = rspService;
- ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("Port-Chain-Event-Processor").build();
- this.eventProcessor = Executors.newSingleThreadExecutor(threadFactory);
- }
-
- /**
- * Method removes PortChain which is identified by InstanceIdentifier.
- *
- * @param path - the whole path to PortChain
- * @param deletedPortChain - PortChain for removing
- */
- @Override
- public void remove(InstanceIdentifier<PortChain> path, PortChain deletedPortChain) {
- if(this.rspService != null) {
- DeleteRenderedPathInput deleteRenderedPathInput =
- PortChainTranslator.buildDeleteRenderedServicePathInput(PortChainTranslator
- .getSFPKey(deletedPortChain));
- if (deleteRenderedPathInput != null ) {
- this.rspService.deleteRenderedPath(deleteRenderedPathInput);
- }
- }
- sfcMdsalHelper.deleteServiceFunctionPath(PortChainTranslator.getSFPKey(deletedPortChain));
- sfcMdsalHelper.deleteServiceFunctionChain(PortChainTranslator.getSFCKey(deletedPortChain));
- }
-
- /**
- * Method updates the original PortChain to the update PortChain.
- * Both are identified by same InstanceIdentifier.
- *
- * @param path - the whole path to PortChain
- * @param originalPortChain - original PortChain (for update)
- * @param updatePortChain - changed PortChain (contain updates)
- */
- @Override
- public void update(InstanceIdentifier<PortChain> path, PortChain originalPortChain, PortChain updatePortChain) {
- //TODO: Add support for chain update
- }
-
- /**
- * Method adds the PortChain which is identified by InstanceIdentifier
- * to device.
- *
- * @param path - the whole path to new PortChain
- * @param newPortChain - new PortChain
- */
- @Override
- public void add(final InstanceIdentifier<PortChain> path, final PortChain newPortChain) {
- processPortChain(newPortChain);
- eventProcessor.submit(() -> processPortChain(newPortChain));
- }
-
- private void processPortChain(PortChain newPortChain) {
- //List of Port Pair Group attached to the Port Chain
- List<PortPairGroup> portPairGroupList = new ArrayList<>();
- //Port Pair Group and associated Port Pair
- Map<Uuid, List<PortPair>> groupPortPairsList = new HashMap<>();
- //Map of Port Pair uuid and Port pair ingress port related Neutron Port
- Map<Uuid, Port> portPairToNeutronPortMap = new HashMap<>();
-
- //Mapping of Port Pair UUID and OvsdbPortMetadata of the port pair ingress port
- Map<Uuid, OvsdbPortMetadata> portPairOvsdbMetadata = new HashMap<>();
-
- Map<Uuid, ServiceFunctionForwarderBuilder> portPairGroupToSFFMap = new HashMap<>();
- List<ServiceFunction> portChainServiceFunctionList = new ArrayList<>();
-
- //Read chain related port pair group, port pair and neutron port from neutron data store
- for (Uuid ppgUuid : newPortChain.getPortPairGroups()) {
- PortPairGroup ppg = neutronMdsalHelper.getNeutronPortPairGroup(ppgUuid);
- if (ppg != null) {
- List<PortPair> portPairList = new ArrayList<>();
- portPairGroupList.add(ppg);
- for(Uuid ppUuid : ppg.getPortPairs()) {
- PortPair pp = neutronMdsalHelper.getNeutronPortPair(ppUuid);
- if (pp != null) {
- portPairList.add(pp);
- //NOTE:Assuming that ingress and egress port is same.
- Port neutronPort = neutronMdsalHelper.getNeutronPort(pp.getIngress());
- if (neutronPort != null) {
- portPairToNeutronPortMap.put(pp.getIngress(), neutronPort);
- }
- }
- }
- groupPortPairsList.put(ppgUuid, portPairList);
- }
- }
-
- Topology ovsdbTopology = ovsdbMdsalHelper.getOvsdbTopologyTree();
-
- //Read ovsdb port details related to neutron port. Each Port pair has two neutron port
- //With the current implementation, i am assuming that we support SF only with single port
- //that act as a ingress as well as egress.
- for(Map.Entry<Uuid, Port> neutronPortEntry : portPairToNeutronPortMap.entrySet()) {
- OvsdbPortMetadata ovsdbPortMetadata =
- ovsdbMdsalHelper.getOvsdbPortMetadata(
- neutronPortEntry.getValue().getKey().getUuid(),
- ovsdbTopology);
-
- if(ovsdbPortMetadata != null) {
- portPairOvsdbMetadata.put(neutronPortEntry.getKey(), ovsdbPortMetadata);
- }
- }
-
- //For each port pair group
- for (PortPairGroup ppg : portPairGroupList) {
- List<ServiceFunctionBuilder> portPairSFList = new ArrayList<>();
-
- List<PortPair> portPairList = groupPortPairsList.get(ppg.getUuid());
- Map<Uuid, OvsdbPortMetadata> metadataList = new HashMap<>();
- //Generate OvsdbPortMetadata for list of all the port pair
- for (PortPair portPair : portPairList) {
- OvsdbPortMetadata metadata = portPairOvsdbMetadata.get(portPair.getIngress());
-
- if (metadata != null) {
- metadataList.put(portPair.getIngress(), metadata);
- }
- }
-
- //Build the SFF Builder from port pair group
- ServiceFunctionForwarderBuilder sffBuilder =
- PortPairGroupTranslator.buildServiceFunctionForwarder(ppg,portPairList, metadataList);
- LOG.info("SFF generated for Port Pair Group {} :: {}",ppg, sffBuilder);
- //Check if SFF already exist
- ServiceFunctionForwarder existingSff =
- sfcMdsalHelper.getExistingSFF(sffBuilder.getIpMgmtAddress().getIpv4Address().getValue());
- if(existingSff != null) {
- LOG.info("SFF already exist for Port Pair Group {}. Existing SFF is {}",ppg, existingSff);
- sffBuilder = new ServiceFunctionForwarderBuilder(existingSff);
- }
- //Add SFF builder to the map for later reference
- portPairGroupToSFFMap.put(ppg.getUuid(), sffBuilder);
-
- //Generate all the SF and write it to SFC data store
- for (PortPair portPair : portPairList) {
- OvsdbPortMetadata metadata = portPairOvsdbMetadata.get(portPair.getIngress());
- //Build the service function for the given port pair.
- ServiceFunctionBuilder sfBuilder = PortPairTranslator.buildServiceFunction(portPair,
- ppg,
- portPairToNeutronPortMap.get(portPair.getIngress()),
- metadata,
- sffBuilder.build());
-
- if (sfBuilder != null) {
- LOG.info("Service Function generated for the Port Pair {} :: {}", portPair, sfBuilder);
- //Write the Service Function to SFC data store.
- sfcMdsalHelper.addServiceFunction(sfBuilder.build());
-
- //Add to the list, to populated SFF Service Function Dictionary
- portPairSFList.add(sfBuilder);
-
- //Add the SF to Port Chain related SF list
- portChainServiceFunctionList.add(sfBuilder.build());
- } else {
- LOG.warn("Service Function building failed for Port Pair {}", portPair);
- }
- }
-
- //Update the Service Function Dictionary of SFF
- for (ServiceFunctionBuilder sf : portPairSFList) {
- PortPairGroupTranslator.buildServiceFunctionDictonary(sffBuilder, sf.build());
- LOG.info("Updating Service Function dictionary of SFF {} for SF {}", sffBuilder, sf);
- }
- // Send SFF create request
- LOG.info("Add Service Function Forwarder {} for Port Pair Group {}", sffBuilder.build(), ppg);
- sfcMdsalHelper.addServiceFunctionForwarder(sffBuilder.build());
- }
- //Build Service Function Chain Builder
- ServiceFunctionChain sfc =
- PortChainTranslator.buildServiceFunctionChain(newPortChain, portChainServiceFunctionList);
-
- //Write SFC to data store
- if (sfc != null) {
- LOG.info("Add service function chain {}", sfc);
- sfcMdsalHelper.addServiceFunctionChain(sfc);
- } else {
- LOG.warn("Service Function Chain building failed for Port Chain {}", newPortChain);
- }
-
- // Build Service Function Path Builder
- ServiceFunctionPath sfp = PortChainTranslator.buildServiceFunctionPath(sfc);
- //Write SFP to data store
- if (sfp != null) {
- LOG.info("Add service function path {}", sfp);
- sfcMdsalHelper.addServiceFunctionPath(sfp);
- } else {
- LOG.warn("Service Function Path building failed for Service Chain {}", sfc);
- }
-
- //TODO:Generate Flow Classifiers and augment RSP on it.
-
- if (this.rspService != null) {
- // Build Create Rendered Service Path input
- CreateRenderedPathInput rpInput = PortChainTranslator.buildCreateRenderedServicePathInput(sfp);
-
- //Call Create Rendered Service Path RPC call
- if (rpInput != null) {
- LOG.info("Call RPC for creating RSP :{}", rpInput);
- Future<RpcResult<CreateRenderedPathOutput>> result = this.rspService.createRenderedPath(rpInput);
- try {
- if (result.get() != null) {
- CreateRenderedPathOutput output = result.get().getResult();
- LOG.debug("RSP name received from SFC : {}", output.getName());
- processFlowClassifiers(newPortChain, newPortChain.getFlowClassifiers(), output.getName());
- } else {
- LOG.error("RSP creation failed : {}", rpInput);
- }
- } catch (InterruptedException | ExecutionException e) {
- LOG.error("Error occurred during creating Rendered Service Path using RPC call", e);
- }
- }
- } else {
- LOG.error("Rendered Path Service is not available, can't create Rendered Path for Port Chain", newPortChain);
- }
- }
-
- private void processFlowClassifiers(PortChain pc, List<Uuid> flowClassifiers, String rspName) {
- for (Uuid uuid : flowClassifiers) {
- SfcFlowClassifier fc = neutronMdsalHelper.getNeutronFlowClassifier(uuid);
- if (fc != null) {
- Acl acl = FlowClassifierTranslator.buildAcl(fc, rspName);
- if (acl != null ) {
- sfcMdsalHelper.addAclFlowClassifier(acl);
- } else {
- LOG.warn("Acl building failed for flow classifier {}. Traffic might not be redirected to RSP", fc);
- }
-
- } else {
- LOG.error("Neutron Flow Classifier {} attached to Port Chain {} is not present in the neutron data " +
- "store", uuid, pc);
- }
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.sfc.translator.portchain;
-
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.netvirt.openstack.sfc.translator.DelegatingDataTreeListener;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.sfc.rev160511.sfc.attributes.PortPairGroups;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.sfc.rev160511.sfc.attributes.port.pair.groups.PortPairGroup;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-
-/**
- * OpenDaylight Neutron Port Pair Group yang models data change listener
- */
-public class NeutronPortPairGroupListener extends DelegatingDataTreeListener<PortPairGroup> {
- private static final InstanceIdentifier<PortPairGroup> portPairGroupIid =
- InstanceIdentifier.create(Neutron.class).child(PortPairGroups.class).child(PortPairGroup.class);
-
- public NeutronPortPairGroupListener(DataBroker db) {
- super(db,new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION, portPairGroupIid));
- }
-
- /**
- * Method removes PortPairGroup which is identified by InstanceIdentifier.
- *
- * @param path - the whole path to PortPairGroup
- * @param deletedPortPairGroup - PortPairGroup for removing
- */
- @Override
- public void remove(InstanceIdentifier<PortPairGroup> path, PortPairGroup deletedPortPairGroup) {
- //NO-OP
- }
-
- /**
- * Method updates the original PortPairGroup to the update PortPairGroup.
- * Both are identified by same InstanceIdentifier.
- *
- * @param path - the whole path to PortPairGroup
- * @param originalPortPairGroup - original PortPairGroup (for update)
- * @param updatePortPairGroup - changed PortPairGroup (contain updates)
- */
- @Override
- public void update(InstanceIdentifier<PortPairGroup> path,
- PortPairGroup originalPortPairGroup,
- PortPairGroup updatePortPairGroup) {
- //NO-OP
- }
-
- /**
- * Method adds the PortPairGroup which is identified by InstanceIdentifier
- * to device.
- *
- * @param path - the whole path to new PortPairGroup
- * @param newPortPairGroup - new PortPairGroup
- */
- @Override
- public void add(InstanceIdentifier<PortPairGroup> path, PortPairGroup newPortPairGroup) {
- //NO-OP
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.sfc.translator.portchain;
-
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.netvirt.openstack.sfc.translator.DelegatingDataTreeListener;
-import org.opendaylight.netvirt.openstack.sfc.translator.NeutronMdsalHelper;
-import org.opendaylight.netvirt.openstack.sfc.translator.OvsdbMdsalHelper;
-import org.opendaylight.netvirt.openstack.sfc.translator.SfcMdsalHelper;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.SffName;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sf.rev140701.service.functions.ServiceFunction;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sf.rev140701.service.functions.ServiceFunctionKey;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.service.function.forwarders.ServiceFunctionForwarder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.service.function.forwarders.ServiceFunctionForwarderBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.service.function.forwarders.ServiceFunctionForwarderKey;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.service.function.forwarders.service.function.forwarder.ServiceFunctionDictionary;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.sfc.rev160511.sfc.attributes.PortPairs;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.sfc.rev160511.sfc.attributes.port.pairs.PortPair;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.List;
-
-/**
- * OpenDaylight Neutron Port Pair yang models data change listener
- */
-public class NeutronPortPairListener extends DelegatingDataTreeListener<PortPair> {
- private static final Logger LOG = LoggerFactory.getLogger(NeutronPortPairListener.class);
-
- private static final InstanceIdentifier<PortPair> portPairIid =
- InstanceIdentifier.create(Neutron.class).child(PortPairs.class).child(PortPair.class);
-
- private final DataBroker db;
- private final SfcMdsalHelper sfcMdsalHelper;
- private final NeutronMdsalHelper neutronMdsalHelper;
- private final OvsdbMdsalHelper ovsdbMdsalHelper;
-
- public NeutronPortPairListener(DataBroker db) {
- super(db,new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION, portPairIid));
- this.db = db;
- sfcMdsalHelper = new SfcMdsalHelper(db);
- neutronMdsalHelper = new NeutronMdsalHelper(db);
- ovsdbMdsalHelper = new OvsdbMdsalHelper(db);
- }
-
- /**
- * Method removes PortPair which is identified by InstanceIdentifier.
- *
- * @param path - the whole path to PortPair
- * @param deletedPortPair - PortPair for removing
- */
- @Override
- public void remove(InstanceIdentifier<PortPair> path, PortPair deletedPortPair) {
- ServiceFunctionKey sfKey = PortPairTranslator.getSFKey(deletedPortPair);
- ServiceFunction serviceFunction = sfcMdsalHelper.readServiceFunction(sfKey);
- if (serviceFunction != null ) {
- //Current support is for one Service Function connected to one data plane locator
- SffName sffName = serviceFunction.getSfDataPlaneLocator().get(0).getServiceFunctionForwarder();
- if (sffName != null) {
- ServiceFunctionForwarderKey sffKey = new ServiceFunctionForwarderKey(sffName);
- ServiceFunctionForwarder sff = sfcMdsalHelper.readServiceFunctionForwarder(sffKey);
- if (sff != null) {
- List<ServiceFunctionDictionary> sfDictionary = sff.getServiceFunctionDictionary();
- if (sfDictionary != null) {
- ServiceFunctionDictionary matchingSfd = null;
- for (ServiceFunctionDictionary sfd : sfDictionary) {
- if (sfd.getName().equals(sfKey.getName())) {
- matchingSfd = sfd;
- break;
- }
- }
- if (matchingSfd != null) {
- sfDictionary.remove(matchingSfd);
- if (sfDictionary.isEmpty()) {
- //If the current SF is last SF attach to SFF, delete the SFF
- sfcMdsalHelper.deleteServiceFunctionForwarder(sffKey);
- } else {
- //If there are SF attached to the SFF, just update the SFF dictionary by removing
- // this deleted SF.
- ServiceFunctionForwarderBuilder sffBuilder = new ServiceFunctionForwarderBuilder(sff);
- LOG.info("Remove the SF {} from SFF {} dictionary and update in data store.", sfKey
- .getName(), sffName);
- sfcMdsalHelper.addServiceFunctionForwarder(sffBuilder.build());
- }
- } else {
- LOG.info("Service Function {} not present in connected Service Function Forwarder {} " +
- "dictionary", sfKey.getName(), sffName);
- }
- }
- }
- }
- } else {
- LOG.info("Service Function related to Port Pair {} don't exist.", deletedPortPair);
- }
- sfcMdsalHelper.removeServiceFunction(sfKey);
- }
-
- /**
- * Method updates the original PortPair to the update PortPair.
- * Both are identified by same InstanceIdentifier.
- *
- * @param path - the whole path to PortPair
- * @param originalPortPair - original PortPair (for update)
- * @param updatePortPair - changed PortPair (contain updates)
- */
- @Override
- public void update(InstanceIdentifier<PortPair> path, PortPair originalPortPair, PortPair updatePortPair) {
- //NO-OP
- }
-
- /**
- * Method adds the PortPair which is identified by InstanceIdentifier
- * to device.
- *
- * @param path - the whole path to new PortPair
- * @param newPortPair - new PortPair
- */
- @Override
- public void add(InstanceIdentifier<PortPair> path, PortPair newPortPair) {
- //NO-OP
- // Port Pair data written in neutron data store will be used
- // When user will create port chain.
- }
-}
+++ /dev/null
-/*
- * Copyright © 2016, 2017 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.sfc.translator.portchain;
-
-import com.google.common.base.Preconditions;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.SfcName;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.SfpName;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.CreateRenderedPathInput;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.CreateRenderedPathInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.DeleteRenderedPathInput;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.DeleteRenderedPathInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sf.rev140701.service.functions.ServiceFunction;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfc.rev140701.service.function.chain.grouping.ServiceFunctionChain;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfc.rev140701.service.function.chain.grouping.ServiceFunctionChainBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfc.rev140701.service.function.chain.grouping.ServiceFunctionChainKey;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfc.rev140701.service.function.chain.grouping.service.function.chain.SfcServiceFunction;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfc.rev140701.service.function.chain.grouping.service.function.chain.SfcServiceFunctionBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfc.rev140701.service.function.chain.grouping.service.function.chain.SfcServiceFunctionKey;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfp.rev140701.service.function.paths.ServiceFunctionPath;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfp.rev140701.service.function.paths.ServiceFunctionPathBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfp.rev140701.service.function.paths.ServiceFunctionPathKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.sfc.rev160511.port.chain.attributes.ChainParameters;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.sfc.rev160511.sfc.attributes.port.chains.PortChain;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Class will convert OpenStack Port Chain API yang models present in
- * neutron northbound project to OpenDaylight SFC yang models.
- */
-public class PortChainTranslator {
- private static final Logger LOG = LoggerFactory.getLogger(PortChainTranslator.class);
- private static final String SYMMETRIC_PARAM = "symmetric";
- private static final String SFP_NAME_PREFIX = "Path-";
-
- public static ServiceFunctionChain buildServiceFunctionChain(
- PortChain portChain, List<ServiceFunction> sfList) {
- ServiceFunctionChainBuilder sfcBuilder = new ServiceFunctionChainBuilder();
- sfcBuilder.setName(new SfcName(portChain.getName()));
- sfcBuilder.setKey(new ServiceFunctionChainKey(sfcBuilder.getName()));
-
- //By default set it to false. If user specify it in chain parameters, it
- //will be overridden.
- sfcBuilder.setSymmetric(false);
-
- //Set service functions
- List<SfcServiceFunction> sfcSfList = new ArrayList<>();
- for(ServiceFunction sf : sfList) {
- SfcServiceFunctionBuilder sfcSfBuilder = new SfcServiceFunctionBuilder();
- sfcSfBuilder.setName(sf.getName().getValue());
- sfcSfBuilder.setType(sf.getType());
- sfcSfBuilder.setKey(new SfcServiceFunctionKey(sfcSfBuilder.getName()));
-
- //NOTE: no explicit order is set.
- sfcSfList.add(sfcSfBuilder.build());
- }
- List<ChainParameters> cpList = portChain.getChainParameters();
- if (cpList != null && !cpList.isEmpty()) {
- for (ChainParameters cp : cpList) {
- if(cp.getChainParameter().equals(SYMMETRIC_PARAM)) {
- //Override the symmetric default value.
- sfcBuilder.setSymmetric(Boolean.valueOf(cp.getChainParameterValue()));
- break;
- }
- }
- }
- sfcBuilder.setSfcServiceFunction(sfcSfList);
- return sfcBuilder.build();
- }
-
- public static ServiceFunctionPath buildServiceFunctionPath(ServiceFunctionChain sfc) {
- Preconditions.checkNotNull(sfc, "Service Function Chain must not be null");
- ServiceFunctionPathBuilder sfpBuilder = new ServiceFunctionPathBuilder();
-
- //Set the name
- sfpBuilder.setName(new SfpName(SFP_NAME_PREFIX + sfc.getName().getValue()));
-
- sfpBuilder.setSymmetric(sfc.isSymmetric());
- //Set related SFC name
- sfpBuilder.setServiceChainName(sfc.getName());
- return sfpBuilder.build();
- }
-
- public static CreateRenderedPathInput buildCreateRenderedServicePathInput(ServiceFunctionPath sfp) {
- CreateRenderedPathInputBuilder rpInputBuilder = new CreateRenderedPathInputBuilder();
- rpInputBuilder.setSymmetric(sfp.isSymmetric());
- rpInputBuilder.setParentServiceFunctionPath(sfp.getName().getValue());
- return rpInputBuilder.build();
- }
-
- public static DeleteRenderedPathInput buildDeleteRenderedServicePathInput(ServiceFunctionPathKey sfpKey) {
- DeleteRenderedPathInputBuilder rpInputBuilder = new DeleteRenderedPathInputBuilder();
- rpInputBuilder.setName(sfpKey.getName().getValue());
- return rpInputBuilder.build();
- }
- public static ServiceFunctionChainKey getSFCKey(PortChain portChain) {
- return new ServiceFunctionChainKey(new SfcName(portChain.getName()));
- }
-
- public static ServiceFunctionPathKey getSFPKey(PortChain portChain) {
- return new ServiceFunctionPathKey(new SfpName(SFP_NAME_PREFIX + portChain.getName()));
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.sfc.translator.portchain;
-
-import com.google.common.base.Preconditions;
-import org.opendaylight.netvirt.openstack.sfc.translator.OvsdbMdsalHelper;
-import org.opendaylight.netvirt.openstack.sfc.translator.OvsdbPortMetadata;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.SffDataPlaneLocatorName;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.SffName;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.SnName;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sf.rev140701.service.functions.ServiceFunction;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.ovs.rev140701.SffOvsBridgeAugmentation;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.ovs.rev140701.SffOvsBridgeAugmentationBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.ovs.rev140701.SffOvsLocatorOptionsAugmentation;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.ovs.rev140701.SffOvsLocatorOptionsAugmentationBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.ovs.rev140701.SffOvsNodeAugmentation;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.ovs.rev140701.SffOvsNodeAugmentationBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.ovs.rev140701.bridge.OvsBridgeBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.ovs.rev140701.node.OvsNodeBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.ovs.rev140701.options.OvsOptionsBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.Open;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.service.function.forwarder.base.SffDataPlaneLocator;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.service.function.forwarder.base.SffDataPlaneLocatorBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.service.function.forwarder.base.SffDataPlaneLocatorKey;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.service.function.forwarder.base.sff.data.plane.locator.DataPlaneLocatorBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.service.function.forwarders.ServiceFunctionForwarderBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.service.function.forwarders.ServiceFunctionForwarderKey;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.service.function.forwarders.service.function.forwarder.ServiceFunctionDictionary;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.service.function.forwarders.service.function.forwarder.ServiceFunctionDictionaryBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.service.function.forwarders.service.function.forwarder.ServiceFunctionDictionaryKey;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.service.function.forwarders.service.function.forwarder.service.function.dictionary.SffSfDataPlaneLocatorBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sl.rev140701.VxlanGpe;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sl.rev140701.data.plane.locator.locator.type.IpBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.sfc.rev160511.sfc.attributes.port.pair.groups.PortPairGroup;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.sfc.rev160511.sfc.attributes.port.pairs.PortPair;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicInteger;
-
-/**
- * Class will convert OpenStack Port Pair API yang models present in
- * neutron northbound project to OpenDaylight SFC yang models.
- */
-public class PortPairGroupTranslator {
- private static final Logger LOG = LoggerFactory.getLogger(PortPairGroupTranslator.class);
- private static final String OPT_FLOW_STR = "flow";
- private static final String OPT_GPE_STR = "gpe";
- private static final String OPT_DST_PORT = "6633";
-
- private static final AtomicInteger counter = new AtomicInteger(0);
- private static final String SFF_DEFAULT_NAME = "sff";
- private static final String SFF_DPL_SUFFIX = "-dpl";
- private static final String SFF_DPL_FIX_NAME = "vxgpe";
-
- public static ServiceFunctionForwarderBuilder buildServiceFunctionForwarder(
- PortPairGroup portPairGroup,
- List<PortPair> portPairs,
- Map<Uuid, OvsdbPortMetadata> ovsdbPortsMetadata) {
- Preconditions.checkNotNull(portPairGroup, "Port pair group must not be null");
-
- ServiceFunctionForwarderBuilder sffBuilder = new ServiceFunctionForwarderBuilder();
- SffOvsBridgeAugmentationBuilder sffOvsBridgeAugBuilder = new SffOvsBridgeAugmentationBuilder();
- SffOvsNodeAugmentationBuilder sffOvsNodeAugBuilder = new SffOvsNodeAugmentationBuilder();
-
- List<SffDataPlaneLocator> sffDataPlaneLocator = new ArrayList<>();
- SffDataPlaneLocatorBuilder sffDplBuilder = new SffDataPlaneLocatorBuilder();
- DataPlaneLocatorBuilder dplBuilder = new DataPlaneLocatorBuilder();
-
- IpBuilder sffLocator = new IpBuilder();
-
- //Currently we only support one SF per type. Mean, one port-pair per port-pair-group.
- //Get port pair from neutron data store.
- PortPair portPair = portPairs.get(0);
- if (portPair == null) {
- LOG.error("Port pair {} does not exist in the neutron data store. Port Pair Group {} request can't be " +
- "processed.", portPairGroup.getPortPairs().get(0), portPairGroup);
- return null;
- }
- //Get metadata of neutron port related to port pair ingress port from ovsdb data store.
- OvsdbPortMetadata ovsdbPortMetadata = ovsdbPortsMetadata.get(portPair.getIngress());
-
- //Convert the port pair to service function
-
- //Set SFF DPL transport type
- dplBuilder.setTransport(VxlanGpe.class);
-
- //Set SFF Locator Type
- OvsdbNodeAugmentation ovsdbNodeAug = ovsdbPortMetadata.getOvsdbNode();
- if (ovsdbNodeAug != null ) {
- sffLocator.setIp(ovsdbNodeAug.getConnectionInfo().getRemoteIp());
- sffLocator.setPort(ovsdbNodeAug.getConnectionInfo().getRemotePort());
- }
- dplBuilder.setLocatorType(sffLocator.build());
- //set data-path-locator for sff-data-path-locator
- sffDplBuilder.setDataPlaneLocator(dplBuilder.build());
-
- //Set location options for sff-dp-locator
- sffDplBuilder.addAugmentation(SffOvsLocatorOptionsAugmentation.class, buildOvsOptions().build());
-
- //Set ovsdb bridge name for sff
- OvsBridgeBuilder ovsBridgeBuilder = new OvsBridgeBuilder();
- OvsdbBridgeAugmentation ovsdbBridgeAugmentation = ovsdbPortMetadata.getOvsdbBridgeNode();
- if (ovsdbBridgeAugmentation != null) {
- ovsBridgeBuilder.setBridgeName(ovsdbBridgeAugmentation.getBridgeName().getValue());
-
- //Set SFF name
- String serviceNode = OvsdbMdsalHelper.getNodeKey(ovsdbBridgeAugmentation.getManagedBy().getValue());
- if(serviceNode.isEmpty()) {
- serviceNode += SFF_DEFAULT_NAME + counter.incrementAndGet();
- sffBuilder.setName(new SffName(serviceNode));
- sffBuilder.setServiceNode(new SnName(serviceNode));
- } else {
- //Set service node to ovsdbNode
- sffBuilder.setServiceNode(new SnName(serviceNode));
-
- //Set SFF name to ovsdbBridgeNode
- serviceNode += "/" + ovsdbBridgeAugmentation.getBridgeName().getValue();
- sffBuilder.setName(new SffName(serviceNode));
- }
-
- //Set ovsdb-node iid reference for SFF
- OvsNodeBuilder ovsNodeBuilder = new OvsNodeBuilder();
- ovsNodeBuilder.setNodeId(ovsdbBridgeAugmentation.getManagedBy());
- sffOvsNodeAugBuilder.setOvsNode(ovsNodeBuilder.build());
- sffBuilder.addAugmentation(SffOvsNodeAugmentation.class, sffOvsNodeAugBuilder.build());
- }
- sffOvsBridgeAugBuilder.setOvsBridge(ovsBridgeBuilder.build());
- sffBuilder.addAugmentation(SffOvsBridgeAugmentation.class, sffOvsBridgeAugBuilder.build());
-
- //Set management ip, same to the ovsdb node ip
- sffBuilder.setIpMgmtAddress(sffLocator.getIp());
-
- //TODO: DPL name should not be hardcoded. Require net-virt classifier to remove dependency on it.
- sffDplBuilder.setName(new SffDataPlaneLocatorName(SFF_DPL_FIX_NAME));
- sffDplBuilder.setKey(new SffDataPlaneLocatorKey(sffDplBuilder.getName()));
- sffDataPlaneLocator.add(sffDplBuilder.build());
- //set SFF key
- sffBuilder.setKey(new ServiceFunctionForwarderKey(sffBuilder.getName()));
- sffBuilder.setSffDataPlaneLocator(sffDataPlaneLocator);
-
- return sffBuilder;
- }
-
- public static void buildServiceFunctionDictonary(ServiceFunctionForwarderBuilder sffBuilder,
- ServiceFunction sf) {
- List<ServiceFunctionDictionary> sfdList = new ArrayList<>();
- ServiceFunctionDictionaryBuilder sfdBuilder = new ServiceFunctionDictionaryBuilder();
-
- //Build Sff-sf-data-plane-locator
- SffSfDataPlaneLocatorBuilder sffSfDplBuilder = new SffSfDataPlaneLocatorBuilder();
- sffSfDplBuilder.setSfDplName(sf.getSfDataPlaneLocator().get(0).getName());
- sffSfDplBuilder.setSffDplName(sffBuilder.getSffDataPlaneLocator().get(0).getName());
- sfdBuilder.setSffSfDataPlaneLocator(sffSfDplBuilder.build());
-
- sfdBuilder.setName(sf.getName());
- sfdBuilder.setKey(new ServiceFunctionDictionaryKey(sfdBuilder.getName()));
-
- //NOTE: fail mode is set to Open by default
- sfdBuilder.setFailmode(Open.class);
- sfdList.add(sfdBuilder.build());
-
- //TODO: set interface name list
-
- if (sffBuilder.getServiceFunctionDictionary() != null) {
- for (Iterator<ServiceFunctionDictionary> sfdItr = sffBuilder.getServiceFunctionDictionary().iterator();sfdItr
- .hasNext();) {
- ServiceFunctionDictionary sfd = sfdItr.next();
- if (sfd.getName().equals(sfdBuilder.getName())) {
- LOG.info("Existing SF dictionary {} found in SFF {}, removing the SF dictionary", sfd.getName(),
- sffBuilder.getName());
- sfdItr.remove();
- break;
- }
- }
- sffBuilder.getServiceFunctionDictionary().addAll(sfdList);
- } else {
- sffBuilder.setServiceFunctionDictionary(sfdList);
- }
- LOG.info("Final Service Function Dictionary {}", sffBuilder.getServiceFunctionDictionary());
- }
-
- private static SffOvsLocatorOptionsAugmentationBuilder buildOvsOptions() {
- SffOvsLocatorOptionsAugmentationBuilder ovsOptions = new SffOvsLocatorOptionsAugmentationBuilder();
- OvsOptionsBuilder ovsOptionsBuilder = new OvsOptionsBuilder();
- ovsOptionsBuilder.setRemoteIp(OPT_FLOW_STR);
- ovsOptionsBuilder.setDstPort(OPT_DST_PORT);
- ovsOptionsBuilder.setKey(OPT_FLOW_STR);
- ovsOptionsBuilder.setExts(OPT_GPE_STR);
- ovsOptions.setOvsOptions(ovsOptionsBuilder.build());
- return ovsOptions;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.openstack.sfc.translator.portchain;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.ImmutableBiMap;
-import org.opendaylight.netvirt.openstack.sfc.translator.OvsdbMdsalHelper;
-import org.opendaylight.netvirt.openstack.sfc.translator.OvsdbPortMetadata;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.SfDataPlaneLocatorName;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.SfName;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.SffName;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.SftTypeName;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.TenantId;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sf.rev140701.service.function.base.SfDataPlaneLocator;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sf.rev140701.service.function.base.SfDataPlaneLocatorBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sf.rev140701.service.function.base.SfDataPlaneLocatorKey;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sf.rev140701.service.functions.ServiceFunctionBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sf.rev140701.service.functions.ServiceFunctionKey;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sff.rev140701.service.function.forwarders.ServiceFunctionForwarder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sl.rev140701.SlTransportType;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sl.rev140701.VxlanGpe;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sl.rev140701.data.plane.locator.locator.type.IpBuilder;
-import org.opendaylight.yang.gen.v1.urn.ericsson.params.xml.ns.yang.sfc.sf.ovs.rev160107.SfDplOvsAugmentation;
-import org.opendaylight.yang.gen.v1.urn.ericsson.params.xml.ns.yang.sfc.sf.ovs.rev160107.SfDplOvsAugmentationBuilder;
-import org.opendaylight.yang.gen.v1.urn.ericsson.params.xml.ns.yang.sfc.sf.ovs.rev160107.connected.port.OvsPortBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.AllowedAddressPairs;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.FixedIps;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.sfc.rev160511.port.pair.attributes.ServiceFunctionParameters;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.sfc.rev160511.sfc.attributes.port.pair.groups.PortPairGroup;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.sfc.rev160511.sfc.attributes.port.pairs.PortPair;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.atomic.AtomicInteger;
-
-/**
- * Class will convert OpenStack Port Pair API yang models present in
- * neutron northbound project to OpenDaylight SFC Service Function yang models.
- */
-public class PortPairTranslator {
- private static final Logger LOG = LoggerFactory.getLogger(PortPairTranslator.class);
- private static final String SF_TYPE_PARAM = "type";
- private static final String DPL_SUFFIX_PARAM = "-dpl";
- private static final String DPL_TRANSPORT_PARAM = "dpl-transport";
- private static final String DPL_IP_PARAM = "dpl-ip";
- private static final String DPL_PORT_PARAM = "dpl-port";
- private static final String SFF_STR = "sff";
-
- public static final ImmutableBiMap<String, Class<? extends SlTransportType>> DPL_TRANSPORT_TYPE
- = new ImmutableBiMap.Builder<String, Class<? extends SlTransportType>>()
- .put("vxlan-gpe", VxlanGpe.class).build();
- private static final PortNumber SF_LOCATOR_PORT = new PortNumber(6633);
- private static final AtomicInteger counter = new AtomicInteger(0);
- private static final String SFF_NAME_PARAM = "sff-name";
-
- public static ServiceFunctionBuilder buildServiceFunction(
- PortPair portPair,
- PortPairGroup portPairGroup,
- Port neutronPort,
- OvsdbPortMetadata ovsdbPortMetadata,
- ServiceFunctionForwarder sff) {
- Preconditions.checkNotNull(portPair, "Port pair must not be null");
- Preconditions.checkNotNull(portPairGroup, "Port pair group must not be null");
- Preconditions.checkNotNull(neutronPort, "Neutron Port related to port pair must not be null");
- LOG.info("Port pair received : {}", portPair);
-
- ServiceFunctionBuilder serviceFunctionBuilder = new ServiceFunctionBuilder();
- List<SfDataPlaneLocator> sfDataPlaneLocatorList = new ArrayList<>();
- SfDataPlaneLocatorBuilder sfDataPlaneLocatorBuilder = new SfDataPlaneLocatorBuilder();
- IpBuilder sfLocator = new IpBuilder();
-
- List<ServiceFunctionParameters> sfParams = portPair.getServiceFunctionParameters();
- //Set SF name, key and tenant-id
- serviceFunctionBuilder.setName(new SfName(portPair.getName()));
- serviceFunctionBuilder.setKey(new ServiceFunctionKey(serviceFunctionBuilder.getName()));
- serviceFunctionBuilder.setTenantId(new TenantId(portPair.getTenantId().getValue()));
-
- //Set SF Type. Setting it to PortPairGroup Type, this will be overridden if user pass
- //it through service_function_params
- serviceFunctionBuilder.setType(SftTypeName.getDefaultInstance(portPairGroup.getName()));
-
- //Set data path locator name and key
- sfDataPlaneLocatorBuilder.setName(new SfDataPlaneLocatorName(portPair.getName() + DPL_SUFFIX_PARAM));
- sfDataPlaneLocatorBuilder.setKey(new SfDataPlaneLocatorKey(sfDataPlaneLocatorBuilder.getName()));
-
- //Set vxlan-gpe as a default transport type, unless user pass specific transport in
- //service_function_parameters
- sfDataPlaneLocatorBuilder.setTransport(VxlanGpe.class);
-
- //Set locator type
- if (neutronPort != null) {
- List<FixedIps> fixedIps = neutronPort.getFixedIps();
- List<AllowedAddressPairs> attachedIpAddresses = neutronPort.getAllowedAddressPairs();
- IpAddress ipAddress;
- if (fixedIps != null && !fixedIps.isEmpty()){
- ipAddress = fixedIps.get(0).getIpAddress();
- sfLocator.setIp(ipAddress);
-
- } else if (attachedIpAddresses != null && !attachedIpAddresses.isEmpty()) {
- //Pick up the first ip address
- ipAddress = attachedIpAddresses.get(0).getIpAddress().getIpAddress();
- sfLocator.setIp(ipAddress);
- } else {
- LOG.warn("No ip address attached to Neutron Port {} related to Port Pair {}", neutronPort, portPair);
- //Ideally we should exit here, because without IP address OpenDaylight SFC won't be able to find the
- //respective overlay. But if user passes additional parameter through service_function_param
- //that can be leveraged here. Parameter passed through service_function_param will take precedence.
- }
- sfLocator.setPort(new PortNumber(SF_LOCATOR_PORT));
-
- } else {
- LOG.warn("Neutron port mapped to Port pair ingress/egress port is not found : {}", portPair);
- }
-
- if (ovsdbPortMetadata.getOvsdbPort() != null ) {
- String ovsdbPortName = OvsdbMdsalHelper.getOvsdbPortName(ovsdbPortMetadata.getOvsdbPort());
- SfDplOvsAugmentationBuilder sfDplOvsAugmentationBuilder = new SfDplOvsAugmentationBuilder();
- OvsPortBuilder ovsPortBuilder = new OvsPortBuilder();
- ovsPortBuilder.setPortId(ovsdbPortName);
- sfDplOvsAugmentationBuilder.setOvsPort(ovsPortBuilder.build());
- sfDataPlaneLocatorBuilder.addAugmentation(SfDplOvsAugmentation.class, sfDplOvsAugmentationBuilder.build());
- } else {
- LOG.warn("No OVSDB Port found for the port pair {}. Lack of ovs-port information might not configure SF " +
- "properly", portPair);
- }
-
- //But if user pass specific param using service_function_parameters, set/override it accordingly
- if (sfParams != null) {
- for(ServiceFunctionParameters sfParam : sfParams) {
- //There is by default type set to port pair group name, override it if user pass it specific type
- if (sfParam.getServiceFunctionParameter().equals(SF_TYPE_PARAM)) {
- serviceFunctionBuilder.setType(new SftTypeName(sfParam.getServiceFunctionParameterValue()));
- }
- if (sfParam.getServiceFunctionParameter().equals(DPL_TRANSPORT_PARAM)) {
- Class transportTypeClass
- = DPL_TRANSPORT_TYPE.get(sfParam.getServiceFunctionParameterValue());
- sfDataPlaneLocatorBuilder.setTransport(transportTypeClass);
- }
- if (sfParam.getServiceFunctionParameter().equals(DPL_IP_PARAM)) {
- IpAddress ipAddress = new IpAddress(new Ipv4Address(sfParam.getServiceFunctionParameterValue()));
- sfLocator.setIp(ipAddress);
- }
- if (sfParam.getServiceFunctionParameter().equals(DPL_PORT_PARAM)) {
- sfLocator.setPort(new PortNumber(new Integer(sfParam.getServiceFunctionParameterValue())));
- }
- if (sfParam.getServiceFunctionParameter().equals(SFF_NAME_PARAM)) {
- sfDataPlaneLocatorBuilder.setServiceFunctionForwarder(
- new SffName(sfParam.getServiceFunctionParameterValue()));
- }
- }
- }
-
- //Set service_function_forwarder
- if (sfDataPlaneLocatorBuilder.getServiceFunctionForwarder() == null
- && ovsdbPortMetadata.getOvsdbNode() != null) {
- SffName sffName = sff.getName();
- if(sffName != null ) {
- sfDataPlaneLocatorBuilder.setServiceFunctionForwarder(sffName);
- } else {
- sfDataPlaneLocatorBuilder.setServiceFunctionForwarder(new SffName(SFF_STR + counter.incrementAndGet()));
- }
- }
-
- sfDataPlaneLocatorBuilder.setLocatorType(sfLocator.build());
-
- sfDataPlaneLocatorList.add(sfDataPlaneLocatorBuilder.build());
- //Set management IP to same as DPL IP.
- serviceFunctionBuilder.setIpMgmtAddress(sfLocator.getIp());
-
- //Set all data plane locator
- serviceFunctionBuilder.setSfDataPlaneLocator(sfDataPlaneLocatorList);
- LOG.info("Port Pair translated to Service Function: {}", serviceFunctionBuilder);
- return serviceFunctionBuilder;
- }
-
- public static ServiceFunctionKey getSFKey(PortPair portPair) {
- return new ServiceFunctionKey(new SfName(portPair.getName()));
- }
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
-
- This program and the accompanying materials are made available under the
- terms of the Eclipse Public License v1.0 which accompanies this distribution,
- and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
- xmlns:odl="http://opendaylight.org/xmlns/blueprint/v1.0.0"
- odl:use-default-for-reference-types="true">
-
- <reference id="dataBroker"
- interface="org.opendaylight.controller.md.sal.binding.api.DataBroker" />
- <odl:rpc-service id="rspService"
- interface="org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.RenderedServicePathService"/>
-
- <odl:clustered-app-config id="openstackSfcTranslatorConfig"
- binding-class="org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.openstack.sfc.translator.config.rev160720.OpenstackSfcTranslatorConfig">
- </odl:clustered-app-config>
-
- <bean id="openstackSFCTranslatorProvider"
- class="org.opendaylight.netvirt.openstack.sfc.translator.OpenStackSFCTranslatorProvider"
- init-method="start" destroy-method="close">
- <argument ref="dataBroker" />
- <argument ref="rspService" />
- <argument ref="openstackSfcTranslatorConfig" />
- <argument ref="blueprintBundleContext" />
- </bean>
-
-</blueprint>
\ No newline at end of file
+++ /dev/null
-module openstack-sfc-translator-config {
- yang-version 1;
- namespace "urn:opendaylight:params:xml:ns:yang:netvirt:openstack:sfc:translator:config";
- prefix "openstack-sfc-translator-config";
-
- description
- "Service configuration for OpenStack sfc translator project";
-
- revision "2016-07-20" {
- description
- "Initial revision";
- }
-
- container openstack-sfc-translator-config {
- }
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
-
- This program and the accompanying materials are made available under the
- terms of the Eclipse Public License v1.0 which accompanies this distribution,
- and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>karaf4-parent</artifactId>
- <version>1.9.0</version>
- <relativePath/>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>openstack.sfc-translator-karaf</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>openstack.sfc-translator-artifacts</artifactId>
- <version>${project.version}</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- </dependencies>
- </dependencyManagement>
- <dependencies>
- <dependency>
- <!-- scope is compile so all features (there is only one) are installed
- into startup.properties and the feature repo itself is not installed -->
- <groupId>org.apache.karaf.features</groupId>
- <artifactId>framework</artifactId>
- <type>kar</type>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>openstack.sfc-translator-features4</artifactId>
- <version>${project.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- <scope>runtime</scope>
- </dependency>
- </dependencies>
- <!-- DO NOT install or deploy the karaf artifact -->
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-deploy-plugin</artifactId>
- <configuration>
- <skip>true</skip>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-Copyright © 2015 Red Hat, Inc. and others. All rights reserved.
-This program and the accompanying materials are made available under the
-terms of the Eclipse Public License v1.0 which accompanies this distribution,
-and is available at http://www.eclipse.org/legal/epl-v10.html INTERNAL
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>odlparent-lite</artifactId>
- <version>2.0.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>openstack.sfc-translator-aggregator</artifactId>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>pom</packaging>
- <modelVersion>4.0.0</modelVersion>
- <modules>
- <module>impl</module>
- <module>karaf</module>
- <module>features</module>
- <module>artifacts</module>
- </modules>
- <properties>
- <neutron.model.version>0.9.0-SNAPSHOT</neutron.model.version>
- </properties>
- <!-- DO NOT install or deploy the repo root pom as it's only needed to initiate a build -->
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.neutron</groupId>
- <artifactId>model</artifactId>
- <version>${neutron.model.version}</version>
- </dependency>
- </dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-deploy-plugin</artifactId>
- <configuration>
- <skip>true</skip>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-install-plugin</artifactId>
- <configuration>
- <skip>true</skip>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
- <scm>
- <connection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</connection>
- <developerConnection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</developerConnection>
- <tag>HEAD</tag>
- <url>https://wiki.opendaylight.org/view/NetVirt</url>
- </scm>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
-
-This program and the accompanying materials are made available under the
-terms of the Eclipse Public License v1.0 which accompanies this distribution,
-and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-parent</artifactId>
- <version>0.7.0-SNAPSHOT</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>utils.config</artifactId>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>jar</packaging>
- <description>The OVSDB Plugin integration project is a project for OpenDaylight that will implement the Open vSwitch Database RFC 7047 management protocol allowing the Southbound configuration of vSwitches and a network virtualization implementation.</description>
- <licenses>
- <license>
- <name>Eclipse Public License v1.0</name>
- <url>http://www.eclipse.org/legal/epl-v10.html</url>
- </license>
- </licenses>
- <developers>
- <developer>
- <name>Sam Hague</name>
- <email>shague@gmail.com</email>
- <url>https://github.com/shague</url>
- </developer>
- </developers>
- <scm>
- <connection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</connection>
- <developerConnection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</developerConnection>
- <tag>HEAD</tag>
- <url>https://wiki.opendaylight.org/view/OVSDB_Integration:Main</url>
- </scm>
-
- <dependencies>
- <!-- testing dependencies -->
- <dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-core</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-api-mockito</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-core</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-module-junit4</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.jacoco</groupId>
- <artifactId>jacoco-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>default-instrument</id>
- <goals>
- <goal>instrument</goal>
- </goals>
- </execution>
- <execution>
- <id>default-restore-instrumented-classes</id>
- <goals>
- <goal>restore-instrumented-classes</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-/*
- * Copyright (c) 2014, 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.utils.config;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.FrameworkUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public final class ConfigProperties {
- private static final Logger LOG = LoggerFactory.getLogger(ConfigProperties.class);
- private static final Map<String, String> OVERRIDES = new HashMap<>();
-
- private ConfigProperties() {
- // empty
- }
-
- public static String getProperty(Class<?> classParam, final String propertyStr) {
- return getProperty(classParam, propertyStr, null);
- }
-
- public static String getProperty(Class<?> classParam, final String propertyStr, final String defaultValue) {
- String value = ConfigProperties.OVERRIDES.get(propertyStr);
- if (value != null) {
- return value;
- }
-
- Bundle bundle = FrameworkUtil.getBundle(classParam);
-
- if (bundle != null) {
- BundleContext bundleContext = bundle.getBundleContext();
- if (bundleContext != null) {
- value = bundleContext.getProperty(propertyStr);
- }
- }
- if (value == null) {
- value = System.getProperty(propertyStr, defaultValue);
- }
-
- if (value == null) {
- LOG.debug("ConfigProperties missing a value for {}, default {}", propertyStr, defaultValue);
- }
-
- return value;
- }
-
- public static void overrideProperty(String property, String value) {
- ConfigProperties.OVERRIDES.put(property, value);
- }
-}
+++ /dev/null
-/*
- * Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.utils.config;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.mockito.Mockito.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.powermock.api.mockito.PowerMockito;
-import org.osgi.framework.FrameworkUtil;
-import org.powermock.core.classloader.annotations.PrepareForTest;
-import org.powermock.modules.junit4.PowerMockRunner;
-
-@RunWith(PowerMockRunner.class)
-@PrepareForTest( {System.class, FrameworkUtil.class} )
- public class ConfigPropertiesTest {
-
- private static final String TEST_PROPERTY_KEY1 = "foobar34465$3467";
- private static final String TEST_PROPERTY_MOCK_VALUE1 = "xbarMock1";
- private static final String TEST_PROPERTY_KEY2 = "foobar34465$3468";
- private static final String TEST_PROPERTY_MOCK_VALUE2 = "xbarMock2";
- private static final String TEST_PROPERTY_KEY_NOT_FOUND = "foobarKey2_12445^%346";
- private static final String DEFAULT_PROPERTY_VALUE = "xbarDefaultValue";
-
- @Test
- public void testGetProperty() {
- Bundle bundleWithoutBundleNoContext = mock(Bundle.class);
- Bundle bundle = mock(Bundle.class);
- BundleContext bundleContext = mock(BundleContext.class);
-
- // mock #1
- PowerMockito.mockStatic(FrameworkUtil.class);
- PowerMockito.when(FrameworkUtil.getBundle(this.getClass())).thenReturn(bundle);
- PowerMockito.when(FrameworkUtil.getBundle(ConfigPropertiesTestMockingBundleNoContext.class))
- .thenReturn(bundleWithoutBundleNoContext);
- // mock #2
- when(bundle.getBundleContext()).thenReturn(bundleContext);
- when(bundleWithoutBundleNoContext.getBundleContext()).thenReturn(null);
- // mock #3
- when(bundleContext.getProperty(eq(TEST_PROPERTY_KEY1))).thenReturn(TEST_PROPERTY_MOCK_VALUE1);
- // mock #4
- // PowerMockito.mockStatic(System.class);
- // PowerMockito.when(System.getProperty(eq(TEST_PROPERTY_KEY2))).thenReturn(TEST_PROPERTY_MOCK_VALUE2);
- // NOTE: The mock #4 above is not supported by PowerMockito. To work around this limitation,
- // we will simply add the property explicitly into System (instead of the solution mentioned in link below).
- // See: http://javax0.wordpress.com/2013/01/29/how-to-mock-the-system-class/
- System.setProperty(TEST_PROPERTY_KEY2, TEST_PROPERTY_MOCK_VALUE2);
-
- // test 1. bundle is null, returned from a mock
- assertNull(FrameworkUtil.getBundle(ConfigPropertiesTestMocking.class));
- assertEquals(FrameworkUtil.getBundle(ConfigPropertiesTest.class), bundle);
- assertEquals(FrameworkUtil.getBundle(ConfigPropertiesTestMockingBundleNoContext.class),
- bundleWithoutBundleNoContext);
-
- // test 2. bundleContext is null
- assertNull(bundleWithoutBundleNoContext.getBundleContext());
- assertEquals(bundle.getBundleContext(), bundleContext);
-
- // test 3. value returned from bundleContext.getProperty() is null.
- // Then System.getProperty() is called and can return a valid value if key is found.
- final String value31 = ConfigProperties.getProperty(this.getClass(), TEST_PROPERTY_KEY2);
- assertEquals(TEST_PROPERTY_MOCK_VALUE2, value31);
-
- // test 4. value returned from ConfigProperties.getProperty is null
- final String value41 = ConfigProperties.getProperty(ConfigPropertiesTestMocking.class, TEST_PROPERTY_KEY1);
- assertNull(value41); // class has no bundle
- final String value42 = ConfigProperties.getProperty(ConfigPropertiesTestMockingBundleNoContext.class,
- TEST_PROPERTY_KEY1);
- assertNull(value42); // class has no bundleContext
- final String value43 = ConfigProperties.getProperty(this.getClass(), TEST_PROPERTY_KEY_NOT_FOUND);
- assertNull(value43); // bundleContext will not know about key provided
-
- // test 5. value returned from ConfigProperties.getProperty is the default value provided
- final String value5 = ConfigProperties.getProperty(this.getClass(), TEST_PROPERTY_KEY_NOT_FOUND, DEFAULT_PROPERTY_VALUE);
- assertEquals(DEFAULT_PROPERTY_VALUE, value5);
-
- // test 6. value returned from ConfigProperties.getProperty is the mocked value
- final String value61 = ConfigProperties.getProperty(this.getClass(), TEST_PROPERTY_KEY1);
- assertEquals(TEST_PROPERTY_MOCK_VALUE1, value61);
- final String value62 = ConfigProperties.getProperty(this.getClass(), TEST_PROPERTY_KEY1, DEFAULT_PROPERTY_VALUE);
- assertEquals(TEST_PROPERTY_MOCK_VALUE1, value62);
- }
-
- // Helper classes used to de-mux mock behaviors
- private class ConfigPropertiesTestMockingBundleNoContext {
- }
- private class ConfigPropertiesTestMocking {
- }
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
-
-This program and the accompanying materials are made available under the
-terms of the Eclipse Public License v1.0 which accompanies this distribution,
-and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-parent</artifactId>
- <version>0.7.0-SNAPSHOT</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>utils.mdsal-openflow</artifactId>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>jar</packaging>
- <description>The OVSDB Plugin integration project is a project for OpenDaylight that will implement the Open vSwitch Database RFC 7047 management protocol allowing the Southbound configuration of vSwitches and a network virtualization implementation.</description>
- <licenses>
- <license>
- <name>Eclipse Public License v1.0</name>
- <url>http://www.eclipse.org/legal/epl-v10.html</url>
- </license>
- </licenses>
- <developers>
- <developer>
- <name>Sam Hague</name>
- <email>shague@gmail.com</email>
- <url>https://github.com/shague</url>
- </developer>
- </developers>
- <scm>
- <connection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</connection>
- <developerConnection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</developerConnection>
- <tag>HEAD</tag>
- <url>https://wiki.opendaylight.org/view/OVSDB_Integration:Main</url>
- </scm>
-
- <properties>
- <openflowplugin.version>0.5.0-SNAPSHOT</openflowplugin.version>
- </properties>
-
- <dependencies>
- <!-- controller dependencies -->
- <dependency>
- <groupId>org.opendaylight.controller.model</groupId>
- <artifactId>model-inventory</artifactId>
- </dependency>
- <!-- mdsal dependencies -->
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>ietf-inet-types-2013-07-15</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>ietf-inet-types-2013-07-15</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>ietf-yang-types-20130715</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>opendaylight-l2-types</artifactId>
- </dependency>
- <!-- openflowplugin dependencies -->
- <dependency>
- <groupId>org.opendaylight.openflowplugin.model</groupId>
- <artifactId>model-flow-base</artifactId>
- <version>${openflowplugin.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.openflowplugin</groupId>
- <artifactId>openflowjava-extension-nicira</artifactId>
- <version>${openflowplugin.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.openflowplugin</groupId>
- <artifactId>openflowplugin-extension-api</artifactId>
- <version>${openflowplugin.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.openflowplugin</groupId>
- <artifactId>openflowplugin-extension-nicira</artifactId>
- <version>${openflowplugin.version}</version>
- </dependency>
- <!-- testing dependencies -->
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <extensions>true</extensions>
- <configuration>
- <instructions>
- <Export-Package>
- org.opendaylight.netvirt.utils.mdsal.openflow
- </Export-Package>
- </instructions>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-/*
- * Copyright (c) 2014 - 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.utils.mdsal.openflow;
-
-import com.google.common.net.InetAddresses;
-import java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.List;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.DecNwTtlCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.DropActionCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.GroupActionCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.OutputActionCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.PopVlanActionCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.SetDlDstActionCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.SetDlSrcActionCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.SetFieldCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.SetNwDstActionCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.SetNwSrcActionCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.dec.nw.ttl._case.DecNwTtlBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.drop.action._case.DropActionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.group.action._case.GroupActionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.output.action._case.OutputActionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.pop.vlan.action._case.PopVlanActionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.set.dl.dst.action._case.SetDlDstActionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.set.dl.src.action._case.SetDlSrcActionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.set.field._case.SetFieldBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.set.nw.dst.action._case.SetNwDstActionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.set.nw.src.action._case.SetNwSrcActionBuilder;
-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;
-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.inventory.rev130819.NodeConnectorId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.Icmpv4MatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.TunnelBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.action.rev140421.OfjNxHashFields;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.action.rev140421.OfjNxMpAlgorithm;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.dst.choice.grouping.DstChoice;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.dst.choice.grouping.dst.choice.DstNxArpShaCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.dst.choice.grouping.dst.choice.DstNxArpThaCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.dst.choice.grouping.dst.choice.DstNxNshMdtypeCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.dst.choice.grouping.dst.choice.DstNxNshNpCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.dst.choice.grouping.dst.choice.DstNxNshc1CaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.dst.choice.grouping.dst.choice.DstNxNshc2CaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.dst.choice.grouping.dst.choice.DstNxNshc3CaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.dst.choice.grouping.dst.choice.DstNxNshc4CaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.dst.choice.grouping.dst.choice.DstNxNspCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.dst.choice.grouping.dst.choice.DstNxNsiCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.dst.choice.grouping.dst.choice.DstNxRegCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.dst.choice.grouping.dst.choice.DstNxTunIdCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.dst.choice.grouping.dst.choice.DstNxTunIpv4DstCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.dst.choice.grouping.dst.choice.DstOfArpOpCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.dst.choice.grouping.dst.choice.DstOfArpSpaCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.dst.choice.grouping.dst.choice.DstOfArpTpaCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.dst.choice.grouping.dst.choice.DstOfEthDstCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.dst.choice.grouping.dst.choice.DstOfIpDstCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nodes.node.group.buckets.bucket.action.action.NxActionRegLoadNodesNodeGroupBucketsBucketActionsCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nodes.node.group.buckets.bucket.action.action.NxActionRegMoveNodesNodeGroupBucketsBucketActionsCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nodes.node.table.flow.instructions.instruction.instruction.apply.actions._case.apply.actions.action.action.NxActionConntrackNodesNodeTableFlowApplyActionsCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nodes.node.table.flow.instructions.instruction.instruction.apply.actions._case.apply.actions.action.action.NxActionMultipathNodesNodeTableFlowApplyActionsCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nodes.node.table.flow.instructions.instruction.instruction.apply.actions._case.apply.actions.action.action.NxActionOutputRegNodesNodeTableFlowApplyActionsCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nodes.node.table.flow.instructions.instruction.instruction.apply.actions._case.apply.actions.action.action.NxActionPopNshNodesNodeTableFlowApplyActionsCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nodes.node.table.flow.instructions.instruction.instruction.apply.actions._case.apply.actions.action.action.NxActionPushNshNodesNodeTableFlowApplyActionsCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nodes.node.table.flow.instructions.instruction.instruction.apply.actions._case.apply.actions.action.action.NxActionRegLoadNodesNodeTableFlowApplyActionsCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nodes.node.table.flow.instructions.instruction.instruction.apply.actions._case.apply.actions.action.action.NxActionRegMoveNodesNodeTableFlowApplyActionsCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nodes.node.table.flow.instructions.instruction.instruction.apply.actions._case.apply.actions.action.action.NxActionResubmitNodesNodeTableFlowApplyActionsCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.conntrack.grouping.NxConntrack;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.conntrack.grouping.NxConntrackBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.multipath.grouping.NxMultipath;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.multipath.grouping.NxMultipathBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.output.reg.grouping.NxOutputReg;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.output.reg.grouping.NxOutputRegBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.pop.nsh.grouping.NxPopNsh;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.pop.nsh.grouping.NxPopNshBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.push.nsh.grouping.NxPushNsh;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.push.nsh.grouping.NxPushNshBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.reg.load.grouping.NxRegLoad;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.reg.load.grouping.NxRegLoadBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.reg.load.grouping.nx.reg.load.DstBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.reg.move.grouping.NxRegMove;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.reg.move.grouping.NxRegMoveBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.reg.move.grouping.nx.reg.move.SrcBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.resubmit.grouping.NxResubmit;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.resubmit.grouping.NxResubmitBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.src.choice.grouping.SrcChoice;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.src.choice.grouping.src.choice.SrcNxArpShaCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.src.choice.grouping.src.choice.SrcNxNshc1CaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.src.choice.grouping.src.choice.SrcNxNshc2CaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.src.choice.grouping.src.choice.SrcNxRegCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.src.choice.grouping.src.choice.SrcNxTunIdCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.src.choice.grouping.src.choice.SrcNxTunIpv4DstCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.src.choice.grouping.src.choice.SrcOfArpSpaCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.src.choice.grouping.src.choice.SrcOfEthSrcCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.src.choice.grouping.src.choice.SrcOfIpSrcCaseBuilder;
-
-public final class ActionUtils {
- public static Action dropAction() {
- return new DropActionCaseBuilder()
- .setDropAction(new DropActionBuilder()
- .build())
- .build();
- }
-
- public static Action outputAction(NodeConnectorId id) {
- return new OutputActionCaseBuilder()
- .setOutputAction(new OutputActionBuilder()
- .setOutputNodeConnector(new Uri(id.getValue()))
- .build())
- .build();
- }
-
- public static Action groupAction(Long id) {
- return new GroupActionCaseBuilder()
- .setGroupAction(new GroupActionBuilder()
- .setGroupId(id)
- .build())
- .build();
- }
-
- public static Action popVlanAction() {
- return new PopVlanActionCaseBuilder()
- .setPopVlanAction(new PopVlanActionBuilder()
- .build())
- .build();
- }
-
- public static Action setDlSrcAction(MacAddress mac) {
- return new SetDlSrcActionCaseBuilder()
- .setSetDlSrcAction(new SetDlSrcActionBuilder()
- .setAddress(mac)
- .build())
- .build();
- }
-
- public static Action setDlDstAction(MacAddress mac) {
- return new SetDlDstActionCaseBuilder()
- .setSetDlDstAction(new SetDlDstActionBuilder()
- .setAddress(mac)
- .build())
- .build();
- }
-
- public static Action setNwSrcAction(Address ip) {
- return new SetNwSrcActionCaseBuilder()
- .setSetNwSrcAction(new SetNwSrcActionBuilder()
- .setAddress(ip)
- .build())
- .build();
- }
-
- public static Action setNwDstAction(Address ip) {
- return new SetNwDstActionCaseBuilder()
- .setSetNwDstAction(new SetNwDstActionBuilder()
- .setAddress(ip)
- .build())
- .build();
- }
-
- public static Action decNwTtlAction() {
- return new DecNwTtlCaseBuilder()
- .setDecNwTtl(new DecNwTtlBuilder()
- .build())
- .build();
- }
-
- public static Action setTunnelIdAction(BigInteger tunnelId) {
-
- SetFieldBuilder setFieldBuilder = new SetFieldBuilder();
-
- // Build the Set Tunnel Field Action
- TunnelBuilder tunnel = new TunnelBuilder();
- tunnel.setTunnelId(tunnelId);
- setFieldBuilder.setTunnel(tunnel.build());
-
- return new SetFieldCaseBuilder()
- .setSetField(setFieldBuilder.build())
- .build();
- }
-
- public static Action nxLoadRegAction(DstChoice dstChoice,
- BigInteger value,
- int endOffset,
- boolean groupBucket) {
- NxRegLoad r = new NxRegLoadBuilder()
- .setDst(new DstBuilder()
- .setDstChoice(dstChoice)
- .setStart(0)
- .setEnd(endOffset)
- .build())
- .setValue(value)
- .build();
- if (groupBucket) {
- return new NxActionRegLoadNodesNodeGroupBucketsBucketActionsCaseBuilder()
- .setNxRegLoad(r).build();
- } else {
- return new NxActionRegLoadNodesNodeTableFlowApplyActionsCaseBuilder()
- .setNxRegLoad(r).build();
- }
- }
-
- public static Action nxLoadRegAction(DstChoice dstChoice,
- BigInteger value) {
- return nxLoadRegAction(dstChoice, value, 31, false);
- }
-
- public static Action nxLoadRegAction(Class<? extends NxmNxReg> reg,
- BigInteger value) {
- return nxLoadRegAction(new DstNxRegCaseBuilder().setNxReg(reg).build(),
- value);
- }
-
- public static Action nxLoadTunIPv4Action(String ipAddress,
- boolean groupBucket) {
- int ip = InetAddresses.coerceToInteger(InetAddresses.forString(ipAddress));
- long ipl = ip & 0xffffffffL;
- return nxLoadRegAction(new DstNxTunIpv4DstCaseBuilder()
- .setNxTunIpv4Dst(Boolean.TRUE).build(),
- BigInteger.valueOf(ipl),
- 31,
- groupBucket);
- }
-
- public static Action nxLoadArpOpAction(BigInteger value) {
- return nxLoadRegAction(new DstOfArpOpCaseBuilder()
- .setOfArpOp(Boolean.TRUE).build(), value, 15, false);
- }
-
- public static Action nxLoadArpShaAction(MacAddress macAddress) {
- return nxLoadArpShaAction(BigInteger.valueOf(toLong(macAddress)));
- }
- public static Action nxLoadArpShaAction(BigInteger value) {
- return nxLoadRegAction(new DstNxArpShaCaseBuilder()
- .setNxArpSha(Boolean.TRUE).build(), value, 47, false);
- }
-
- public static Action nxLoadArpSpaAction(BigInteger value) {
- return nxLoadRegAction(new DstOfArpSpaCaseBuilder()
- .setOfArpSpa(Boolean.TRUE).build(), value);
- }
-
- public static Action nxLoadArpSpaAction(String ipAddress) {
- int ip = InetAddresses.coerceToInteger(InetAddresses.forString(ipAddress));
- long ipl = ip & 0xffffffffL;
- return nxLoadArpSpaAction(BigInteger.valueOf(ipl));
- }
-
- public static Action setIcmpTypeAction(byte value) {
- SetFieldBuilder setFieldBuilder = new SetFieldBuilder();
- setFieldBuilder.setIcmpv4Match(new Icmpv4MatchBuilder().setIcmpv4Type((short)value).build());
- return new SetFieldCaseBuilder()
- .setSetField(setFieldBuilder.build())
- .build();
- }
-
- public static Action nxMoveRegAction(SrcChoice srcChoice,
- DstChoice dstChoice,
- int endOffset,
- boolean groupBucket) {
- return nxMoveRegAction(srcChoice, dstChoice, 0, 0, endOffset, groupBucket);
- }
-
- public static Action nxMoveRegAction(SrcChoice srcChoice,
- DstChoice dstChoice,
- int srcStartOffset,
- int dstStartOffset,
- int dstEndOffset,
- boolean groupBucket) {
- NxRegMove r = new NxRegMoveBuilder()
- .setSrc(new SrcBuilder()
- .setSrcChoice(srcChoice)
- .setStart(srcStartOffset)
- .build())
- .setDst(new org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.reg.move.grouping.nx.reg.move.DstBuilder()
- .setDstChoice(dstChoice)
- .setStart(dstStartOffset)
- .setEnd(dstEndOffset)
- .build())
- .build();
- if (groupBucket) {
- return new NxActionRegMoveNodesNodeGroupBucketsBucketActionsCaseBuilder()
- .setNxRegMove(r).build();
- } else {
- return new NxActionRegMoveNodesNodeTableFlowApplyActionsCaseBuilder()
- .setNxRegMove(r).build();
- }
- }
-
- public static Action nxMoveRegAction(SrcChoice srcChoice,
- DstChoice dstChoice) {
- return nxMoveRegAction(srcChoice, dstChoice, 31, false);
- }
-
- public static Action nxMoveRegTunIdAction(Class<? extends NxmNxReg> src,
- boolean groupBucket) {
- return nxMoveRegAction(new SrcNxRegCaseBuilder().setNxReg(src).build(),
- new DstNxTunIdCaseBuilder().setNxTunId(Boolean.TRUE).build(),
- 31,
- groupBucket);
- }
-
- public static Action nxMoveArpShaToArpThaAction() {
- return nxMoveRegAction(new SrcNxArpShaCaseBuilder().setNxArpSha(Boolean.TRUE).build(),
- new DstNxArpThaCaseBuilder().setNxArpTha(Boolean.TRUE).build(),
- 47, false);
- }
-
- public static Action nxMoveEthSrcToEthDstAction() {
- return nxMoveRegAction(new SrcOfEthSrcCaseBuilder().setOfEthSrc(Boolean.TRUE).build(),
- new DstOfEthDstCaseBuilder().setOfEthDst(Boolean.TRUE).build(),
- 47, false);
- }
-
- public static Action nxMoveArpSpaToArpTpaAction() {
- return nxMoveRegAction(new SrcOfArpSpaCaseBuilder().setOfArpSpa(Boolean.TRUE).build(),
- new DstOfArpTpaCaseBuilder().setOfArpTpa(Boolean.TRUE).build());
- }
-
- public static Action nxMoveIpSrcToIpDstAction() {
- return nxMoveRegAction(new SrcOfIpSrcCaseBuilder().setOfIpSrc(Boolean.TRUE).build(),
- new DstOfIpDstCaseBuilder().setOfIpDst(Boolean.TRUE).build());
- }
-
-
- public static Action nxOutputRegAction(SrcChoice srcChoice) {
- NxOutputReg r = new NxOutputRegBuilder()
- .setSrc(new org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.output.reg.grouping.nx.output.reg.SrcBuilder()
- .setSrcChoice(srcChoice)
- .setOfsNbits(31)
- .build())
- .setMaxLen(0xffff)
- .build();
- return new NxActionOutputRegNodesNodeTableFlowApplyActionsCaseBuilder()
- .setNxOutputReg(r).build();
- }
-
- public static Action nxOutputRegAction(Class<? extends NxmNxReg> reg) {
- return nxOutputRegAction(new SrcNxRegCaseBuilder().setNxReg(reg).build());
- }
-
- public static Action nxResubmitAction(Integer inPort, Short table) {
- NxResubmitBuilder builder = new NxResubmitBuilder();
- if (inPort != null) {
- builder.setInPort(inPort);
- }
- if (table != null) {
- builder.setTable(table);
- }
- NxResubmit r = builder.build();
- return new NxActionResubmitNodesNodeTableFlowApplyActionsCaseBuilder().setNxResubmit(r).build();
- }
-
- public static Action nxPushNshAction() {
- NxPushNshBuilder builder = new NxPushNshBuilder();
- NxPushNsh r = builder.build();
- return new NxActionPushNshNodesNodeTableFlowApplyActionsCaseBuilder().setNxPushNsh(r).build();
- }
-
- public static Action nxPopNshAction() {
- NxPopNshBuilder builder = new NxPopNshBuilder();
- NxPopNsh r = builder.build();
- return new NxActionPopNshNodesNodeTableFlowApplyActionsCaseBuilder().setNxPopNsh(r).build();
- }
-
- public static Action nxLoadNshMdtypeAction(Short value) {
- return nxLoadRegAction(
- new DstNxNshMdtypeCaseBuilder().setNxNshMdtype(Boolean.TRUE).build(),
- BigInteger.valueOf(value.longValue()),
- 7,
- false
- );
- }
-
- public static Action nxLoadNshNpAction(Short value) {
- return nxLoadRegAction(
- new DstNxNshNpCaseBuilder().setNxNshNp(Boolean.TRUE).build(),
- BigInteger.valueOf(value),
- 7,
- false
- );
- }
-
- public static Action nxSetNspAction(Long nsp) {
- return nxLoadRegAction(
- new DstNxNspCaseBuilder().setNxNspDst(Boolean.TRUE).build(),
- BigInteger.valueOf(nsp),
- 23,
- false
- );
- }
-
- public static Action nxSetNsiAction(Short nsi) {
- return nxLoadRegAction(
- new DstNxNsiCaseBuilder().setNxNsiDst(Boolean.TRUE).build(),
- BigInteger.valueOf(nsi.longValue()),
- 7,
- false
- );
- }
-
- public static Action nxLoadNshc1RegAction(Long value) {
- return nxLoadRegAction(
- new DstNxNshc1CaseBuilder().setNxNshc1Dst(Boolean.TRUE).build(),
- BigInteger.valueOf(value),
- 31,
- false
- );
- }
-
- public static Action nxLoadNshc2RegAction(Long value) {
- return nxLoadRegAction(
- new DstNxNshc2CaseBuilder().setNxNshc2Dst(Boolean.TRUE).build(),
- BigInteger.valueOf(value),
- 31,
- false
- );
- }
-
- public static Action nxLoadNshc3RegAction(Long value) {
- return nxLoadRegAction(
- new DstNxNshc3CaseBuilder().setNxNshc3Dst(Boolean.TRUE).build(),
- BigInteger.valueOf(value),
- 31,
- false
- );
- }
-
- public static Action nxLoadNshc4RegAction(Long value) {
- return nxLoadRegAction(
- new DstNxNshc4CaseBuilder().setNxNshc4Dst(Boolean.TRUE).build(),
- BigInteger.valueOf(value),
- 31,
- false
- );
- }
-
- public static Action nxMoveRegTunDstToNshc1() {
- return nxMoveRegAction(
- new SrcNxTunIpv4DstCaseBuilder().setNxTunIpv4Dst(Boolean.TRUE).build(),
- new DstNxNshc1CaseBuilder().setNxNshc1Dst(Boolean.TRUE).build(),
- 31, false);
- }
-
- public static Action nxMoveTunIdtoNshc2() {
- return nxMoveRegAction(
- new SrcNxTunIdCaseBuilder().setNxTunId(Boolean.TRUE).build(),
- new DstNxNshc2CaseBuilder().setNxNshc2Dst(Boolean.TRUE).build(),
- 31, false);
- }
-
- public static Action nxMoveNshc1ToTunIpv4Dst() {
- return nxMoveRegAction(
- new SrcNxNshc1CaseBuilder().setNxNshc1Dst(Boolean.TRUE).build(),
- new DstNxTunIpv4DstCaseBuilder().setNxTunIpv4Dst(Boolean.TRUE).build(),
- 31, false);
- }
-
- public static Action nxMoveNshc2ToTunId() {
- return nxMoveRegAction(
- new SrcNxNshc2CaseBuilder().setNxNshc2Dst(Boolean.TRUE).build(),
- new DstNxTunIdCaseBuilder().setNxTunId(Boolean.TRUE).build(),
- 31, false);
- }
-
- public static Action nxLoadTunIdAction(BigInteger tunnelId, boolean groupBucket) {
- return nxLoadRegAction(new DstNxTunIdCaseBuilder().setNxTunId(Boolean.TRUE).build(), tunnelId, 31, groupBucket);
- }
-
- public static Action nxMultipathAction(OfjNxHashFields fields, Integer basis,
- OfjNxMpAlgorithm algorithm, Integer maxLink, Long arg, DstChoice dstChoice,
- Integer start, Integer end) {
- NxMultipath r = new NxMultipathBuilder()
- .setFields(fields)
- .setBasis(basis)
- .setAlgorithm(algorithm)
- .setMaxLink(maxLink)
- .setArg(arg)
- .setDst(new org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.nx.action.multipath.grouping.nx.multipath.DstBuilder()
- .setDstChoice(dstChoice)
- .setStart(start)
- .setEnd(end)
- .build())
- .build();
- return new NxActionMultipathNodesNodeTableFlowApplyActionsCaseBuilder().setNxMultipath(r).build();
- }
-
- /**
- * Builds the conntrack action.
- * @param flags the flags for the action
- * @param zoneSrc the zoneSrc
- * @param conntrackZone the conntrackZone
- * @param recircTable the recirc table if it is a recirc action
- * @return the conntrack action.
- */
- public static Action nxConntrackAction(Integer flags, Long zoneSrc,
- Integer conntrackZone, Short recircTable) {
- NxConntrack r = new NxConntrackBuilder()
- .setFlags(flags)
- .setZoneSrc(zoneSrc)
- .setConntrackZone(conntrackZone)
- .setRecircTable(recircTable)
- .build();
- return new NxActionConntrackNodesNodeTableFlowApplyActionsCaseBuilder().setNxConntrack(r).build();
- }
-
- /**
- * Builds the apply action builder for the action
- * @param action the conntrack action.
- * @return the apply action builder.
- */
- public static ApplyActionsBuilder conntrackActionBuilder(Action action) {
- ActionBuilder ab = new ActionBuilder();
- ab.setAction(action);
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
- List<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action> actionList =
- new ArrayList<>();
- actionList.add(ab.build());
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
- return aab;
- }
- /**
- * Accepts a MAC address and returns the corresponding long, where the
- * MAC bytes are set on the lower order bytes of the long.
- * @param macAddress
- * @return a long containing the mac address bytes
- */
- public static long toLong(byte[] macAddress) {
- long mac = 0;
- for (int i = 0; i < 6; i++) {
- long t = (macAddress[i] & 0xffL) << ((5-i)*8);
- mac |= t;
- }
- return mac;
- }
-
- /**
- * Accepts a MAC address of the form 00:aa:11:bb:22:cc, case does not
- * matter, and returns the corresponding long, where the MAC bytes are set
- * on the lower order bytes of the long.
- *
- * @param macAddress
- * in String format
- * @return a long containing the mac address bytes
- */
- public static long toLong(MacAddress macAddress) {
- return toLong(toMACAddress(macAddress.getValue()));
- }
-
- /**
- * Accepts a MAC address of the form 00:aa:11:bb:22:cc, case does not
- * matter, and returns a corresponding byte[].
- * @param macAddress
- * @return
- */
- public static byte[] toMACAddress(String macAddress) {
- final String HEXES = "0123456789ABCDEF";
- byte[] address = new byte[6];
- String[] macBytes = macAddress.split(":");
- if (macBytes.length != 6) {
- throw new IllegalArgumentException(
- "Specified MAC Address must contain 12 hex digits" +
- " separated pairwise by :'s.");
- }
- for (int i = 0; i < 6; ++i) {
- address[i] = (byte) ((HEXES.indexOf(macBytes[i].toUpperCase()
- .charAt(0)) << 4) | HEXES.indexOf(macBytes[i].toUpperCase()
- .charAt(1)));
- }
- return address;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 - 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.utils.mdsal.openflow;
-
-import com.google.common.base.Optional;
-
-import java.util.concurrent.ExecutionException;
-
-import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
-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.MatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg0;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class FlowUtils {
- private static final Logger LOG = LoggerFactory.getLogger(FlowUtils.class);
- private static final String OPENFLOW = "openflow";
- public final static long REG_VALUE_FROM_LOCAL = 0x1L;
- public final static long REG_VALUE_FROM_REMOTE = 0x2L;
- public static final Class<? extends NxmNxReg> REG_FIELD = NxmNxReg0.class;
- public static final int ARP_OP_REQUEST = 0x1;
- public static final int ARP_OP_REPLY = 0x2;
-
-
- public static String getNodeName(long dpidLong) {
- return OPENFLOW + ":" + dpidLong;
- }
-
- public static NodeConnectorId getNodeConnectorId(long ofPort, String nodeName) {
- return new NodeConnectorId(nodeName + ":" + ofPort);
- }
-
- public static NodeConnectorId getSpecialNodeConnectorId(long dpidLong, String portName) {
- return new NodeConnectorId(getNodeName(dpidLong) + ":" + portName);
- }
-
- public static NodeConnectorId getNodeConnectorId(long dpidLong, long ofPort) {
- return getNodeConnectorId(ofPort, getNodeName(dpidLong));
- }
-
- public static NodeBuilder createNodeBuilder(String nodeId) {
- NodeBuilder builder = new NodeBuilder();
- builder.setId(new NodeId(nodeId));
- builder.setKey(new NodeKey(builder.getId()));
- return builder;
- }
-
- public static NodeBuilder createNodeBuilder(long dpidLong) {
- return createNodeBuilder(getNodeName(dpidLong));
- }
-
- public static InstanceIdentifier<Flow> createFlowPath(FlowBuilder flowBuilder, NodeBuilder nodeBuilder) {
- return InstanceIdentifier.builder(Nodes.class)
- .child(Node.class, nodeBuilder.getKey())
- .augmentation(FlowCapableNode.class)
- .child(Table.class, new TableKey(flowBuilder.getTableId()))
- .child(Flow.class, flowBuilder.getKey()).build();
- }
-
- public static InstanceIdentifier<Table> createTablePath(NodeBuilder nodeBuilder, short table) {
- return InstanceIdentifier.builder(Nodes.class)
- .child(Node.class, nodeBuilder.getKey())
- .augmentation(FlowCapableNode.class)
- .child(Table.class, new TableKey(table)).build();
- }
-
- public static InstanceIdentifier<Node> createNodePath(NodeBuilder nodeBuilder) {
- return InstanceIdentifier.builder(Nodes.class).child(Node.class, nodeBuilder.getKey()).build();
- }
-
- public static Flow getFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder,
- ReadOnlyTransaction readTx, final LogicalDatastoreType store) {
- try {
- Optional<Flow> data = readTx.read(store, createFlowPath(flowBuilder, nodeBuilder)).get();
- if (data.isPresent()) {
- return data.get();
- }
- } catch (InterruptedException|ExecutionException e) {
- LOG.error("Failed to get flow {}", flowBuilder.getFlowName(), e);
- }
-
- LOG.info("Cannot find data for Flow {} in {}", flowBuilder.getFlowName(), store);
- return null;
- }
-
- public static Table getTable(NodeBuilder nodeBuilder, short table,
- ReadOnlyTransaction readTx, final LogicalDatastoreType store) {
- try {
- Optional<Table> data = readTx.read(store, createTablePath(nodeBuilder, table)).get();
- if (data.isPresent()) {
- return data.get();
- }
- } catch (InterruptedException|ExecutionException e) {
- LOG.error("Failed to get table {}", table, e);
- }
-
- LOG.info("Cannot find data for table {} in {}", table, store);
- return null;
- }
-
- public static FlowBuilder getPipelineFlow(short table, short gotoTable) {
- FlowBuilder flowBuilder = new FlowBuilder();
- flowBuilder.setMatch(new MatchBuilder().build());
-
- String flowName = "DEFAULT_PIPELINE_FLOW_" + table;
- return initFlowBuilder(flowBuilder, flowName, table)
- .setPriority(0);
- }
-
- /**
- * Creates a flowBuilder.
- * @param flowName the flow name
- * @param priority the priority
- * @param matchBuilder the match builder
- * @param tableNo the table no to which flow needs to be inserted.
- * @return the created flow builder.
- */
- public static FlowBuilder createFlowBuilder(String flowName,Integer priority,
- MatchBuilder matchBuilder, short tableNo) {
- FlowBuilder flowBuilder = new FlowBuilder();
- flowBuilder.setMatch(matchBuilder.build());
- initFlowBuilder(flowBuilder, flowName, tableNo).setPriority(priority);
- return flowBuilder;
- }
- /**
- * 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;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 - 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.utils.mdsal.openflow;
-
-import static org.opendaylight.netvirt.utils.mdsal.openflow.ActionUtils.dropAction;
-
-import java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Prefix;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.DecNwTtlCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.DropActionCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.OutputActionCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.OutputActionCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.PopVlanActionCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.PushVlanActionCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.SetDlDstActionCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.SetDlSrcActionCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.SetFieldCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.SetNwDstActionCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.SetNwSrcActionCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.SetVlanIdActionCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.dec.nw.ttl._case.DecNwTtl;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.dec.nw.ttl._case.DecNwTtlBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.drop.action._case.DropAction;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.drop.action._case.DropActionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.output.action._case.OutputActionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.pop.vlan.action._case.PopVlanActionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.push.vlan.action._case.PushVlanActionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.set.dl.dst.action._case.SetDlDstActionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.set.dl.src.action._case.SetDlSrcActionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.set.field._case.SetFieldBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.set.nw.dst.action._case.SetNwDstActionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.set.nw.src.action._case.SetNwSrcActionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.set.vlan.id.action._case.SetVlanIdActionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
-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;
-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.GoToTableCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.WriteMetadataCaseBuilder;
-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.instruction.go.to.table._case.GoToTableBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.write.metadata._case.WriteMetadataBuilder;
-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;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.VlanId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.arp.match.fields.ArpSourceHardwareAddressBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.arp.match.fields.ArpTargetHardwareAddressBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.Icmpv4MatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.TunnelBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.ArpMatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.TunnelIpv4MatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._4.match.TcpMatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._4.match.UdpMatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.vlan.match.fields.VlanIdBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.VlanMatchBuilder;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class InstructionUtils {
- private static final Logger LOG = LoggerFactory.getLogger(InstructionUtils.class);
- private static final int IPV4 = 0x8100;
- private static final int MAX_LENGTH = 0xffff;
- private static final int MAX_LENGTH_FOR_OUTPUT_INS = 60;
-
- /**
- * Create Send to Controller Reserved Port Instruction (packet_in)
- *
- * @param nodeName Uri Prefix, containing nodeConnectorType and dpId (aka NodeId)
- * @param ib Map InstructionBuilder without any instructions
- * @return ib Map InstructionBuilder with instructions
- */
- public static InstructionBuilder createSendToControllerInstructions(String nodeName, InstructionBuilder ib) {
-
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab = new ActionBuilder();
-
- OutputActionBuilder output = new OutputActionBuilder();
- output.setMaxLength(MAX_LENGTH);
- NodeId nodeId = new NodeId(nodeName);
- output.setOutputNodeConnector(new NodeConnectorId(nodeId.getValue() + ":"
- + OutputPortValues.CONTROLLER.toString()));
- ab.setAction(new OutputActionCaseBuilder().setOutputAction(output.build()).build());
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
- actionList.add(ab.build());
-
- // Create an Apply Action
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
-
- // Wrap our Apply Action in an Instruction
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
-
- return ib;
- }
-
- /**
- * Create NORMAL Reserved Port Instruction (packet_in)
- *
- * @param nodeName Uri Prefix, containing nodeConnectorType and dpId (aka NodeId)
- * @param ib Map InstructionBuilder without any instructions
- * @return ib Map InstructionBuilder with instructions
- */
-
- public static InstructionBuilder createNormalInstructions(String nodeName, InstructionBuilder ib) {
-
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab = new ActionBuilder();
-
- OutputActionBuilder output = new OutputActionBuilder();
- NodeId nodeId = new NodeId(nodeName);
- output.setOutputNodeConnector(new NodeConnectorId(nodeId.getValue() + ":"
- + OutputPortValues.NORMAL.toString()));
- ab.setAction(new OutputActionCaseBuilder().setOutputAction(output.build()).build());
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
- actionList.add(ab.build());
-
- // Create an Apply Action
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
-
- // Wrap our Apply Action in an Instruction
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
-
- return ib;
- }
-
- /**
- * Create LOCAL Reserved Port Instruction
- *
- * @param ib Map InstructionBuilder without any instructions
- * @param dpidLong Long the datapath ID of a switch/node
- * @return ib Map InstructionBuilder with instructions
- */
- public static InstructionBuilder createLocalInstructions(InstructionBuilder ib, long dpidLong) {
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab = new ActionBuilder();
-
- OutputActionBuilder output = new OutputActionBuilder();
- output.setOutputNodeConnector(new NodeConnectorId("openflow:" + dpidLong + ":"
- + OutputPortValues.LOCAL.toString()));
- ab.setAction(new OutputActionCaseBuilder().setOutputAction(output.build()).build());
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
- actionList.add(ab.build());
-
- // Create an Apply Action
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
-
- // Wrap our Apply Action in an Instruction
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
-
- return ib;
- }
-
- /**
- * Create Output Port Instruction
- *
- * @param ib Map InstructionBuilder without any instructions
- * @param dpidLong Long the datapath ID of a switch/node
- * @param port Long representing a port on a switch/node
- * @return ib InstructionBuilder Map with instructions
- */
- public static InstructionBuilder createOutputPortInstructions(InstructionBuilder ib, Long dpidLong, Long port) {
-
- List<Action> actionList = new ArrayList<>();
- actionList.add(createOutputActionWithIndex(actionList.size(), dpidLong, port).build());
-
- return createOutputApplyAction(ib, actionList);
- }
-
- /**
- * Create Output Port Instruction and append the list of instructions
- *
- * @param ib Map InstructionBuilder without any instructions
- * @param dpidLong Long the datapath ID of a switch/node
- * @param port Long representing a port on a switch/node
- * @param instructions the list of instructions
- * @return ib InstructionBuilder Map with instructions
- */
- public static InstructionBuilder createOutputPortInstructions(InstructionBuilder ib,
- Long dpidLong, Long port ,
- List<Instruction> instructions) {
-
- List<Action> actionList = new ArrayList<>();
- actionList.add(createOutputActionWithIndex(actionList.size(), dpidLong, port).build());
-
- List<Action> existingActions;
- for (Instruction instruction : instructions) {
- if (instruction.getInstruction() instanceof ApplyActionsCase) {
- existingActions = (((ApplyActionsCase) instruction.getInstruction()).getApplyActions().getAction());
- // Only include output actions
- for (Action action : existingActions) {
- actionList.add(action);
- }
- }
- }
-
- return createOutputApplyAction(ib, actionList);
- }
-
- /**
- * Create Output Port Instruction with specified index and add to the list.
- *
- * @param index index of the action
- * @param dpidLong Long the datapath ID of a switch/node
- * @param ofPort Long representing a port on a switch/node
- * @param outputInstructions list to add the generated actions
- */
- public static void createOutputPortInstruction(int index, Long dpidLong,
- Long ofPort, List<Instruction> outputInstructions) {
- InstructionBuilder ib = new InstructionBuilder();
- List<Action> actionList = new ArrayList<>();
- actionList.add(createOutputActionWithIndex(index, dpidLong, ofPort).build());
-
- // Create an Apply Action
- outputInstructions.add(createOutputApplyAction(ib, actionList).build());
- }
-
- private static ActionBuilder createOutputActionWithIndex(int index, long dpidLong, long ofPort) {
- NodeConnectorId ncid = new NodeConnectorId("openflow:" + dpidLong + ":" + ofPort);
- ActionBuilder ab = new ActionBuilder();
- /* Create output action for this port*/
- OutputActionBuilder oab = new OutputActionBuilder();
- oab.setOutputNodeConnector(ncid);
- ab.setAction(new OutputActionCaseBuilder().setOutputAction(oab.build()).build());
- ab.setOrder(index);
- ab.setKey(new ActionKey(index));
- return ab;
- }
-
- private static InstructionBuilder createOutputApplyAction(InstructionBuilder ib, List<Action> actionList) {
- // Create an Apply Action
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
- return ib;
- }
-
- /**
- * Create Output Port Instruction with push vlan.
- *
- * @param ib Map InstructionBuilder without any instructions
- * @param dpidLong Long the datapath ID of a switch/node
- * @param port Long representing a port on a switch/node
- * @param instructions list to add the generated actions
- * @param vlanId the vlan Id
- */
- public static InstructionBuilder createVlanOutputPortInstructions(InstructionBuilder ib,
- Long dpidLong, Long port, List<Instruction> instructions, VlanId vlanId) {
-
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab = new ActionBuilder();
-
- List<Action> existingActions;
- for (Instruction instruction : instructions) {
- if (instruction.getInstruction() instanceof ApplyActionsCase) {
- existingActions = (((ApplyActionsCase) instruction.getInstruction()).getApplyActions().getAction());
- // Only include output actions
- for (Action action : existingActions) {
- if (action.getAction() instanceof OutputActionCase) {
- actionList.add(action);
- }
- }
- }
- }
- createPushVlanInstruction(ib, dpidLong, port, vlanId, actionList);
- return ib;
- }
-
- /**
- * Create Output Port Instruction with push vlan.
- *
- * @param ib Map InstructionBuilder without any instructions
- * @param dpidLong Long the datapath ID of a switch/node
- * @param port Long representing a port on a switch/node
- * @param vlanId the vlan Id
- * @param actionList list to actions to be added.
- */
- public static InstructionBuilder createPushVlanInstruction(InstructionBuilder ib,
- Long dpidLong, Long port, VlanId vlanId, List<Action> actionList) {
-
- NodeConnectorId ncid = new NodeConnectorId("openflow:" + dpidLong + ":" + port);
- ActionBuilder ab = new ActionBuilder();
-
- /* First we push vlan header */
- PushVlanActionBuilder vlan = new PushVlanActionBuilder();
- vlan.setEthernetType(IPV4);
- ab.setAction(new PushVlanActionCaseBuilder().setPushVlanAction(vlan.build()).build());
- ab.setOrder(actionList.size());
- actionList.add(ab.build());
-
- SetFieldBuilder setFieldBuilder = new SetFieldBuilder();
-
- VlanMatchBuilder vlanMatchBuilder = new VlanMatchBuilder();
- VlanIdBuilder vlanIdBuilder = new VlanIdBuilder();
- vlanMatchBuilder.setVlanId(vlanIdBuilder.setVlanId(vlanId).setVlanIdPresent(true).build());
- setFieldBuilder.setVlanMatch(vlanMatchBuilder.build());
- ab = new ActionBuilder();
- ab.setAction(new SetFieldCaseBuilder().setSetField(setFieldBuilder.build()).build());
- ab.setOrder(actionList.size());
- actionList.add(ab.build());
-
- ab = new ActionBuilder();
- OutputActionBuilder output = new OutputActionBuilder();
- output.setMaxLength(MAX_LENGTH_FOR_OUTPUT_INS);
- output.setOutputNodeConnector(ncid);
- ab.setAction(new OutputActionCaseBuilder().setOutputAction(output.build()).build());
- ab.setOrder(actionList.size());
- actionList.add(ab.build());
-
- return createOutputApplyAction(ib, actionList);
- }
-
- /**
- * Create Output Port Instruction with Pop vlan.
- *
- * @param ib Map InstructionBuilder without any instructions
- * @param dpidLong Long the datapath ID of a switch/node
- * @param port Long representing a port on a switch/node
- * @param instructions list to add the generated actions
- */
- public static InstructionBuilder createPopOutputPortInstructions(InstructionBuilder ib,
- Long dpidLong, Long port ,
- List<Instruction> instructions) {
-
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab = new ActionBuilder();
-
- PopVlanActionBuilder popVlanActionBuilder = new PopVlanActionBuilder();
- ab.setAction(new PopVlanActionCaseBuilder().setPopVlanAction(popVlanActionBuilder.build()).build());
- ab.setOrder(0);
- actionList.add(ab.build());
- List<Action> existingActions;
- if(instructions != null && !instructions.isEmpty()) {
- for (Instruction instruction : instructions) {
- if (instruction.getInstruction() instanceof ApplyActionsCase) {
- existingActions = (((ApplyActionsCase) instruction.getInstruction()).getApplyActions().getAction());
- // Only include output actions
- for (Action action : existingActions) {
- if (action.getAction() instanceof OutputActionCase) {
- actionList.add(action);
- }
- }
- }
- }
- }
-
- if (port != null) {
- /* Create output action for this port*/
- NodeConnectorId ncid = new NodeConnectorId("openflow:" + dpidLong + ":" + port);
- OutputActionBuilder oab = new OutputActionBuilder();
- oab.setOutputNodeConnector(ncid);
- ab.setAction(new OutputActionCaseBuilder().setOutputAction(oab.build()).build());
- ab.setOrder(actionList.size());
- ab.setKey(new ActionKey(actionList.size()));
- actionList.add(ab.build());
- }
- return createOutputApplyAction(ib, actionList);
- }
-
- /**
- * add Output Port action to Instruction action list.
- * This is use for flow with single output port actions.
- * Flow with mutiple output port actions should use createOutputPortInstructions() method.
- *
- * @param ib Map InstructionBuilder without any instructions
- * @param dpidLong Long the datapath ID of a switch/node
- * @param port Long representing a port on a switch/node
- * @return ib InstructionBuilder Map with instructions
- */
- public static InstructionBuilder addOutputPortInstructions(InstructionBuilder ib,
- Long dpidLong, Long port,
- List<Instruction> instructions) {
- NodeConnectorId ncid = new NodeConnectorId("openflow:" + dpidLong + ":" + port);
- LOG.debug(
- "addOutputPortInstructions() Node Connector ID is - Type=openflow: DPID={} port={} existingInstructions={}",
- dpidLong, port, instructions);
-
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab = new ActionBuilder();
-
- List<Action> existingActions;
- if (instructions != null) {
- for (Instruction in : instructions) {
- if (in.getInstruction() instanceof ApplyActionsCase) {
- existingActions = (((ApplyActionsCase) in.getInstruction()).getApplyActions().getAction());
- actionList.addAll(existingActions);
- }
- }
- }
-
- /* Create output action for this port*/
- OutputActionBuilder oab = new OutputActionBuilder();
- oab.setOutputNodeConnector(ncid);
- ab.setAction(new OutputActionCaseBuilder().setOutputAction(oab.build()).build());
- ab.setOrder(actionList.size());
- ab.setKey(new ActionKey(actionList.size()));
- actionList.add(ab.build());
-
- // Create an Apply Action
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
-
- return ib;
- }
-
- /**
- * Remove Output Port from Instruction
- *
- * @param ib Map InstructionBuilder without any instructions
- * @param dpidLong Long the datapath ID of a switch/node
- * @param port Long representing a port on a switch/node
- * @return ib InstructionBuilder Map with instructions
- */
- public static boolean removeOutputPortFromInstructions(InstructionBuilder ib,
- Long dpidLong, Long port, List<Instruction> instructions) {
-
- final NodeConnectorId ncid = new NodeConnectorId("openflow:" + dpidLong + ":" + port);
- final Uri ncidUri = new Uri(ncid);
- LOG.debug(
- "removeOutputPortFromInstructions() Node Connector ID is - Type=openflow: DPID={} port={} existingInstructions={}",
- dpidLong, port, instructions);
-
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab;
-
- // Start of by locating actions that will have port removed, from the existing instructionList
- //
- List<Action> existingActions;
- if (instructions != null) {
- for (Instruction in : instructions) {
- if (in.getInstruction() instanceof ApplyActionsCase) {
- existingActions = (((ApplyActionsCase) in.getInstruction()).getApplyActions().getAction());
- actionList.addAll(existingActions);
- break;
- }
- }
- }
-
- int removedActionOrder = 0;
- boolean isPortDeleted = false;
- boolean removeFlow = true;
-
- // Locate specific action that has the port to be removed. Then, take note on its action order
- // and remove it from list, in addition to flag that it was found.
- //
- for (Action action : actionList) {
- if (action.getAction() instanceof OutputActionCase) {
- OutputActionCase opAction = (OutputActionCase) action.getAction();
- if (opAction.getOutputAction().getOutputNodeConnector().equals(ncidUri)) {
- /* Find the output port in action list and remove */
- removedActionOrder = action.getOrder();
- actionList.remove(action);
- isPortDeleted = true;
- break;
- }
- }
- }
-
- if (isPortDeleted) {
- // Iterate through all actions in the modified list and adjust the order of
- // the actions left behind. With that, all actions that have order higher than
- // the action removed gets their value decremented by 1. Note that this iteration
- // visits all entries to account for cases where the list order is not the same
- // as the action's order.
- //
- for (int i = 0; i < actionList.size(); i++) {
- Action action = actionList.get(i);
- if (action.getOrder() > removedActionOrder) {
- /* Shift the action by rebuilding action, using adjusted order */
- ab = new ActionBuilder();
- ab.setAction(action.getAction());
- ab.setOrder(action.getOrder() - 1);
- ab.setKey(new ActionKey(action.getOrder() - 1));
- Action actionNewOrder = ab.build();
- actionList.remove(action);
- actionList.add(i, actionNewOrder);
- } else if (action.getOrder() == removedActionOrder) {
- // Sanity: implementation assumes no two actions have the same order
- //
- LOG.error("Found action with same order as the action removed for {}, order {} index {}: {}",
- ncid, removedActionOrder, i, action);
- }
-
- // If action refers to a port output, then flow should be preserved.
- // We do this, so that if we are only left with non-output port actions,
- // we still remove the flow
- //
- if (action.getAction() instanceof OutputActionCase) {
- removeFlow = false;
- }
- }
- } else {
- // If port we are asked to delete is not found, this implementation will leave actions
- // alone and not remove the flow, as long as a remaining OutputActionCase is found.
- //
- for (Action action : actionList) {
- if (action.getAction() instanceof OutputActionCase) {
- removeFlow = false;
- break;
- }
- }
- }
-
- /* Put new action list in Apply Action instruction */
- if (!removeFlow) {
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
- LOG.debug("removeOutputPortFromInstructions() : applyAction {}", aab.build());
- return false;
- } else {
- /* if all output ports are removed. Return true to indicate flow remove */
- return true;
- }
- }
-
- /**
- * Create Set Vlan ID Instruction - This includes push vlan action, and set field -> vlan vid action
- *
- * @param ib Map InstructionBuilder without any instructions
- * @param vlanId Integer representing a VLAN ID Integer representing a VLAN ID
- * @return ib Map InstructionBuilder with instructions
- */
- public static InstructionBuilder createSetVlanInstructions(InstructionBuilder ib, VlanId vlanId) {
-
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab = new ActionBuilder();
-
- /* First we push vlan header */
- PushVlanActionBuilder vlan = new PushVlanActionBuilder();
- vlan.setEthernetType(IPV4);
- ab.setAction(new PushVlanActionCaseBuilder().setPushVlanAction(vlan.build()).build());
- ab.setOrder(0);
- actionList.add(ab.build());
-
- /* Then we set vlan id value as vlanId */
- SetVlanIdActionBuilder vl = new SetVlanIdActionBuilder();
- vl.setVlanId(vlanId);
- ab = new ActionBuilder();
- ab.setAction(new SetVlanIdActionCaseBuilder().setSetVlanIdAction(vl.build()).build());
- ab.setOrder(1);
- actionList.add(ab.build());
- // Create an Apply Action
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
-
- // Wrap our Apply Action in an Instruction
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
-
- return ib;
- }
-
- /**
- * Create Pop Vlan Instruction - this remove vlan header
- *
- * @param ib Map InstructionBuilder without any instructions
- * @return ib Map InstructionBuilder with instructions
- */
- public static InstructionBuilder createPopVlanInstructions(InstructionBuilder ib) {
-
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab = new ActionBuilder();
-
- PopVlanActionBuilder popVlanActionBuilder = new PopVlanActionBuilder();
- ab.setAction(new PopVlanActionCaseBuilder().setPopVlanAction(popVlanActionBuilder.build()).build());
- ab.setOrder(0);
- actionList.add(ab.build());
-
- // Create an Apply Action
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
-
- // Wrap our Apply Action in an Instruction
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
-
- return ib;
- }
-
- /**
- * Create Pop Vlan and Normal Instruction - this remove vlan header
- *
- * @param ib Map InstructionBuilder without any instructions
- * @return ib Map InstructionBuilder with instructions
- */
- public static InstructionBuilder createPopVlanAndNormalInstructions(InstructionBuilder ib) {
-
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab = new ActionBuilder();
-
- PopVlanActionBuilder popVlanActionBuilder = new PopVlanActionBuilder();
- ab.setAction(new PopVlanActionCaseBuilder().setPopVlanAction(popVlanActionBuilder.build()).build());
- ab.setOrder(0);
- actionList.add(ab.build());
-
- ab = new ActionBuilder();
- OutputActionBuilder output = new OutputActionBuilder();
- output.setMaxLength(60);
- Uri value = new Uri(OutputPortValues.NORMAL.toString());
- output.setOutputNodeConnector(value);
- ab.setAction(new OutputActionCaseBuilder().setOutputAction(output.build()).build());
- ab.setOrder(1);
- actionList.add(ab.build());
-
- // Create an Apply Action
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
-
- // Wrap our Apply Action in an Instruction
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
-
- return ib;
- }
-
- /**
- * Create Set IPv4 Source Instruction
- *
- * @param ib Map InstructionBuilder without any instructions
- * @param prefixsrc String containing an IPv4 prefix
- * @return ib Map InstructionBuilder with instructions
- */
- public static InstructionBuilder createNwSrcInstructions(InstructionBuilder ib, Ipv4Prefix prefixsrc) {
-
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab = new ActionBuilder();
-
- SetNwSrcActionBuilder setNwsrcActionBuilder = new SetNwSrcActionBuilder();
- Ipv4Builder ipsrc = new Ipv4Builder();
- ipsrc.setIpv4Address(prefixsrc);
- setNwsrcActionBuilder.setAddress(ipsrc.build());
- ab.setAction(new SetNwSrcActionCaseBuilder().setSetNwSrcAction(setNwsrcActionBuilder.build()).build());
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
- actionList.add(ab.build());
-
- // Create an Apply Action
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
-
- // Wrap our Apply Action in an Instruction
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
-
- return ib;
- }
-
- /**
- * Create Set IPv4 Destination Instruction
- *
- * @param ib Map InstructionBuilder without any instructions
- * @param prefixdst String containing an IPv4 prefix
- * @param extraAction (optional) Additional action to be performed in actionList
- * @return ib Map InstructionBuilder with instructions
- */
- public static InstructionBuilder createNwDstInstructions(InstructionBuilder ib, Ipv4Prefix prefixdst,
- ActionBuilder extraAction) {
-
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab = new ActionBuilder();
-
- SetNwDstActionBuilder setNwDstActionBuilder = new SetNwDstActionBuilder();
- Ipv4Builder ipdst = new Ipv4Builder();
- ipdst.setIpv4Address(prefixdst);
- setNwDstActionBuilder.setAddress(ipdst.build());
- ab.setAction(new SetNwDstActionCaseBuilder().setSetNwDstAction(setNwDstActionBuilder.build()).build());
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
- actionList.add(ab.build());
-
- if (extraAction != null) {
- extraAction.setOrder(1);
- extraAction.setKey(new ActionKey(1));
- actionList.add(extraAction.build());
- }
-
- // Create an Apply Action
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
-
- // Wrap our Apply Action in an Instruction
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
-
- return ib;
- }
-
- /**
- * Create Drop Instruction
- *
- * @param ib Map InstructionBuilder without any instructions
- * @return ib Map InstructionBuilder with instructions
- */
- public static InstructionBuilder createDropInstructions(InstructionBuilder ib) {
-
- DropActionBuilder dab = new DropActionBuilder();
- DropAction dropAction = dab.build();
- ActionBuilder ab = new ActionBuilder();
- ab.setAction(new DropActionCaseBuilder().setDropAction(dropAction).build());
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
-
- // Add our drop action to a list
- List<Action> actionList = new ArrayList<>();
- actionList.add(ab.build());
-
- // Create an Apply Action
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
-
- // Wrap our Apply Action in an Instruction
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
-
- return ib;
- }
-
- /**
- * Create GOTO Table Instruction Builder
- *
- * @param ib Map InstructionBuilder without any instructions
- * @param tableId short representing a flow table ID short representing a flow table ID
- * @return ib Map InstructionBuilder with instructions
- */
- public static InstructionBuilder createGotoTableInstructions(InstructionBuilder ib, short tableId) {
-
- GoToTableBuilder gttb = new GoToTableBuilder();
- gttb.setTableId(tableId);
-
- // Wrap our Apply Action in an InstructionBuilder
- ib.setInstruction(new GoToTableCaseBuilder().setGoToTable(gttb.build()).build());
-
- return ib;
- }
-
- /**
- * Create Set Tunnel ID Instruction Builder
- *
- * @param ib Map InstructionBuilder without any instructions
- * @param tunnelId BigInteger representing a tunnel ID
- * @return ib Map InstructionBuilder with instructions
- */
- public static InstructionBuilder createSetTunnelIdInstructions(InstructionBuilder ib, BigInteger tunnelId) {
-
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab = new ActionBuilder();
- SetFieldBuilder setFieldBuilder = new SetFieldBuilder();
-
- // Build the Set Tunnel Field Action
- TunnelBuilder tunnel = new TunnelBuilder();
- tunnel.setTunnelId(tunnelId);
- setFieldBuilder.setTunnel(tunnel.build());
- ab.setAction(new SetFieldCaseBuilder().setSetField(setFieldBuilder.build()).build());
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
- actionList.add(ab.build());
-
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
-
- // Wrap the Apply Action in an InstructionBuilder and return
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
-
- return ib;
- }
-
- /**
- * Create Set Source TCP Port Instruction
- *
- * @param ib Map InstructionBuilder without any instructions
- * @param tcpport Integer representing a source TCP port
- * @return ib Map InstructionBuilder with instructions
- */
- public static InstructionBuilder createSetSrcTCPPort(InstructionBuilder ib, PortNumber tcpport) {
-
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab = new ActionBuilder();
- SetFieldBuilder setFieldBuilder = new SetFieldBuilder();
-
- // Build the Destination TCP Port
- PortNumber tcpsrcport = new PortNumber(tcpport);
- TcpMatchBuilder tcpmatch = new TcpMatchBuilder();
- tcpmatch.setTcpSourcePort(tcpsrcport);
-
- setFieldBuilder.setLayer4Match(tcpmatch.build());
- ab.setAction(new SetFieldCaseBuilder().setSetField(setFieldBuilder.build()).build());
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
- actionList.add(ab.build());
-
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
-
- return ib;
- }
-
- /**
- * Create Set Destination TCP Port Instruction
- *
- * @param ib Map InstructionBuilder without any instructions
- * @param tcpport Integer representing a source TCP port
- * @return ib Map InstructionBuilder with instructions
- */
- public static InstructionBuilder createSetDstTCPPort(InstructionBuilder ib, PortNumber tcpport) {
-
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab = new ActionBuilder();
- SetFieldBuilder setFieldBuilder = new SetFieldBuilder();
-
- // Build the Destination TCP Port
- PortNumber tcpdstport = new PortNumber(tcpport);
- TcpMatchBuilder tcpmatch = new TcpMatchBuilder();
- tcpmatch.setTcpDestinationPort(tcpdstport);
-
- setFieldBuilder.setLayer4Match(tcpmatch.build());
- ab.setAction(new SetFieldCaseBuilder().setSetField(setFieldBuilder.build()).build());
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
- actionList.add(ab.build());
-
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
-
- return ib;
- }
-
- /**
- * Create Set Source UDP Port Instruction
- *
- * @param ib Map InstructionBuilder without any instructions
- * @param udpport Integer representing a source UDP port
- * @return ib Map InstructionBuilder with instructions
- */
- public static InstructionBuilder createSetSrcUDPPort(InstructionBuilder ib, PortNumber udpport) {
-
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab = new ActionBuilder();
- SetFieldBuilder setFieldBuilder = new SetFieldBuilder();
-
- // Build the Destination TCP Port
- PortNumber udpsrcport = new PortNumber(udpport);
- UdpMatchBuilder udpmatch = new UdpMatchBuilder();
- udpmatch.setUdpSourcePort(udpsrcport);
-
- setFieldBuilder.setLayer4Match(udpmatch.build());
- ab.setAction(new SetFieldCaseBuilder().setSetField(setFieldBuilder.build()).build());
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
- actionList.add(ab.build());
-
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
-
- return ib;
- }
-
- /**
- * Create Set Destination UDP Port Instruction
- *
- * @param ib Map InstructionBuilder without any instructions
- * @param udpport Integer representing a destination UDP port
- * @return ib Map InstructionBuilder with instructions
- */
- public static InstructionBuilder createSetDstUDPPort(InstructionBuilder ib, PortNumber udpport) {
-
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab = new ActionBuilder();
- SetFieldBuilder setFieldBuilder = new SetFieldBuilder();
-
- // Build the Destination TCP Port
- PortNumber udpdstport = new PortNumber(udpport);
- UdpMatchBuilder udpmatch = new UdpMatchBuilder();
- udpmatch.setUdpDestinationPort(udpdstport);
-
- setFieldBuilder.setLayer4Match(udpmatch.build());
- ab.setAction(new SetFieldCaseBuilder().setSetField(setFieldBuilder.build()).build());
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
- actionList.add(ab.build());
-
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
-
- return ib;
- }
-
- /**
- * Create Set ICMP Code Instruction
- *
- * @param ib Map InstructionBuilder without any instructions
- * @param code short repesenting an ICMP code
- * @return ib Map InstructionBuilder with instructions
- */
-
- public static InstructionBuilder createSetIcmpCodeInstruction(InstructionBuilder ib, short code) {
-
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab = new ActionBuilder();
- SetFieldBuilder setFieldBuilder = new SetFieldBuilder();
- Icmpv4MatchBuilder icmpv4match = new Icmpv4MatchBuilder();
-
- // Build the ICMPv4 Code Match
- icmpv4match.setIcmpv4Code(code);
- setFieldBuilder.setIcmpv4Match(icmpv4match.build());
-
- ab.setAction(new SetFieldCaseBuilder().setSetField(setFieldBuilder.build()).build());
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
- actionList.add(ab.build());
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
-
- // Wrap our Apply Action in an Instruction
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
-
- return ib;
- }
-
- /**
- * Create Set ICMP Code Instruction
- *
- * @param ib Map InstructionBuilder without any instructions
- * @return ib Map InstructionBuilder with instructions
- */
- public static InstructionBuilder createSetIcmpTypeInstruction(InstructionBuilder ib, short type) {
-
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab = new ActionBuilder();
- SetFieldBuilder setFieldBuilder = new SetFieldBuilder();
- Icmpv4MatchBuilder icmpv4match = new Icmpv4MatchBuilder();
-
- // Build the ICMPv4 Code Match
- icmpv4match.setIcmpv4Code(type);
- setFieldBuilder.setIcmpv4Match(icmpv4match.build());
-
- ab.setAction(new SetFieldCaseBuilder().setSetField(setFieldBuilder.build()).build());
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
- actionList.add(ab.build());
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
-
- // Wrap our Apply Action in an Instruction
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
-
- return ib;
- }
-
- /**
- * Create Decrement TTL Instruction
- *
- * @param ib Map InstructionBuilder without any instructions
- * @return ib Map InstructionBuilder with instructions
- */
- public static InstructionBuilder createDecNwTtlInstructions(InstructionBuilder ib) {
- DecNwTtlBuilder decNwTtlBuilder = new DecNwTtlBuilder();
- DecNwTtl decNwTtl = decNwTtlBuilder.build();
- ActionBuilder ab = new ActionBuilder();
- ab.setAction(new DecNwTtlCaseBuilder().setDecNwTtl(decNwTtl).build());
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
-
- // Add our drop action to a list
- List<Action> actionList = new ArrayList<>();
- actionList.add(ab.build());
-
- // Create an Apply Action
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
-
- // Wrap our Apply Action in an Instruction
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
-
- return ib;
- }
-
- /**
- * Set ARP_SHA Instructions
- * @param ib Map InstructionBuilder
- * @param macsrc the macsrc
- * @return instructionbuilder with new instructions
- */
- public static InstructionBuilder createSrcArpMacInstructions(InstructionBuilder ib, MacAddress macsrc) {
-
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab = new ActionBuilder();
-
- SetFieldBuilder setFieldBuilder = new SetFieldBuilder();
- ArpMatchBuilder arpmatch = new ArpMatchBuilder();
- ArpSourceHardwareAddressBuilder arpsrc = new ArpSourceHardwareAddressBuilder();
- arpsrc.setAddress(macsrc);
- arpmatch.setArpSourceHardwareAddress(arpsrc.build());
- setFieldBuilder.setLayer3Match(arpmatch.build());
- ab.setAction(new SetFieldCaseBuilder().setSetField(setFieldBuilder.build()).build());
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
- actionList.add(ab.build());
-
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
- // Wrap our Apply Action in an Instruction
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
-
- return ib;
- }
-
- /**
- * Set ARP_THA Instructions
- * @param ib Map InstructionBuilder
- * @param macdst the macdst
- * @return instructionbuilder with new attributes
- */
- public static InstructionBuilder createDstArpMacInstructions(InstructionBuilder ib, MacAddress macdst) {
-
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab = new ActionBuilder();
- SetFieldBuilder setFieldBuilder = new SetFieldBuilder();
-
- ArpMatchBuilder arpmatch = new ArpMatchBuilder();
- ArpTargetHardwareAddressBuilder arpdst = new ArpTargetHardwareAddressBuilder();
- arpdst.setAddress(macdst);
- setFieldBuilder.setLayer3Match(arpmatch.build());
- ab.setAction(new SetFieldCaseBuilder().setSetField(setFieldBuilder.build()).build());
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
- actionList.add(ab.build());
-
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
- // Wrap our Apply Action in an Instruction
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
-
- return ib;
- }
-
- /**
- * Set ARP_TPA Instructions
- * @param ib Map InstructionBuilder
- * @param dstiparp the dstiparp
- * @return instructionbuilder with new attributes
- */
- public static InstructionBuilder createDstArpIpInstructions(InstructionBuilder ib, Ipv4Prefix dstiparp) {
-
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab = new ActionBuilder();
- SetFieldBuilder setFieldBuilder = new SetFieldBuilder();
-
- ArpMatchBuilder arpmatch = new ArpMatchBuilder();
- arpmatch.setArpTargetTransportAddress(dstiparp);
- setFieldBuilder.setLayer3Match(arpmatch.build());
- ab.setAction(new SetFieldCaseBuilder().setSetField(setFieldBuilder.build()).build());
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
- actionList.add(ab.build());
-
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
- // Wrap our Apply Action in an Instruction
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
-
- return ib;
- }
-
- /**
- * Set ARP_SPA Instructions
- * @param ib Map InstructionBuilder
- * @param srciparp the srciparp
- * @return instructionbuilder with new attributes
- */
- public static InstructionBuilder createSrcArpIpInstructions(InstructionBuilder ib, Ipv4Prefix srciparp) {
-
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab = new ActionBuilder();
- SetFieldBuilder setFieldBuilder = new SetFieldBuilder();
-
- ArpMatchBuilder arpmatch = new ArpMatchBuilder();
- arpmatch.setArpSourceTransportAddress(srciparp);
- setFieldBuilder.setLayer3Match(arpmatch.build());
- ab.setAction(new SetFieldCaseBuilder().setSetField(setFieldBuilder.build()).build());
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
- actionList.add(ab.build());
-
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
- // Wrap our Apply Action in an Instruction
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
-
- return ib;
- }
-
- /**
- * Set the Tunnel EndpointIPv4 Source Address
- * @param ib Map InstructionBuilder
- * @param srcIp Ipv4Prefix source IP for the tunnel endpoint (TEP)
- * @return instructionbuilder with new attributes
- */
- public static InstructionBuilder createTunnelIpv4SrcInstructions(InstructionBuilder ib, Ipv4Prefix srcIp) {
-
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab = new ActionBuilder();
-
- // Build the tunnel endpoint source IPv4 address
- SetFieldBuilder setFieldBuilder = new SetFieldBuilder();
-
- // Add the new IPv4 object as the tunnel destination
- TunnelIpv4MatchBuilder tunnelIpv4MatchBuilder = new TunnelIpv4MatchBuilder();
- tunnelIpv4MatchBuilder.setTunnelIpv4Source(srcIp);
- setFieldBuilder.setLayer3Match(tunnelIpv4MatchBuilder.build());
-
- // Add the IPv4 tunnel src to the set_field value
- ab.setAction(new SetFieldCaseBuilder().setSetField(setFieldBuilder.build()).build());
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
- actionList.add(ab.build());
-
- // Resulting action is a per/flow src TEP (set_field:172.16.100.100->tun_src)
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
- // Wrap our Apply Action in an Instruction
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
-
- return ib;
- }
-
- /**
- * Set the Tunnel EndpointIPv4 Destination Address
- * @param ib Map InstructionBuilder
- * @param dstIp Ipv4Prefix destination IP for the tunnel endpoint (TEP)
- * @return instructionbuilder with new attributes
- */
- public static InstructionBuilder createTunnelIpv4DstInstructions(InstructionBuilder ib, Ipv4Prefix dstIp) {
-
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab = new ActionBuilder();
-
- // Build the tunnel endpoint dst IPv4 address
- SetFieldBuilder setFieldBuilder = new SetFieldBuilder();
-
- // Add the new IPv4 object as the tunnel destination
- TunnelIpv4MatchBuilder tunnelIpv4MatchBuilder = new TunnelIpv4MatchBuilder();
- tunnelIpv4MatchBuilder.setTunnelIpv4Destination(dstIp);
- setFieldBuilder.setLayer3Match(tunnelIpv4MatchBuilder.build());
-
- // Add the IPv4 tunnel src to the set_field value
- ab.setAction(new SetFieldCaseBuilder().setSetField(setFieldBuilder.build()).build());
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
- actionList.add(ab.build());
-
- // Resulting action is a per/flow src TEP (set_field:172.16.100.100->tun_src)
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
- // Wrap our Apply Action in an Instruction
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
-
- return ib;
- }
-
- /**
- * Set IPv4 Source Address Instructions
- * @param ib Map InstructionBuilder
- * @param metaData BigInteger representing the OpenFlow metadata
- * @param metaDataMask BigInteger representing the OpenFlow metadata mask
- * @return instructionbuilder with new attributes
- */
- public static InstructionBuilder createMetadataInstructions(InstructionBuilder ib, BigInteger metaData, BigInteger metaDataMask) {
-
- WriteMetadataBuilder aab = new WriteMetadataBuilder();
- aab.setMetadata(metaData);
- aab.setMetadataMask(metaDataMask);
- ib.setInstruction(new WriteMetadataCaseBuilder().setWriteMetadata(aab.build()).build());
-
- /**
- *
- * TODO Determine why the following fails serialization
- * with a null value. Per the spec it is optional.
- * The metadata match, the Flowmod works w/o an accompanying mask.
- *
- * if (metaDataMask != null) {
- * aab.setMetadataMask(metaDataMask);
- * }
- *
- */
-
- return ib;
- }
-
- public static InstructionBuilder createDlSrcInstructions(InstructionBuilder ib, MacAddress macAddress) {
-
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab = new ActionBuilder();
-
- SetDlSrcActionBuilder dlSrcActionBuilder= new SetDlSrcActionBuilder();
-
- dlSrcActionBuilder.setAddress(macAddress);
-
- ab.setAction(new SetDlSrcActionCaseBuilder().setSetDlSrcAction(dlSrcActionBuilder.build()).build());
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
- actionList.add(ab.build());
-
-
- // Create an Apply Action
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
-
- // Wrap our Apply Action in an Instruction
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
-
- return ib;
- }
-
- public static InstructionBuilder createDlDstInstructions(InstructionBuilder ib, MacAddress macAddress) {
-
- List<Action> actionList = new ArrayList<>();
- ActionBuilder ab = new ActionBuilder();
-
- SetDlDstActionBuilder dlDstActionBuilder= new SetDlDstActionBuilder();
-
- dlDstActionBuilder.setAddress(macAddress);
-
- ab.setAction(new SetDlDstActionCaseBuilder().setSetDlDstAction(dlDstActionBuilder.build()).build());
- ab.setOrder(0);
- ab.setKey(new ActionKey(0));
- actionList.add(ab.build());
-
- // Create an Apply Action
- ApplyActionsBuilder aab = new ApplyActionsBuilder();
- aab.setAction(actionList);
-
- // Wrap our Apply Action in an Instruction
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
-
- return ib;
- }
-
- public static List<Action>
- actionList(org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action... actions) {
-
- List<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action> alist
- = new ArrayList<>();
- int count = 0;
- for (org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action action : actions) {
- alist.add(new ActionBuilder()
- .setOrder(count)
- .setKey(new ActionKey(count))
- .setAction(action)
- .build());
- count++;
- }
- return alist;
- }
-
- public static org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.Instruction
- applyActionIns(org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action... actions) {
-
- return new ApplyActionsCaseBuilder()
- .setApplyActions(new ApplyActionsBuilder()
- .setAction(actionList(actions))
- .build())
- .build();
- }
-
- public static Instructions getInstructions(org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.Instruction... instructions) {
- List<Instruction> ins
- = new ArrayList<>();
- int order = 0;
- for (org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.Instruction i : instructions) {
- ins.add(new InstructionBuilder()
- .setOrder(order)
- .setKey(new InstructionKey(order))
- .setInstruction(i)
- .build());
- order++;
- }
- return new InstructionsBuilder().setInstruction(ins).build();
- }
-
- public static Instructions dropInstructions() {
- 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
- * @param instructions org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instructions
- * @return instruction list that additional
- */
- public static List<Instruction> getInstructionList(
- org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.Instruction... instructions) {
- List<Instruction> ins
- = new ArrayList<>();
- int order = 0;
- for (org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.Instruction i : instructions) {
- ins.add(new InstructionBuilder()
- .setOrder(order++)
- .setInstruction(i)
- .build());
- }
- return ins;
- }
-
- /**
- * Create InstructionBuilder with apply action.
- *
- * @param aab the apply action Builder.
- * @param order the position of the instruction in the instruction list.
- * @param drop indicates whether it is a drop instruction.
- * @return the instruction builder.
- */
- public static InstructionBuilder createInstructionBuilder(ApplyActionsBuilder aab, int order, boolean drop) {
- InstructionBuilder ib = new InstructionBuilder();
- ib.setOrder(order);
- ib.setKey(new InstructionKey(order));
- ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
- if (drop) {
- InstructionUtils.createDropInstructions(ib);
- }
- return ib;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 - 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.utils.mdsal.openflow;
-
-import com.google.common.collect.ImmutableList;
-import java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Dscp;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Prefix;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv6Prefix;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
-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.l2.types.rev130827.EtherType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.VlanId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.arp.match.fields.ArpSourceHardwareAddressBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.arp.match.fields.ArpTargetHardwareAddressBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ethernet.match.fields.EthernetDestinationBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ethernet.match.fields.EthernetSourceBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ethernet.match.fields.EthernetTypeBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.EthernetMatch;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.EthernetMatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.Icmpv4MatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.Icmpv6MatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.IpMatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.MetadataBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.TcpFlagsMatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.TunnelBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.VlanMatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.ArpMatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.Ipv4MatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.Ipv6MatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._4.match.SctpMatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._4.match.TcpMatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._4.match.UdpMatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.vlan.match.fields.VlanIdBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg0;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg1;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg2;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg3;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg4;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg5;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg6;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.ExtensionKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.GeneralAugMatchNodesNodeTableFlow;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.GeneralAugMatchNodesNodeTableFlowBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.general.extension.grouping.ExtensionBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.general.extension.list.grouping.ExtensionList;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.general.extension.list.grouping.ExtensionListBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxAugMatchNodesNodeTableFlow;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxAugMatchNodesNodeTableFlowBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmNxCtStateKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmNxCtZoneKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmNxNsiKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmNxNspKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmNxReg0Key;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmNxReg1Key;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmNxReg2Key;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmNxReg3Key;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmNxReg4Key;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmNxReg5Key;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmNxReg6Key;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmNxReg7Key;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmNxTunIdKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmOfTcpDstKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmOfTcpSrcKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmOfUdpDstKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmOfUdpSrcKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.nxm.nx.ct.state.grouping.NxmNxCtStateBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.nxm.nx.ct.zone.grouping.NxmNxCtZoneBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.nxm.nx.reg.grouping.NxmNxRegBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.nxm.nx.tun.id.grouping.NxmNxTunIdBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.nxm.nx.nsp.grouping.NxmNxNspBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.nxm.nx.nsi.grouping.NxmNxNsiBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.nxm.of.tcp.src.grouping.NxmOfTcpSrcBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.nxm.of.tcp.dst.grouping.NxmOfTcpDstBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.nxm.of.udp.dst.grouping.NxmOfUdpDstBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.nxm.of.udp.src.grouping.NxmOfUdpSrcBuilder;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class MatchUtils {
- private static final Logger LOG = LoggerFactory.getLogger(MatchUtils.class);
- public static final short ICMP_SHORT = 1;
- public static final short TCP_SHORT = 6;
- public static final short UDP_SHORT = 17;
- public static final short SCTP_SHORT = 132;
- public static final String TCP = "tcp";
- public static final String UDP = "udp";
- public static final String ICMP_PROTOCOL = "1";
- public static final String TCP_PROTOCOL = "6";
- public static final String UDP_PROTOCOL = "17";
- public static final String ANY_PROTOCOL = "0";
- private static final int TCP_SYN = 0x0002;
- public static final String ICMP = "icmp";
- public static final String ICMPV6 = "icmpv6";
- public static final short ALL_ICMP = -1;
- public static final long ETHERTYPE_IPV4 = 0x0800;
- public static final long ETHERTYPE_IPV6 = 0x86dd;
- public static final long ETHERTYPE_ARP = 0x0806L;
- public static final int UNTRACKED_CT_STATE = 0x00;
- public static final int UNTRACKED_CT_STATE_MASK = 0x20;
- public static final int TRACKED_EST_CT_STATE = 0x22;
- public static final int TRACKED_REL_CT_STATE = 0x24;
- public static final int TRACKED_NEW_CT_STATE = 0x21;
- public static final int TRACKED_INV_CT_STATE = 0x30;
- public static final int TRACKED_INV_CT_STATE_MASK = 0x30;
- public static final int TRACKED_CT_STATE_MASK = 0x37;
- public static final int TRACKED_NEW_CT_STATE_MASK = 0x21;
-
- /**
- * Create Ingress Port Match dpidLong, inPort
- *
- * @param matchBuilder Map matchBuilder MatchBuilder Object without a match
- * @param dpidLong Long the datapath ID of a switch/node
- * @param inPort Long ingress port on a switch
- * @return matchBuilder Map MatchBuilder Object with a match
- */
- public static MatchBuilder createInPortMatch(MatchBuilder matchBuilder, Long dpidLong, Long inPort) {
-
- NodeConnectorId ncid = new NodeConnectorId("openflow:" + dpidLong + ":" + inPort);
- LOG.debug("createInPortMatch() Node Connector ID is - Type=openflow: DPID={} inPort={} ", dpidLong, inPort);
- matchBuilder.setInPort(NodeConnectorId.getDefaultInstance(ncid.getValue()));
- matchBuilder.setInPort(ncid);
-
- return matchBuilder;
- }
-
- public static MatchBuilder createInPortReservedMatch(MatchBuilder matchBuilder, Long dpidLong, String inPort) {
-
- NodeConnectorId ncid = new NodeConnectorId("openflow:" + dpidLong + ":" + inPort);
- LOG.debug("createInPortResrevedMatch() Node Connector ID is - Type=openflow: DPID={} inPort={} ",
- dpidLong, inPort);
- matchBuilder.setInPort(NodeConnectorId.getDefaultInstance(ncid.getValue()));
- matchBuilder.setInPort(ncid);
-
- return matchBuilder;
- }
-
- /**
- * Create EtherType Match
- *
- * @param matchBuilder Map matchBuilder MatchBuilder Object without a match
- * @param etherType Long EtherType
- * @return matchBuilder Map MatchBuilder Object with a match
- */
- public static MatchBuilder createEtherTypeMatch(MatchBuilder matchBuilder, EtherType etherType) {
-
- EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder();
- EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
- ethTypeBuilder.setType(new EtherType(etherType));
- ethernetMatch.setEthernetType(ethTypeBuilder.build());
- matchBuilder.setEthernetMatch(ethernetMatch.build());
-
- return matchBuilder;
- }
-
- public static MatchBuilder createEthSrcDstMatch(MatchBuilder matchBuilder, MacAddress srcMac, MacAddress dstMac) {
- EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder();
- if (srcMac != null) {
- EthernetSourceBuilder ethSourceBuilder = new EthernetSourceBuilder();
- ethSourceBuilder.setAddress(srcMac);
- ethernetMatch.setEthernetSource(ethSourceBuilder.build());
- }
- if (dstMac != null) {
- EthernetDestinationBuilder ethDestinationBuild = new EthernetDestinationBuilder();
- ethDestinationBuild.setAddress(dstMac);
- ethernetMatch.setEthernetDestination(ethDestinationBuild.build());
- }
- if (matchBuilder.getEthernetMatch() != null && matchBuilder.getEthernetMatch().getEthernetType() != null) {
- ethernetMatch.setEthernetType(matchBuilder.getEthernetMatch().getEthernetType());
- }
-
- matchBuilder.setEthernetMatch(ethernetMatch.build());
-
- return matchBuilder;
- }
-
- /**
- * Create Ethernet Source Match
- *
- * @param matchBuilder MatchBuilder Object without a match yet
- * @param sMacAddr String representing a source MAC
- * @return matchBuilder Map MatchBuilder Object with a match
- */
- public static MatchBuilder createEthSrcMatch(MatchBuilder matchBuilder, MacAddress sMacAddr) {
-
- EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder();
- EthernetSourceBuilder ethSourceBuilder = new EthernetSourceBuilder();
- ethSourceBuilder.setAddress(sMacAddr);
- ethernetMatch.setEthernetSource(ethSourceBuilder.build());
- matchBuilder.setEthernetMatch(ethernetMatch.build());
-
- return matchBuilder;
- }
-
- /**
- * Create Ethernet Destination Match
- *
- * @param matchBuilder MatchBuilder Object without a match yet
- * @param vlanId Integer representing a VLAN ID Integer representing a VLAN ID
- * @return matchBuilder Map MatchBuilder Object with a match
- */
- public static MatchBuilder createVlanIdMatch(MatchBuilder matchBuilder, VlanId vlanId, boolean present) {
- VlanMatchBuilder vlanMatchBuilder = new VlanMatchBuilder();
- VlanIdBuilder vlanIdBuilder = new VlanIdBuilder();
- vlanIdBuilder.setVlanId(new VlanId(vlanId));
- vlanIdBuilder.setVlanIdPresent(present);
- vlanMatchBuilder.setVlanId(vlanIdBuilder.build());
- matchBuilder.setVlanMatch(vlanMatchBuilder.build());
-
- return matchBuilder;
- }
-
- /**
- * Create Ethernet Destination Match
- *
- * @param matchBuilder MatchBuilder Object without a match yet
- * @param dMacAddr String representing a destination MAC
- * @return matchBuilder Map MatchBuilder Object with a match
- */
- public static MatchBuilder createDestEthMatch(MatchBuilder matchBuilder, MacAddress dMacAddr, MacAddress mask) {
-
- EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder();
- EthernetDestinationBuilder ethDestinationBuilder = new EthernetDestinationBuilder();
- ethDestinationBuilder.setAddress(dMacAddr);
- if (mask != null) {
- ethDestinationBuilder.setMask(mask);
- }
- ethernetMatch.setEthernetDestination(ethDestinationBuilder.build());
- matchBuilder.setEthernetMatch(ethernetMatch.build());
-
- return matchBuilder;
- }
-
- /**
- * Create Ethernet Source and Destination Match
- *
- * @param matchBuilder MatchBuilder Object without a match yet
- * @param sMacAddr String representing a source MAC
- * @param dMacAddr String representing a destination MAC
- * @param mask the mask of the Destination Mac Address
- * @return matchBuilder Map MatchBuilder Object with a match
- */
- public static MatchBuilder createEthSrcDestMatch(MatchBuilder matchBuilder, MacAddress sMacAddr, MacAddress dMacAddr, MacAddress mask) {
- EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder();
- EthernetSourceBuilder ethSourceBuilder = new EthernetSourceBuilder();
- ethSourceBuilder.setAddress(sMacAddr);
- ethernetMatch.setEthernetSource(ethSourceBuilder.build());
-
- EthernetDestinationBuilder ethDestinationBuilder = new EthernetDestinationBuilder();
- ethDestinationBuilder.setAddress(dMacAddr);
- if (mask != null) {
- ethDestinationBuilder.setMask(mask);
- }
- ethernetMatch.setEthernetDestination(ethDestinationBuilder.build());
- matchBuilder.setEthernetMatch(ethernetMatch.build());
-
- return matchBuilder;
- }
-
- /**
- * Tunnel ID Match Builder
- *
- * @param matchBuilder MatchBuilder Object without a match yet
- * @param tunnelId BigInteger representing a tunnel ID
- * @return matchBuilder Map MatchBuilder Object with a match
- */
- public static MatchBuilder createTunnelIDMatch(MatchBuilder matchBuilder, BigInteger tunnelId) {
-
- TunnelBuilder tunnelBuilder = new TunnelBuilder();
- tunnelBuilder.setTunnelId(tunnelId);
- matchBuilder.setTunnel(tunnelBuilder.build());
-
- return matchBuilder;
- }
-
- /**
- * Match ICMP code and type
- *
- * @param matchBuilder MatchBuilder Object
- * @param type short representing an ICMP type
- * @param code short representing an ICMP code
- * @return matchBuilder Map MatchBuilder Object with a match
- */
- public static MatchBuilder createICMPv4Match(MatchBuilder matchBuilder, short type, short code) {
-
- // Build the IPv4 Match requied per OVS Syntax
- IpMatchBuilder ipmatch = new IpMatchBuilder();
- ipmatch.setIpProtocol((short) 1);
- matchBuilder.setIpMatch(ipmatch.build());
-
- // Build the ICMPv4 Match
- Icmpv4MatchBuilder icmpv4match = new Icmpv4MatchBuilder();
- if (type != ALL_ICMP) {
- icmpv4match.setIcmpv4Type(type);
- }
- if (code != ALL_ICMP) {
- icmpv4match.setIcmpv4Code(code);
- }
- matchBuilder.setIcmpv4Match(icmpv4match.build());
-
- return matchBuilder;
- }
-
- /**
- * Match ICMPv6 code and type
- *
- * @param matchBuilder MatchBuilder Object
- * @param type short representing an ICMP type
- * @param code short representing an ICMP code
- * @return matchBuilder Map MatchBuilder Object with a match
- */
- public static MatchBuilder createICMPv6Match(MatchBuilder matchBuilder, short type, short code) {
-
- // Build the IPv6 Match required per OVS Syntax
- IpMatchBuilder ipmatch = new IpMatchBuilder();
- ipmatch.setIpProtocol((short) 58);
- matchBuilder.setIpMatch(ipmatch.build());
-
- // Build the ICMPv6 Match
- Icmpv6MatchBuilder icmpv6match = new Icmpv6MatchBuilder();
- if (type != ALL_ICMP || code != ALL_ICMP) {
- icmpv6match.setIcmpv6Type(type);
- icmpv6match.setIcmpv6Code(code);
- }
- matchBuilder.setIcmpv6Match(icmpv6match.build());
-
- return matchBuilder;
- }
-
- /**
- * @param matchBuilder MatchBuilder Object without a match yet
- * @param dstip String containing an IPv4 prefix
- * @return matchBuilder Map Object with a match
- */
- public static MatchBuilder createDstL3IPv4Match(MatchBuilder matchBuilder, Ipv4Prefix dstip) {
-
- EthernetMatchBuilder eth = new EthernetMatchBuilder();
- EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
- ethTypeBuilder.setType(new EtherType(0x0800L));
- eth.setEthernetType(ethTypeBuilder.build());
- matchBuilder.setEthernetMatch(eth.build());
-
- Ipv4MatchBuilder ipv4match = new Ipv4MatchBuilder();
- ipv4match.setIpv4Destination(dstip);
-
- matchBuilder.setLayer3Match(ipv4match.build());
-
- return matchBuilder;
-
- }
-
- /**
- * @param matchBuilder MatchBuilder Object without a match yet
- * @param dstip String containing an IPv4 prefix
- * @return matchBuilder Map Object with a match
- */
- public static MatchBuilder createArpDstIpv4Match(MatchBuilder matchBuilder, Ipv4Prefix dstip) {
- ArpMatchBuilder arpDstMatch = new ArpMatchBuilder();
- arpDstMatch.setArpTargetTransportAddress(dstip)
- .setArpOp(FlowUtils.ARP_OP_REQUEST);
- matchBuilder.setLayer3Match(arpDstMatch.build());
-
- return matchBuilder;
- }
-
- /**
- * Builds the arp match with src and destintion mac address.
- * @param matchBuilder the match builder
- * @param srcMac the src mac address , will not be added to match if null.
- * @param dstMac the destination mac address, will not be added to match if null.
- * @return the match builder with the matches
- */
- public static MatchBuilder addArpMacMatch(MatchBuilder matchBuilder, String srcMac, String dstMac) {
- ArpMatchBuilder arpMatch = new ArpMatchBuilder();
- if (null != srcMac) {
- ArpSourceHardwareAddressBuilder arpSrc = new ArpSourceHardwareAddressBuilder();
- arpSrc.setAddress(new MacAddress(srcMac));
- arpMatch.setArpSourceHardwareAddress(arpSrc.build());
- }
- if (null != dstMac) {
- ArpTargetHardwareAddressBuilder arpDst = new ArpTargetHardwareAddressBuilder();
- arpDst.setAddress(new MacAddress(dstMac));
- arpMatch.setArpTargetHardwareAddress(arpDst.build());
- }
- matchBuilder.setLayer3Match(arpMatch.build());
- return matchBuilder;
- }
-
- /**
- * @param matchBuilder MatchBuilder Object without a match yet
- * @param srcip String containing an IPv4 prefix
- * @return matchBuilder Map Object with a match
- */
- public static MatchBuilder createSrcL3IPv4Match(MatchBuilder matchBuilder, Ipv4Prefix srcip) {
-
- EthernetMatchBuilder eth = new EthernetMatchBuilder();
- EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
- ethTypeBuilder.setType(new EtherType(0x0800L));
- eth.setEthernetType(ethTypeBuilder.build());
- matchBuilder.setEthernetMatch(eth.build());
-
- Ipv4MatchBuilder ipv4match = new Ipv4MatchBuilder();
- ipv4match.setIpv4Source(srcip);
- matchBuilder.setLayer3Match(ipv4match.build());
-
- return matchBuilder;
-
- }
-
- /**
- * Create Source TCP Port Match
- *
- * @param matchBuilder MatchBuilder Object without a match yet
- * @param tcpport Integer representing a source TCP port
- * @return matchBuilder Map MatchBuilder Object with a match
- */
- public static MatchBuilder createSetSrcTcpMatch(MatchBuilder matchBuilder, PortNumber tcpport) {
-
- EthernetMatchBuilder ethType = new EthernetMatchBuilder();
- EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
- ethTypeBuilder.setType(new EtherType(0x0800L));
- ethType.setEthernetType(ethTypeBuilder.build());
- matchBuilder.setEthernetMatch(ethType.build());
-
- IpMatchBuilder ipmatch = new IpMatchBuilder();
- ipmatch.setIpProtocol((short) 6);
- matchBuilder.setIpMatch(ipmatch.build());
-
- TcpMatchBuilder tcpmatch = new TcpMatchBuilder();
- tcpmatch.setTcpSourcePort(tcpport);
- matchBuilder.setLayer4Match(tcpmatch.build());
-
- return matchBuilder;
-
- }
-
- /**
- * Create Destination TCP Port Match
- *
- * @param matchBuilder MatchBuilder Object without a match yet
- * @param tcpDstPort Integer representing a destination TCP port
- * @return matchBuilder Map MatchBuilder Object with a match
- */
- public static MatchBuilder createSetDstTcpMatch(MatchBuilder matchBuilder, PortNumber tcpDstPort) {
-
- EthernetMatchBuilder ethType = new EthernetMatchBuilder();
- EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
- ethTypeBuilder.setType(new EtherType(0x0800L));
- ethType.setEthernetType(ethTypeBuilder.build());
- matchBuilder.setEthernetMatch(ethType.build());
-
- IpMatchBuilder ipmatch = new IpMatchBuilder();
- ipmatch.setIpProtocol((short) 6);
- matchBuilder.setIpMatch(ipmatch.build());
-
- TcpMatchBuilder tcpmatch = new TcpMatchBuilder();
- tcpmatch.setTcpDestinationPort(tcpDstPort);
- matchBuilder.setLayer4Match(tcpmatch.build());
-
- return matchBuilder;
- }
-
- /**
- * Test match for TCP_Flags
- *
- * @param matchBuilder MatchBuilder Object without a match yet
- * @param tcpPort PortNumber representing a destination TCP port
- * @param tcpFlags int representing a tcp_flag
- * @return match containing TCP_Flag (), IP Protocol (TCP), TCP_Flag (SYN)
- * <p>
- * Defined TCP Flag values in OVS v2.1+
- * TCP_FIN 0x001 / TCP_SYN 0x002 / TCP_RST 0x004
- * TCP_PSH 0x008 / TCP_ACK 0x010 / TCP_URG 0x020
- * TCP_ECE 0x040 / TCP_CWR 0x080 / TCP_NS 0x100
- */
- public static MatchBuilder createTcpFlagsMatch(MatchBuilder matchBuilder, PortNumber tcpPort, int tcpFlags) {
-
- // Ethertype match
- EthernetMatchBuilder ethernetType = new EthernetMatchBuilder();
- EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
- ethTypeBuilder.setType(new EtherType(0x0800L));
- ethernetType.setEthernetType(ethTypeBuilder.build());
- matchBuilder.setEthernetMatch(ethernetType.build());
-
- // TCP Protocol Match
- IpMatchBuilder ipMatch = new IpMatchBuilder(); // ipv4 version
- ipMatch.setIpProtocol((short) 6);
- matchBuilder.setIpMatch(ipMatch.build());
-
- // TCP Port Match
- PortNumber dstPort = new PortNumber(tcpPort);
- TcpMatchBuilder tcpMatch = new TcpMatchBuilder();
- tcpMatch.setTcpDestinationPort(dstPort);
- matchBuilder.setLayer4Match(tcpMatch.build());
-
- TcpFlagsMatchBuilder tcpFlagsMatch = new TcpFlagsMatchBuilder();
- tcpFlagsMatch.setTcpFlags(tcpFlags);
- matchBuilder.setTcpFlagsMatch(tcpFlagsMatch.build());
- return matchBuilder;
- }
-
- /**
- * @return MatchBuilder containing the metadata match values
- */
- public static MatchBuilder createMetadataMatch(MatchBuilder matchBuilder, BigInteger metaData, BigInteger metaDataMask) {
-
- // metadata matchbuilder
- MetadataBuilder metadata = new MetadataBuilder();
- metadata.setMetadata(metaData);
- // Optional metadata mask
- if (metaDataMask != null) {
- metadata.setMetadataMask(metaDataMask);
- }
- matchBuilder.setMetadata(metadata.build());
-
- return matchBuilder;
- }
-
- /**
- * Create TCP Port Match
- *
- * @param matchBuilder MatchBuilder Object without a match yet
- * @param ipProtocol Integer representing the IP protocol
- * @return matchBuilder Map MatchBuilder Object with a match
- */
- public static MatchBuilder createIpProtocolMatch(MatchBuilder matchBuilder, short ipProtocol) {
-
- EthernetMatchBuilder ethType = new EthernetMatchBuilder();
- EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
- ethTypeBuilder.setType(new EtherType(0x0800L));
- ethType.setEthernetType(ethTypeBuilder.build());
- matchBuilder.setEthernetMatch(ethType.build());
-
- IpMatchBuilder ipMmatch = new IpMatchBuilder();
- if (ipProtocol == TCP_SHORT) {
- ipMmatch.setIpProtocol(TCP_SHORT);
- }
- else if (ipProtocol == UDP_SHORT) {
- ipMmatch.setIpProtocol(UDP_SHORT);
- }
- else if (ipProtocol == ICMP_SHORT) {
- ipMmatch.setIpProtocol(ICMP_SHORT);
- }
- matchBuilder.setIpMatch(ipMmatch.build());
- return matchBuilder;
- }
-
- /**
- * Create IP protocol match with Eth Match
- *
- * @param matchBuilder MatchBuilder Object without a match yet
- * @param ipProtocol Integer representing the IP protocol
- * @param srcMac The source macAddress
- * @param dstMac The destination mac address
- * @return matchBuilder Map MatchBuilder Object with a match
- */
- public static MatchBuilder createIpProtocolAndEthMatch(MatchBuilder matchBuilder, short ipProtocol, String srcMac, String dstMac) {
-
- EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
- ethTypeBuilder.setType(new EtherType(0x0800L));
- EthernetMatchBuilder ethMatchBuilder = new EthernetMatchBuilder();
- ethMatchBuilder.setEthernetType(ethTypeBuilder.build());
- if (null != srcMac) {
- ethMatchBuilder.setEthernetSource(new EthernetSourceBuilder()
- .setAddress(new MacAddress(srcMac)).build());
- }
- if (null != dstMac) {
- ethMatchBuilder.setEthernetDestination(new EthernetDestinationBuilder()
- .setAddress(new MacAddress(dstMac)).build());
- }
- matchBuilder.setEthernetMatch(ethMatchBuilder.build());
- IpMatchBuilder ipMmatch = new IpMatchBuilder();
- ipMmatch.setIpProtocol(ipProtocol);
- matchBuilder.setIpMatch(ipMmatch.build());
- return matchBuilder;
- }
-
- /**
- * Create TCP Port Match
- *
- * @param matchBuilder MatchBuilder Object without a match yet
- * @param ipProtocol Integer representing the IP protocol
- * @return matchBuilder Map MatchBuilder Object with a match
- */
- public static MatchBuilder createIpv6ProtocolMatch(MatchBuilder matchBuilder, short ipProtocol) {
-
- EthernetMatchBuilder ethType = new EthernetMatchBuilder();
- EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
- ethTypeBuilder.setType(new EtherType(0x86DDL));
- ethType.setEthernetType(ethTypeBuilder.build());
- matchBuilder.setEthernetMatch(ethType.build());
-
- IpMatchBuilder ipMmatch = new IpMatchBuilder();
- if (ipProtocol == TCP_SHORT) {
- ipMmatch.setIpProtocol(TCP_SHORT);
- }
- else if (ipProtocol == UDP_SHORT) {
- ipMmatch.setIpProtocol(UDP_SHORT);
- }
- else if (ipProtocol == ICMP_SHORT) {
- ipMmatch.setIpProtocol(ICMP_SHORT);
- }
- matchBuilder.setIpMatch(ipMmatch.build());
- return matchBuilder;
- }
-
- /**
- * Create tcp syn with proto match.
- *
- * @param matchBuilder the match builder
- * @return matchBuilder match builder
- */
- public static MatchBuilder createTcpSynWithProtoMatch(MatchBuilder matchBuilder) {
-
- // Ethertype match
- EthernetMatchBuilder ethernetType = new EthernetMatchBuilder();
- EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
- ethTypeBuilder.setType(new EtherType(0x0800L));
- ethernetType.setEthernetType(ethTypeBuilder.build());
- matchBuilder.setEthernetMatch(ethernetType.build());
-
- // TCP Protocol Match
- IpMatchBuilder ipMatch = new IpMatchBuilder(); // ipv4 version
- ipMatch.setIpProtocol((short) 6);
- matchBuilder.setIpMatch(ipMatch.build());
-
- TcpFlagsMatchBuilder tcpFlagsMatch = new TcpFlagsMatchBuilder();
- tcpFlagsMatch.setTcpFlags(TCP_SYN);
- matchBuilder.setTcpFlagsMatch(tcpFlagsMatch.build());
- return matchBuilder;
- }
-
- /**
- * Adds tcp syn match to the matchbuilder.
- *
- * @param matchBuilder the match builder
- * @return matchBuilder match builder
- */
- public static MatchBuilder addTcpSynMatch(MatchBuilder matchBuilder) {
-
- // TCP Protocol Match
- IpMatchBuilder ipMatch = new IpMatchBuilder(); // ipv4 version
- ipMatch.setIpProtocol((short) 6);
- matchBuilder.setIpMatch(ipMatch.build());
-
- TcpFlagsMatchBuilder tcpFlagsMatch = new TcpFlagsMatchBuilder();
- tcpFlagsMatch.setTcpFlags(TCP_SYN);
- matchBuilder.setTcpFlagsMatch(tcpFlagsMatch.build());
- return matchBuilder;
- }
-
- /**
- * Create tcp proto syn match.
- *
- * @param matchBuilder the match builder
- * @return matchBuilder match builder
- */
- public static MatchBuilder createTcpProtoSynMatch(MatchBuilder matchBuilder) {
-
- // TCP Protocol Match
- IpMatchBuilder ipMatch = new IpMatchBuilder(); // ipv4 version
- ipMatch.setIpProtocol((short) 6);
- matchBuilder.setIpMatch(ipMatch.build());
-
- TcpFlagsMatchBuilder tcpFlagsMatch = new TcpFlagsMatchBuilder();
- tcpFlagsMatch.setTcpFlags(TCP_SYN);
- matchBuilder.setTcpFlagsMatch(tcpFlagsMatch.build());
- return matchBuilder;
- }
-
- /**
- * Create dmac tcp port with flag match.
- *
- * @param matchBuilder the match builder
- * @param attachedMac the attached mac
- * @param tcpFlags the tcp flag
- * @param tunnelID the tunnel iD
- * @return match containing TCP_Flag (), IP Protocol (TCP), TCP_Flag (SYN)
- */
- public static MatchBuilder createDmacTcpPortWithFlagMatch(MatchBuilder matchBuilder,
- String attachedMac, Integer tcpFlags, String tunnelID) {
- return createDmacTcpPortIpSaWithFlagMatch(matchBuilder, attachedMac, tcpFlags, null, tunnelID);
- }
-
- /**
- * Create dmac ipSa match.
- *
- * @param matchBuilder the match builder
- * @param attachedMac the attached mac
- * @param ipPrefix the src ipPrefix
- * @param tunnelID the tunnel iD
- * @return match containing TCP_Flag (), IP Protocol (TCP), TCP_Flag (SYN), Ip Source Address (IPsa)
- */
- public static MatchBuilder createDmacIpSaMatch(
- MatchBuilder matchBuilder, String attachedMac, Ipv4Prefix ipPrefix, String tunnelID) {
- return createDmacTcpPortIpSaWithFlagMatch(matchBuilder, attachedMac, null, ipPrefix, tunnelID);
- }
-
- /**
- * Create dmac tcp port ipSa with flag match.
- *
- * @param matchBuilder the match builder
- * @param attachedMac the attached mac
- * @param tcpFlags the tcp flag
- * @param ipPrefix the src ipPrefix
- * @param tunnelID the tunnel iD
- * @return match containing TCP_Flag (), IP Protocol (TCP), TCP_Flag (SYN), Ip Source Address (IPsa)
- */
- public static MatchBuilder createDmacTcpPortIpSaWithFlagMatch(
- MatchBuilder matchBuilder, String attachedMac, Integer tcpFlags, Ipv4Prefix ipPrefix, String tunnelID) {
-
- EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder();
- EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
- ethTypeBuilder.setType(new EtherType(0x0800L));
- ethernetMatch.setEthernetType(ethTypeBuilder.build());
-
- if (attachedMac != null) {
- EthernetDestinationBuilder ethDestinationBuilder = new EthernetDestinationBuilder();
- ethDestinationBuilder.setAddress(new MacAddress(attachedMac));
- ethernetMatch.setEthernetDestination(ethDestinationBuilder.build());
- matchBuilder.setEthernetMatch(ethernetMatch.build());
- }
-
- if (tcpFlags != null) {
- // TCP Protocol Match
- IpMatchBuilder ipMatch = new IpMatchBuilder(); // ipv4 version
- ipMatch.setIpProtocol(TCP_SHORT);
- matchBuilder.setIpMatch(ipMatch.build());
-
- TcpFlagsMatchBuilder tcpFlagsMatch = new TcpFlagsMatchBuilder();
- tcpFlagsMatch.setTcpFlags(tcpFlags);
- matchBuilder.setTcpFlagsMatch(tcpFlagsMatch.build());
- }
-
- if (tunnelID != null) {
- TunnelBuilder tunnelBuilder = new TunnelBuilder();
- tunnelBuilder.setTunnelId(new BigInteger(tunnelID));
- matchBuilder.setTunnel(tunnelBuilder.build());
- }
-
- if (ipPrefix != null) {
- Ipv4MatchBuilder ipv4match = new Ipv4MatchBuilder();
- ipv4match.setIpv4Source(ipPrefix);
- matchBuilder.setLayer3Match(ipv4match.build());
- }
-
- return matchBuilder;
- }
-
- /**
- * Create dmac tcp syn match.
- *
- * @param matchBuilder the match builder
- * @param attachedMac the attached mac
- * @param tcpPort the tcp port
- * @param tcpFlags the tcp flag
- * @param tunnelID the tunnel iD
- * @return the match builder
- */
- public static MatchBuilder createDmacTcpSynMatch(MatchBuilder matchBuilder,
- String attachedMac, PortNumber tcpPort, Integer tcpFlags, String tunnelID) {
-
- EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder();
- EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
- ethTypeBuilder.setType(new EtherType(0x0800L));
- ethernetMatch.setEthernetType(ethTypeBuilder.build());
-
- EthernetDestinationBuilder ethDestinationBuilder = new EthernetDestinationBuilder();
- ethDestinationBuilder.setAddress(new MacAddress(attachedMac));
- ethernetMatch.setEthernetDestination(ethDestinationBuilder.build());
- matchBuilder.setEthernetMatch(ethernetMatch.build());
-
- // TCP Protocol Match
- IpMatchBuilder ipMatch = new IpMatchBuilder(); // ipv4 version
- ipMatch.setIpProtocol((short) 6);
- matchBuilder.setIpMatch(ipMatch.build());
-
- // TCP Port Match
- PortNumber dstPort = new PortNumber(tcpPort);
- TcpMatchBuilder tcpMatch = new TcpMatchBuilder();
- tcpMatch.setTcpDestinationPort(dstPort);
- matchBuilder.setLayer4Match(tcpMatch.build());
-
- TcpFlagsMatchBuilder tcpFlagsMatch = new TcpFlagsMatchBuilder();
- tcpFlagsMatch.setTcpFlags(tcpFlags);
- matchBuilder.setTcpFlagsMatch(tcpFlagsMatch.build());
-
- TunnelBuilder tunnelBuilder = new TunnelBuilder();
- tunnelBuilder.setTunnelId(new BigInteger(tunnelID));
- matchBuilder.setTunnel(tunnelBuilder.build());
-
- return matchBuilder;
- }
-
- /**
- * Create dmac tcp syn dst ip prefix tcp port.
- *
- * @param matchBuilder the match builder
- * @param attachedMac the attached mac
- * @param tcpPort the tcp port
- * @param tcpFlags the tcp flag
- * @param segmentationId the segmentation id
- * @param dstIp the dst ip
- * @return the match builder
- */
- public static MatchBuilder createDmacTcpSynDstIpPrefixTcpPort(MatchBuilder matchBuilder,
- MacAddress attachedMac, PortNumber tcpPort, Integer tcpFlags, String segmentationId,
- Ipv4Prefix dstIp) {
-
- EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder();
- EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
- ethTypeBuilder.setType(new EtherType(0x0800L));
- ethernetMatch.setEthernetType(ethTypeBuilder.build());
-
- EthernetDestinationBuilder ethDestinationBuilder = new EthernetDestinationBuilder();
- ethDestinationBuilder.setAddress(attachedMac);
- ethernetMatch.setEthernetDestination(ethDestinationBuilder.build());
-
- matchBuilder.setEthernetMatch(ethernetMatch.build());
-
- Ipv4MatchBuilder ipv4match = new Ipv4MatchBuilder();
- ipv4match.setIpv4Destination(dstIp);
- matchBuilder.setLayer3Match(ipv4match.build());
-
- // TCP Protocol Match
- IpMatchBuilder ipMatch = new IpMatchBuilder(); // ipv4 version
- ipMatch.setIpProtocol(TCP_SHORT);
- matchBuilder.setIpMatch(ipMatch.build());
-
- // TCP Port Match
- PortNumber dstPort = new PortNumber(tcpPort);
- TcpMatchBuilder tcpMatch = new TcpMatchBuilder();
- tcpMatch.setTcpDestinationPort(dstPort);
- matchBuilder.setLayer4Match(tcpMatch.build());
-
- TcpFlagsMatchBuilder tcpFlagsMatch = new TcpFlagsMatchBuilder();
- tcpFlagsMatch.setTcpFlags(tcpFlags);
- matchBuilder.setTcpFlagsMatch(tcpFlagsMatch.build());
-
- TunnelBuilder tunnelBuilder = new TunnelBuilder();
- tunnelBuilder.setTunnelId(new BigInteger(segmentationId));
- matchBuilder.setTunnel(tunnelBuilder.build());
-
- return matchBuilder;
- }
-
- /**
- * Create dmac ip tcp syn match.
- *
- * @param matchBuilder the match builder
- * @param dMacAddr the d mac addr
- * @param mask the mask
- * @param ipPrefix the ip prefix
- * @return MatchBuilder containing the metadata match values
- */
- public static MatchBuilder createDmacIpTcpSynMatch(MatchBuilder matchBuilder,
- MacAddress dMacAddr, MacAddress mask, Ipv4Prefix ipPrefix) {
-
- EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder();
- EthernetDestinationBuilder ethDestBuilder = new EthernetDestinationBuilder();
- ethDestBuilder.setAddress(dMacAddr);
- if (mask != null) {
- ethDestBuilder.setMask(mask);
- }
- ethernetMatch.setEthernetDestination(ethDestBuilder.build());
- matchBuilder.setEthernetMatch(ethernetMatch.build());
- // Ethertype match
- EthernetMatchBuilder ethernetType = new EthernetMatchBuilder();
- EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
- ethTypeBuilder.setType(new EtherType(0x0800L));
- ethernetType.setEthernetType(ethTypeBuilder.build());
- matchBuilder.setEthernetMatch(ethernetType.build());
- if (ipPrefix != null) {
- Ipv4MatchBuilder ipv4match = new Ipv4MatchBuilder();
- ipv4match.setIpv4Destination(ipPrefix);
- matchBuilder.setLayer3Match(ipv4match.build());
- }
- // TCP Protocol Match
- IpMatchBuilder ipMatch = new IpMatchBuilder(); // ipv4 version
- ipMatch.setIpProtocol(TCP_SHORT);
- matchBuilder.setIpMatch(ipMatch.build());
- // TCP Flag Match
- TcpFlagsMatchBuilder tcpFlagsMatch = new TcpFlagsMatchBuilder();
- tcpFlagsMatch.setTcpFlags(TCP_SYN);
- matchBuilder.setTcpFlagsMatch(tcpFlagsMatch.build());
-
- return matchBuilder;
- }
-
- /**
- * Create smac tcp syn dst ip prefix tcp port.
- *
- * @param matchBuilder the match builder
- * @param attachedMac the attached mac
- * @param tcpPort the tcp port
- * @param tcpFlags the tcp flag
- * @param segmentationId the segmentation id
- * @param dstIp the dst ip
- * @return the match builder
- */
- public static MatchBuilder createSmacTcpSynDstIpPrefixTcpPort(MatchBuilder matchBuilder, MacAddress attachedMac,
- PortNumber tcpPort, Integer tcpFlags, String segmentationId, Ipv4Prefix dstIp) {
-
- EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder();
- EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
- ethTypeBuilder.setType(new EtherType(0x0800L));
- ethernetMatch.setEthernetType(ethTypeBuilder.build());
-
- EthernetSourceBuilder ethSourceBuilder = new EthernetSourceBuilder();
- ethSourceBuilder.setAddress(attachedMac);
- ethernetMatch.setEthernetSource(ethSourceBuilder.build());
-
- matchBuilder.setEthernetMatch(ethernetMatch.build());
-
- Ipv4MatchBuilder ipv4match = new Ipv4MatchBuilder();
- ipv4match.setIpv4Destination(dstIp);
- matchBuilder.setLayer3Match(ipv4match.build());
-
- // TCP Protocol Match
- IpMatchBuilder ipMatch = new IpMatchBuilder(); // ipv4 version
- ipMatch.setIpProtocol(TCP_SHORT);
- matchBuilder.setIpMatch(ipMatch.build());
-
- // TCP Port Match
- PortNumber dstPort = new PortNumber(tcpPort);
- TcpMatchBuilder tcpMatch = new TcpMatchBuilder();
- tcpMatch.setTcpDestinationPort(dstPort);
- matchBuilder.setLayer4Match(tcpMatch.build());
-
- TcpFlagsMatchBuilder tcpFlagsMatch = new TcpFlagsMatchBuilder();
- tcpFlagsMatch.setTcpFlags(tcpFlags);
- matchBuilder.setTcpFlagsMatch(tcpFlagsMatch.build());
-
- TunnelBuilder tunnelBuilder = new TunnelBuilder();
- tunnelBuilder.setTunnelId(new BigInteger(segmentationId));
- matchBuilder.setTunnel(tunnelBuilder.build());
-
- return matchBuilder;
- }
-
- /**
- * Create smac tcp port with flag match.
- *
- * @param matchBuilder the match builder
- * @param attachedMac the attached mac
- * @param tcpFlags the tcp flag
- * @param tunnelID the tunnel iD
- * @return matchBuilder
- */
- public static MatchBuilder createSmacTcpPortWithFlagMatch(MatchBuilder matchBuilder, String attachedMac,
- Integer tcpFlags, String tunnelID) {
-
- EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder();
- EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
- ethTypeBuilder.setType(new EtherType(0x0800L));
- ethernetMatch.setEthernetType(ethTypeBuilder.build());
-
- EthernetSourceBuilder ethSrcBuilder = new EthernetSourceBuilder();
- ethSrcBuilder.setAddress(new MacAddress(attachedMac));
- ethernetMatch.setEthernetSource(ethSrcBuilder.build());
- matchBuilder.setEthernetMatch(ethernetMatch.build());
-
- // TCP Protocol Match
- IpMatchBuilder ipMatch = new IpMatchBuilder(); // ipv4 version
- ipMatch.setIpProtocol(TCP_SHORT);
- matchBuilder.setIpMatch(ipMatch.build());
-
- TcpFlagsMatchBuilder tcpFlagsMatch = new TcpFlagsMatchBuilder();
- tcpFlagsMatch.setTcpFlags(tcpFlags);
- matchBuilder.setTcpFlagsMatch(tcpFlagsMatch.build());
-
- TunnelBuilder tunnelBuilder = new TunnelBuilder();
- tunnelBuilder.setTunnelId(new BigInteger(tunnelID));
- matchBuilder.setTunnel(tunnelBuilder.build());
-
- return matchBuilder;
- }
-
- /**
- * Create smac ip tcp syn match.
- *
- * @param matchBuilder the match builder
- * @param dMacAddr the d mac addr
- * @param mask the mask
- * @param ipPrefix the ip prefix
- * @return MatchBuilder containing the metadata match values
- */
- public static MatchBuilder createSmacIpTcpSynMatch(MatchBuilder matchBuilder, MacAddress dMacAddr,
- MacAddress mask, Ipv4Prefix ipPrefix) {
-
- EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder();
- EthernetSourceBuilder ethSrcBuilder = new EthernetSourceBuilder();
- ethSrcBuilder.setAddress(dMacAddr);
- if (mask != null) {
- ethSrcBuilder.setMask(mask);
- }
- ethernetMatch.setEthernetSource(ethSrcBuilder.build());
- matchBuilder.setEthernetMatch(ethernetMatch.build());
- // Ethertype match
- EthernetMatchBuilder ethernetType = new EthernetMatchBuilder();
- EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
- ethTypeBuilder.setType(new EtherType(0x0800L));
- ethernetType.setEthernetType(ethTypeBuilder.build());
- matchBuilder.setEthernetMatch(ethernetType.build());
- if (ipPrefix != null) {
- Ipv4MatchBuilder ipv4match = new Ipv4MatchBuilder();
- ipv4match.setIpv4Destination(ipPrefix);
- matchBuilder.setLayer3Match(ipv4match.build());
- }
- // TCP Protocol Match
- IpMatchBuilder ipMatch = new IpMatchBuilder(); // ipv4 version
- ipMatch.setIpProtocol(TCP_SHORT);
- matchBuilder.setIpMatch(ipMatch.build());
- // TCP Flag Match
- TcpFlagsMatchBuilder tcpFlagsMatch = new TcpFlagsMatchBuilder();
- tcpFlagsMatch.setTcpFlags(TCP_SYN);
- matchBuilder.setTcpFlagsMatch(tcpFlagsMatch.build());
-
- return matchBuilder;
- }
-
- /**
- * Create smac tcp syn.
- *
- * @param matchBuilder the match builder
- * @param attachedMac the attached mac
- * @param tcpPort the tcp port
- * @param tcpFlags the tcp flag
- * @param tunnelID the tunnel iD
- * @return the match builder
- */
- public static MatchBuilder createSmacTcpSyn(MatchBuilder matchBuilder,
- String attachedMac, PortNumber tcpPort, Integer tcpFlags, String tunnelID) {
-
- EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder();
- EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
- ethTypeBuilder.setType(new EtherType(0x0800L));
- ethernetMatch.setEthernetType(ethTypeBuilder.build());
-
- EthernetSourceBuilder ethSrcBuilder = new EthernetSourceBuilder();
- ethSrcBuilder.setAddress(new MacAddress(attachedMac));
- ethernetMatch.setEthernetSource(ethSrcBuilder.build());
- matchBuilder.setEthernetMatch(ethernetMatch.build());
-
- // TCP Protocol Match
- IpMatchBuilder ipMatch = new IpMatchBuilder(); // ipv4 version
- ipMatch.setIpProtocol((short) 6);
- matchBuilder.setIpMatch(ipMatch.build());
-
- // TCP Port Match
- PortNumber dstPort = new PortNumber(tcpPort);
- TcpMatchBuilder tcpMatch = new TcpMatchBuilder();
- tcpMatch.setTcpDestinationPort(dstPort);
- matchBuilder.setLayer4Match(tcpMatch.build());
-
-
- TcpFlagsMatchBuilder tcpFlagsMatch = new TcpFlagsMatchBuilder();
- tcpFlagsMatch.setTcpFlags(tcpFlags);
- matchBuilder.setTcpFlagsMatch(tcpFlagsMatch.build());
-
- TunnelBuilder tunnelBuilder = new TunnelBuilder();
- tunnelBuilder.setTunnelId(new BigInteger(tunnelID));
- matchBuilder.setTunnel(tunnelBuilder.build());
-
- return matchBuilder;
- }
-
- /**
- * @return MatchBuilder containing the metadata match values
- */
- public static MatchBuilder createMacSrcIpTcpSynMatch(MatchBuilder matchBuilder,
- MacAddress dMacAddr, MacAddress mask, Ipv4Prefix ipPrefix) {
-
- EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder();
- EthernetDestinationBuilder ethDestinationBuilder = new EthernetDestinationBuilder();
- ethDestinationBuilder.setAddress(dMacAddr);
- if (mask != null) {
- ethDestinationBuilder.setMask(mask);
- }
- ethernetMatch.setEthernetDestination(ethDestinationBuilder.build());
- matchBuilder.setEthernetMatch(ethernetMatch.build());
- // Ethertype match
- EthernetMatchBuilder ethernetType = new EthernetMatchBuilder();
- EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
- ethTypeBuilder.setType(new EtherType(0x0800L));
- ethernetType.setEthernetType(ethTypeBuilder.build());
- matchBuilder.setEthernetMatch(ethernetType.build());
- if (ipPrefix != null) {
- Ipv4MatchBuilder ipv4match = new Ipv4MatchBuilder();
- ipv4match.setIpv4Source(ipPrefix);
- matchBuilder.setLayer3Match(ipv4match.build());
- }
- // TCP Protocol Match
- IpMatchBuilder ipMatch = new IpMatchBuilder(); // ipv4 version
- ipMatch.setIpProtocol(TCP_SHORT);
- matchBuilder.setIpMatch(ipMatch.build());
- // TCP Flag Match
- TcpFlagsMatchBuilder tcpFlagsMatch = new TcpFlagsMatchBuilder();
- tcpFlagsMatch.setTcpFlags(TCP_SYN);
- matchBuilder.setTcpFlagsMatch(tcpFlagsMatch.build());
-
- return matchBuilder;
- }
-
- /**
- * Create a DHCP match with port provided.
- *
- * @param matchBuilder the match builder
- * @param srcPort the source port
- * @param dstPort the destination port
- * @return the DHCP match
- */
- public static MatchBuilder createDhcpMatch(MatchBuilder matchBuilder,
- int srcPort, int dstPort) {
-
- EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder();
- EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
- ethTypeBuilder.setType(new EtherType(0x0800L));
- ethernetMatch.setEthernetType(ethTypeBuilder.build());
- matchBuilder.setEthernetMatch(ethernetMatch.build());
-
- IpMatchBuilder ipmatch = new IpMatchBuilder();
- ipmatch.setIpProtocol(UDP_SHORT);
- matchBuilder.setIpMatch(ipmatch.build());
-
- UdpMatchBuilder udpmatch = new UdpMatchBuilder();
- udpmatch.setUdpSourcePort(new PortNumber(srcPort));
- udpmatch.setUdpDestinationPort(new PortNumber(dstPort));
- matchBuilder.setLayer4Match(udpmatch.build());
-
- return matchBuilder;
-
- }
-
- /**
- * Create a DHCP match with port provided.
- *
- * @param matchBuilder the match builder
- * @param srcPort the source port
- * @param dstPort the destination port
- * @return the DHCP match
- */
- public static MatchBuilder createDhcpv6Match(MatchBuilder matchBuilder,
- int srcPort, int dstPort) {
-
- EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder();
- EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
- ethTypeBuilder.setType(new EtherType(0x86DDL));
- ethernetMatch.setEthernetType(ethTypeBuilder.build());
- matchBuilder.setEthernetMatch(ethernetMatch.build());
-
- IpMatchBuilder ipmatch = new IpMatchBuilder();
- ipmatch.setIpProtocol(UDP_SHORT);
- matchBuilder.setIpMatch(ipmatch.build());
-
- UdpMatchBuilder udpmatch = new UdpMatchBuilder();
- udpmatch.setUdpSourcePort(new PortNumber(srcPort));
- udpmatch.setUdpDestinationPort(new PortNumber(dstPort));
- matchBuilder.setLayer4Match(udpmatch.build());
-
- return matchBuilder;
-
- }
-
- /**
- * Creates DHCP server packet match with DHCP mac address and port.
- *
- * @param matchBuilder the matchbuilder
- * @param dhcpServerMac MAc address of the DHCP server of the subnet
- * @param srcPort the source port
- * @param dstPort the destination port
- * @return the DHCP server match
- */
- public static MatchBuilder createDhcpServerMatch(MatchBuilder matchBuilder, String dhcpServerMac, int srcPort,
- int dstPort) {
-
- EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder();
- EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
- ethTypeBuilder.setType(new EtherType(0x0800L));
- ethernetMatch.setEthernetType(ethTypeBuilder.build());
- matchBuilder.setEthernetMatch(ethernetMatch.build());
-
- EthernetSourceBuilder ethSourceBuilder = new EthernetSourceBuilder();
- ethSourceBuilder.setAddress(new MacAddress(dhcpServerMac));
- ethernetMatch.setEthernetSource(ethSourceBuilder.build());
- matchBuilder.setEthernetMatch(ethernetMatch.build());
-
- IpMatchBuilder ipmatch = new IpMatchBuilder();
- ipmatch.setIpProtocol(UDP_SHORT);
- matchBuilder.setIpMatch(ipmatch.build());
-
- UdpMatchBuilder udpmatch = new UdpMatchBuilder();
- udpmatch.setUdpSourcePort(new PortNumber(srcPort));
- udpmatch.setUdpDestinationPort(new PortNumber(dstPort));
- matchBuilder.setLayer4Match(udpmatch.build());
-
- return matchBuilder;
-
- }
-
- /**
- * Creates DHCPv6 server packet match with DHCP mac address and port.
- *
- * @param matchBuilder the matchbuilder
- * @param dhcpServerMac MAc address of the DHCP server of the subnet
- * @param srcPort the source port
- * @param dstPort the destination port
- * @return the DHCP server match
- */
- public static MatchBuilder createDhcpv6ServerMatch(MatchBuilder matchBuilder, String dhcpServerMac, int srcPort,
- int dstPort) {
-
- EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder();
- EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
- ethTypeBuilder.setType(new EtherType(0x86DDL));
- ethernetMatch.setEthernetType(ethTypeBuilder.build());
- matchBuilder.setEthernetMatch(ethernetMatch.build());
-
- EthernetSourceBuilder ethSourceBuilder = new EthernetSourceBuilder();
- ethSourceBuilder.setAddress(new MacAddress(dhcpServerMac));
- ethernetMatch.setEthernetSource(ethSourceBuilder.build());
- matchBuilder.setEthernetMatch(ethernetMatch.build());
-
- IpMatchBuilder ipmatch = new IpMatchBuilder();
- ipmatch.setIpProtocol(UDP_SHORT);
- matchBuilder.setIpMatch(ipmatch.build());
-
- UdpMatchBuilder udpmatch = new UdpMatchBuilder();
- udpmatch.setUdpSourcePort(new PortNumber(srcPort));
- udpmatch.setUdpDestinationPort(new PortNumber(dstPort));
- matchBuilder.setLayer4Match(udpmatch.build());
-
- return matchBuilder;
-
- }
-
- /**
- * Creates a Match with src ip address mac address set.
- * @param matchBuilder MatchBuilder Object
- * @param srcip String containing an IPv4 prefix
- * @param srcMac The source macAddress
- * @return matchBuilder Map Object with a match
- */
- public static MatchBuilder createSrcL3Ipv4MatchWithMac(MatchBuilder matchBuilder, Ipv4Prefix srcip, MacAddress srcMac) {
-
- Ipv4MatchBuilder ipv4MatchBuilder = new Ipv4MatchBuilder();
- ipv4MatchBuilder.setIpv4Source(srcip);
- EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
- ethTypeBuilder.setType(new EtherType(0x0800L));
- EthernetMatchBuilder eth = new EthernetMatchBuilder();
- eth.setEthernetType(ethTypeBuilder.build());
- eth.setEthernetSource(new EthernetSourceBuilder()
- .setAddress(srcMac)
- .build());
-
- matchBuilder.setLayer3Match(ipv4MatchBuilder.build());
- matchBuilder.setEthernetMatch(eth.build());
- return matchBuilder;
-
- }
-
- /**
- * Creates a Match with src ip address mac address set.
- * @param matchBuilder MatchBuilder Object
- * @param srcip String containing an IPv6 prefix
- * @param srcMac The source macAddress
- * @return matchBuilder Map Object with a match
- */
- public static MatchBuilder createSrcL3Ipv6MatchWithMac(MatchBuilder matchBuilder, Ipv6Prefix srcip, MacAddress srcMac) {
-
- Ipv6MatchBuilder ipv6MatchBuilder = new Ipv6MatchBuilder();
- ipv6MatchBuilder.setIpv6Source(srcip);
- EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
- ethTypeBuilder.setType(new EtherType(0x86DDL));
- EthernetMatchBuilder eth = new EthernetMatchBuilder();
- eth.setEthernetType(ethTypeBuilder.build());
- eth.setEthernetSource(new EthernetSourceBuilder()
- .setAddress(srcMac)
- .build());
-
- matchBuilder.setLayer3Match(ipv6MatchBuilder.build());
- matchBuilder.setEthernetMatch(eth.build());
- return matchBuilder;
-
- }
-
- /**
- * Creates a ether net match with ether type set to 0x0800L.
- * @param matchBuilder MatchBuilder Object
- * @param srcMac The source macAddress
- * @param dstMac The destination mac address
- * @return matchBuilder Map Object with a match
- */
- public static MatchBuilder createV4EtherMatchWithType(MatchBuilder matchBuilder,String srcMac, String dstMac, Long type)
- {
- EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
- ethTypeBuilder.setType(new EtherType(type));
- EthernetMatchBuilder eth = new EthernetMatchBuilder();
- eth.setEthernetType(ethTypeBuilder.build());
- if (null != srcMac) {
- eth.setEthernetSource(new EthernetSourceBuilder()
- .setAddress(new MacAddress(srcMac)).build());
- }
- if (null != dstMac) {
- eth.setEthernetDestination(new EthernetDestinationBuilder()
- .setAddress(new MacAddress(dstMac)).build());
- }
- matchBuilder.setEthernetMatch(eth.build());
- return matchBuilder;
- }
- /**
- * Creates a ether net match with ether type set to 0x0800L.
- * @param matchBuilder MatchBuilder Object
- * @param srcMac The source macAddress
- * @param dstMac The destination mac address
- * @param type The Tcp type
- * @param dstPort The destination port
- * @return matchBuilder Map Object with a match
- */
- public static MatchBuilder createV4EtherMatchWithLearnTCP(MatchBuilder matchBuilder,String srcMac, String dstMac, Long type, Integer dstPort)
- {
- matchBuilder = createV4EtherMatchWithType(matchBuilder, srcMac, dstMac, type);
- TcpMatchBuilder tcpmatch = new TcpMatchBuilder();
- tcpmatch.setTcpDestinationPort(new PortNumber(dstPort));
- matchBuilder.setLayer4Match(tcpmatch.build());
- return matchBuilder;
- }
- /**
- * Creates a ether net match with ether type set to 0x0800L.
- * @param matchBuilder MatchBuilder Object
- * @param srcMac The source macAddress
- * @param dstMac The destination mac address
- * @param type The UDP type
- * @param dstPort The destination port
- * @return matchBuilder Map Object with a match
- */
- public static MatchBuilder createV4EtherMatchWithLearnUDP(MatchBuilder matchBuilder,String srcMac, String dstMac, Long type, Integer dstPort)
- {
- matchBuilder = createV4EtherMatchWithType(matchBuilder, srcMac, dstMac, type);
- UdpMatchBuilder udpmatch = new UdpMatchBuilder();
- udpmatch.setUdpDestinationPort(new PortNumber(dstPort));
- matchBuilder.setLayer4Match(udpmatch.build());
- return matchBuilder;
- }
- /**
- * Creates a ether net match with ether type set to 0x0800L.
- * @param matchBuilder MatchBuilder Object
- * @param srcMac The source macAddress
- * @param dstMac The destination mac address
- * @return matchBuilder Map Object with a match
- */
- public static MatchBuilder createV4EtherMatchWithoutType(MatchBuilder matchBuilder,String srcMac, String dstMac)
- {
- EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
- EthernetMatchBuilder eth = new EthernetMatchBuilder();
- if (null != srcMac) {
- eth.setEthernetSource(new EthernetSourceBuilder()
- .setAddress(new MacAddress(srcMac)).build());
- }
- if (null != dstMac) {
- eth.setEthernetDestination(new EthernetDestinationBuilder()
- .setAddress(new MacAddress(dstMac)).build());
- }
- matchBuilder.setEthernetMatch(eth.build());
- return matchBuilder;
- }
-
- /**
- * Creates a ether net match with ether type set to 0x86DDL.
- * @param matchBuilder MatchBuilder Object
- * @param srcMac The source macAddress
- * @param dstMac The destination mac address
- * @return matchBuilder Map Object with a match
- */
- public static MatchBuilder createV6EtherMatchWithType(MatchBuilder matchBuilder,String srcMac, String dstMac)
- {
- EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
- ethTypeBuilder.setType(new EtherType(0x86DDL));
- EthernetMatchBuilder eth = new EthernetMatchBuilder();
- eth.setEthernetType(ethTypeBuilder.build());
- if (null != srcMac) {
- eth.setEthernetSource(new EthernetSourceBuilder()
- .setAddress(new MacAddress(srcMac)).build());
- }
- if (null != dstMac) {
- eth.setEthernetDestination(new EthernetDestinationBuilder()
- .setAddress(new MacAddress(dstMac)).build());
- }
- matchBuilder.setEthernetMatch(eth.build());
- return matchBuilder;
- }
-
- /**
- * Adds remote Ip prefix to existing match.
- * @param matchBuilder The match builder
- * @param sourceIpPrefix The source IP prefix
- * @param destIpPrefix The destination IP prefix
- * @return matchBuilder Map Object with a match
- */
- public static MatchBuilder addRemoteIpPrefix(MatchBuilder matchBuilder,
- Ipv4Prefix sourceIpPrefix,Ipv4Prefix destIpPrefix) {
- Ipv4MatchBuilder ipv4match = new Ipv4MatchBuilder();
- if (null != sourceIpPrefix) {
- ipv4match.setIpv4Source(sourceIpPrefix);
- }
- if (null != destIpPrefix) {
- ipv4match.setIpv4Destination(destIpPrefix);
- }
- matchBuilder.setLayer3Match(ipv4match.build());
-
- return matchBuilder;
- }
-
- /**
- * Adds remote Ipv6 prefix to existing match.
- * @param matchBuilder The match builder
- * @param sourceIpPrefix The source IP prefix
- * @param destIpPrefix The destination IP prefix
- * @return matchBuilder Map Object with a match
- */
- public static MatchBuilder addRemoteIpv6Prefix(MatchBuilder matchBuilder,
- Ipv6Prefix sourceIpPrefix,Ipv6Prefix destIpPrefix) {
- Ipv6MatchBuilder ipv6match = new Ipv6MatchBuilder();
- if (null != sourceIpPrefix) {
- ipv6match.setIpv6Source(sourceIpPrefix);
- }
- if (null != destIpPrefix) {
- ipv6match.setIpv6Destination(destIpPrefix);
- }
- matchBuilder.setLayer3Match(ipv6match.build());
-
- return matchBuilder;
- }
-
- /**
- * Add a DSCP match to an existing match
- * @param matchBuilder Map matchBuilder MatchBuilder Object with a match
- * @param dscpValue
- * @return {@link MatchBuilder}
- */
- public static MatchBuilder addDscp(MatchBuilder matchBuilder, short dscpValue) {
- createEtherTypeMatch(matchBuilder, new EtherType(ETHERTYPE_IPV4));
- return matchBuilder.setIpMatch(
- new IpMatchBuilder()
- .setIpDscp(new Dscp(dscpValue))
- .build());
- }
-
- /**
- * Add a layer4 match to an existing match
- *
- * @param matchBuilder Map matchBuilder MatchBuilder Object with a match
- * @param protocol The layer4 protocol
- * @param srcPort The src port
- * @param destPort The destination port
- * @return matchBuilder Map Object with a match
- */
- public static MatchBuilder addLayer4Match(MatchBuilder matchBuilder,
- int protocol, int srcPort, int destPort) {
- IpMatchBuilder ipmatch = new IpMatchBuilder();
- if (TCP_SHORT == protocol) {
- ipmatch.setIpProtocol(TCP_SHORT);
- TcpMatchBuilder tcpmatch = new TcpMatchBuilder();
- if (0 != srcPort) {
- tcpmatch.setTcpSourcePort(new PortNumber(srcPort));
- }
- if (0 != destPort) {
- tcpmatch.setTcpDestinationPort(new PortNumber(destPort));
- }
- matchBuilder.setLayer4Match(tcpmatch.build());
- } else if (UDP_SHORT == protocol) {
- ipmatch.setIpProtocol(UDP_SHORT);
- UdpMatchBuilder udpMatch = new UdpMatchBuilder();
- if (0 != srcPort) {
- udpMatch.setUdpSourcePort(new PortNumber(srcPort));
- }
- if (0 != destPort) {
- udpMatch.setUdpDestinationPort(new PortNumber(destPort));
- }
- matchBuilder.setLayer4Match(udpMatch.build());
- } else if (SCTP_SHORT == protocol) {
- ipmatch.setIpProtocol(SCTP_SHORT);
- SctpMatchBuilder sctpMatchBuilder = new SctpMatchBuilder();
- if (0 != srcPort) {
- sctpMatchBuilder.setSctpSourcePort(new PortNumber(srcPort));
- }
- if (0 != destPort) {
- sctpMatchBuilder.setSctpDestinationPort(new PortNumber(destPort));
- }
- matchBuilder.setLayer4Match(sctpMatchBuilder.build());
- }
- matchBuilder.setIpMatch(ipmatch.build());
-
- return matchBuilder;
- }
-
- /**
- * Add a layer4 match to an existing match with mask
- *
- * @param matchBuilder Map matchBuilder MatchBuilder Object with a match.
- * @param protocol The layer4 protocol
- * @param srcPort The src port
- * @param destPort The destination port
- * @param mask the mask for the port
- * @return matchBuilder Map Object with a match
- */
- public static MatchBuilder addLayer4MatchWithMask(MatchBuilder matchBuilder,
- int protocol, int srcPort, int destPort,int mask) {
-
- IpMatchBuilder ipmatch = new IpMatchBuilder();
-
- NxAugMatchNodesNodeTableFlow nxAugMatch = null;
- GeneralAugMatchNodesNodeTableFlow genAugMatch = null;
- if (protocol == TCP_SHORT) {
- ipmatch.setIpProtocol(TCP_SHORT);
- if (0 != srcPort) {
- NxmOfTcpSrcBuilder tcpSrc = new NxmOfTcpSrcBuilder();
- tcpSrc.setPort(new PortNumber(srcPort));
- tcpSrc.setMask(mask);
- nxAugMatch = new NxAugMatchNodesNodeTableFlowBuilder().setNxmOfTcpSrc(tcpSrc.build()).build();
- genAugMatch = new GeneralAugMatchNodesNodeTableFlowBuilder()
- .setExtensionList(ImmutableList.of(new ExtensionListBuilder().setExtensionKey(NxmOfTcpSrcKey.class)
- .setExtension(new ExtensionBuilder()
- .addAugmentation(NxAugMatchNodesNodeTableFlow.class, nxAugMatch)
- .build()).build())).build();
- } else if (0 != destPort) {
- NxmOfTcpDstBuilder tcpDst = new NxmOfTcpDstBuilder();
- tcpDst.setPort(new PortNumber(destPort));
- tcpDst.setMask(mask);
- nxAugMatch = new NxAugMatchNodesNodeTableFlowBuilder()
- .setNxmOfTcpDst(tcpDst.build())
- .build();
- genAugMatch = new GeneralAugMatchNodesNodeTableFlowBuilder()
- .setExtensionList(ImmutableList.of(new ExtensionListBuilder().setExtensionKey(NxmOfTcpDstKey.class)
- .setExtension(new ExtensionBuilder()
- .addAugmentation(NxAugMatchNodesNodeTableFlow.class, nxAugMatch)
- .build()).build())).build();
- }
-
- } else if (UDP_SHORT == protocol) {
- ipmatch.setIpProtocol(UDP_SHORT);
- new UdpMatchBuilder();
- if (0 != srcPort) {
- NxmOfUdpSrcBuilder udpSrc = new NxmOfUdpSrcBuilder();
- udpSrc.setPort(new PortNumber(srcPort));
- udpSrc.setMask(mask);
- nxAugMatch = new NxAugMatchNodesNodeTableFlowBuilder().setNxmOfUdpSrc(udpSrc.build()).build();
- genAugMatch = new GeneralAugMatchNodesNodeTableFlowBuilder()
- .setExtensionList(ImmutableList.of(new ExtensionListBuilder().setExtensionKey(NxmOfUdpSrcKey.class)
- .setExtension(new ExtensionBuilder()
- .addAugmentation(NxAugMatchNodesNodeTableFlow.class, nxAugMatch)
- .build()).build())).build();
- } else if (0 != destPort) {
- NxmOfUdpDstBuilder udpDst = new NxmOfUdpDstBuilder();
- udpDst.setPort(new PortNumber(destPort));
- udpDst.setMask(mask);
- nxAugMatch = new NxAugMatchNodesNodeTableFlowBuilder()
- .setNxmOfUdpDst(udpDst.build())
- .build();
- genAugMatch = new GeneralAugMatchNodesNodeTableFlowBuilder()
- .setExtensionList(ImmutableList.of(new ExtensionListBuilder().setExtensionKey(NxmOfUdpDstKey.class)
- .setExtension(new ExtensionBuilder()
- .addAugmentation(NxAugMatchNodesNodeTableFlow.class, nxAugMatch)
- .build()).build())).build();
- }
- }
- matchBuilder.setIpMatch(ipmatch.build());
- matchBuilder.addAugmentation(GeneralAugMatchNodesNodeTableFlow.class, genAugMatch);
- return matchBuilder;
- }
-
- public static MatchBuilder addCtState(MatchBuilder matchBuilder,int ct_state, int mask) {
- NxmNxCtStateBuilder ctStateBuilder = new NxmNxCtStateBuilder();
- ctStateBuilder.setCtState((long)ct_state);
- ctStateBuilder.setMask((long)mask);
- NxAugMatchNodesNodeTableFlow nxAugMatch = new NxAugMatchNodesNodeTableFlowBuilder()
- .setNxmNxCtState(ctStateBuilder.build())
- .build();
- GeneralAugMatchNodesNodeTableFlow genAugMatch = new GeneralAugMatchNodesNodeTableFlowBuilder()
- .setExtensionList(ImmutableList.of(new ExtensionListBuilder().setExtensionKey(NxmNxCtStateKey.class)
- .setExtension(new ExtensionBuilder()
- .addAugmentation(NxAugMatchNodesNodeTableFlow.class, nxAugMatch)
- .build()).build())).build();
- matchBuilder.addAugmentation(GeneralAugMatchNodesNodeTableFlow.class, genAugMatch);
- return matchBuilder;
- }
-
- public static MatchBuilder addCtZone(MatchBuilder matchBuilder,int ct_zone) {
- NxmNxCtZoneBuilder ctZoneBuilder = new NxmNxCtZoneBuilder();
- ctZoneBuilder.setCtZone(ct_zone);
- NxAugMatchNodesNodeTableFlow nxAugMatch = new NxAugMatchNodesNodeTableFlowBuilder()
- .setNxmNxCtZone(ctZoneBuilder.build())
- .build();
- GeneralAugMatchNodesNodeTableFlow genAugMatch = new GeneralAugMatchNodesNodeTableFlowBuilder()
- .setExtensionList(ImmutableList.of(new ExtensionListBuilder().setExtensionKey(NxmNxCtZoneKey.class)
- .setExtension(new ExtensionBuilder()
- .addAugmentation(NxAugMatchNodesNodeTableFlow.class, nxAugMatch)
- .build()).build())).build();
- matchBuilder.addAugmentation(GeneralAugMatchNodesNodeTableFlow.class, genAugMatch);
- return matchBuilder;
- }
-
- public static class RegMatch {
- final Class<? extends NxmNxReg> reg;
- final Long value;
- public RegMatch(Class<? extends NxmNxReg> reg, Long value) {
- super();
- this.reg = reg;
- this.value = value;
- }
- public static RegMatch of(Class<? extends NxmNxReg> reg, Long value) {
- return new RegMatch(reg, value);
- }
- }
-
- public static MatchBuilder addNxRegMatch(MatchBuilder matchBuilder, RegMatch... matches) {
- List<ExtensionList> extensions = new ArrayList<>();
- for (RegMatch rm : matches) {
- Class<? extends ExtensionKey> key;
- if (NxmNxReg0.class.equals(rm.reg)) {
- key = NxmNxReg0Key.class;
- } else if (NxmNxReg1.class.equals(rm.reg)) {
- key = NxmNxReg1Key.class;
- } else if (NxmNxReg2.class.equals(rm.reg)) {
- key = NxmNxReg2Key.class;
- } else if (NxmNxReg3.class.equals(rm.reg)) {
- key = NxmNxReg3Key.class;
- } else if (NxmNxReg4.class.equals(rm.reg)) {
- key = NxmNxReg4Key.class;
- } else if (NxmNxReg5.class.equals(rm.reg)) {
- key = NxmNxReg5Key.class;
- } else if (NxmNxReg6.class.equals(rm.reg)) {
- key = NxmNxReg6Key.class;
- } else {
- key = NxmNxReg7Key.class;
- }
- NxAugMatchNodesNodeTableFlow am =
- new NxAugMatchNodesNodeTableFlowBuilder()
- .setNxmNxReg(new NxmNxRegBuilder()
- .setReg(rm.reg)
- .setValue(rm.value)
- .build())
- .build();
- extensions.add(new ExtensionListBuilder()
- .setExtensionKey(key)
- .setExtension(new ExtensionBuilder()
- .addAugmentation(NxAugMatchNodesNodeTableFlow.class, am)
- .build())
- .build());
- }
- GeneralAugMatchNodesNodeTableFlow m = new GeneralAugMatchNodesNodeTableFlowBuilder()
- .setExtensionList(extensions)
- .build();
- matchBuilder.addAugmentation(GeneralAugMatchNodesNodeTableFlow.class, m);
- return matchBuilder;
- }
-
- public static MatchBuilder addNxTunIdMatch(MatchBuilder matchBuilder, int tunId) {
- NxAugMatchNodesNodeTableFlow am = new NxAugMatchNodesNodeTableFlowBuilder()
- .setNxmNxTunId(new NxmNxTunIdBuilder()
- .setValue(BigInteger.valueOf(tunId))
- .build())
- .build();
- GeneralAugMatchNodesNodeTableFlow m =
- new GeneralAugMatchNodesNodeTableFlowBuilder()
- .setExtensionList(ImmutableList.of(new ExtensionListBuilder()
- .setExtensionKey(NxmNxTunIdKey.class)
- .setExtension(new ExtensionBuilder()
- .addAugmentation(NxAugMatchNodesNodeTableFlow.class, am)
- .build())
- .build()))
- .build();
- matchBuilder.addAugmentation(GeneralAugMatchNodesNodeTableFlow.class, m);
- return matchBuilder;
- }
-
- public static MatchBuilder addNxNspMatch(MatchBuilder matchBuilder, long nsp) {
- NxAugMatchNodesNodeTableFlow am = new NxAugMatchNodesNodeTableFlowBuilder()
- .setNxmNxNsp(new NxmNxNspBuilder()
- .setValue(nsp)
- .build())
- .build();
- addExtension(matchBuilder, NxmNxNspKey.class, am);
- return matchBuilder;
- }
-
- public static MatchBuilder addNxNsiMatch(MatchBuilder matchBuilder, short nsi) {
- NxAugMatchNodesNodeTableFlow am = new NxAugMatchNodesNodeTableFlowBuilder()
- .setNxmNxNsi(new NxmNxNsiBuilder()
- .setNsi(nsi)
- .build())
- .build();
- addExtension(matchBuilder, NxmNxNsiKey.class, am);
- return matchBuilder;
- }
-
- private static void addExtension(MatchBuilder matchBuilder, Class<? extends ExtensionKey> extensionKey,
- NxAugMatchNodesNodeTableFlow am) {
- GeneralAugMatchNodesNodeTableFlow existingAugmentations =
- matchBuilder.getAugmentation(GeneralAugMatchNodesNodeTableFlow.class);
- List<ExtensionList> extensions = null;
- if (existingAugmentations != null ) {
- extensions = existingAugmentations.getExtensionList();
- }
- if (extensions == null) {
- extensions = new ArrayList<>();
- }
-
- extensions.add(new ExtensionListBuilder()
- .setExtensionKey(extensionKey)
- .setExtension(new ExtensionBuilder()
- .addAugmentation(NxAugMatchNodesNodeTableFlow.class, am)
- .build())
- .build());
-
- GeneralAugMatchNodesNodeTableFlow m = new GeneralAugMatchNodesNodeTableFlowBuilder()
- .setExtensionList(extensions)
- .build();
- matchBuilder.addAugmentation(GeneralAugMatchNodesNodeTableFlow.class, m);
- }
-
- public static EthernetMatch ethernetMatch(MacAddress srcMac,
- MacAddress dstMac,
- Long etherType) {
- EthernetMatchBuilder emb = new EthernetMatchBuilder();
- if (srcMac != null) {
- emb.setEthernetSource(new EthernetSourceBuilder()
- .setAddress(srcMac)
- .build());
- }
- if (dstMac != null) {
- emb.setEthernetDestination(new EthernetDestinationBuilder()
- .setAddress(dstMac)
- .build());
- }
- if (etherType != null) {
- emb.setEthernetType(new EthernetTypeBuilder()
- .setType(new EtherType(etherType))
- .build());
- }
- return emb.build();
- }
-
- /**
- * Create ipv4 prefix from ipv4 address, by appending /32 mask
- *
- * @param ipv4AddressString the ip address, in string format
- * @return Ipv4Prefix with ipv4Address and /32 mask
- */
- public static Ipv4Prefix iPv4PrefixFromIPv4Address(String ipv4AddressString) {
- return new Ipv4Prefix(ipv4AddressString + "/32");
- }
-
- /**
- * Create ipv6 prefix from ipv6 address, by appending /128 mask
- *
- * @param ipv6AddressString the ip address, in string format
- * @return Ipv6Prefix with ipv6Address and /128 mask
- */
- public static Ipv6Prefix iPv6PrefixFromIPv6Address(String ipv6AddressString) {
- return new Ipv6Prefix(ipv6AddressString + "/128");
- }
-
- /**
- * Converts port range into a set of masked port ranges.
- *
- * @param portMin the strating port of the range.
- * @param portMax the ending port of the range.
- * @return the map contianing the port no and their mask.
- *
- */
- public static Map<Integer,Integer> getLayer4MaskForRange(int portMin, int portMax) {
- int [] offset = {32768,16384,8192,4096,2048,1024,512,256,128,64,32,16,8,4,2,1};
- int[] mask = {0x8000,0xC000,0xE000,0xF000,0xF800,0xFC00,0xFE00,0xFF00,
- 0xFF80,0xFFC0,0xFFE0,0xFFF0,0xFFF8,0xFFFC,0xFFFE,0xFFFF};
- int noOfPorts = portMax - portMin + 1;
- String binaryNoOfPorts = Integer.toBinaryString(noOfPorts);
- int medianOffset = 16 - binaryNoOfPorts.length();
- int medianLength = offset[medianOffset];
- int median = 0;
- for (int tempMedian = 0;tempMedian < portMax;) {
- tempMedian = medianLength + tempMedian;
- if (portMin < tempMedian) {
- median = tempMedian;
- break;
- }
- }
- Map<Integer,Integer> portMap = new HashMap<>();
- int tempMedian = 0;
- int currentMedain = median;
- for (int tempMedianOffset = medianOffset;16 > tempMedianOffset;tempMedianOffset++) {
- tempMedian = currentMedain - offset[tempMedianOffset];
- if (portMin <= tempMedian) {
- for (;portMin <= tempMedian;) {
- portMap.put(tempMedian, mask[tempMedianOffset]);
- currentMedain = tempMedian;
- tempMedian = tempMedian - offset[tempMedianOffset];
- }
- }
- }
- currentMedain = median;
- for (int tempMedianOffset = medianOffset;16 > tempMedianOffset;tempMedianOffset++) {
- tempMedian = currentMedain + offset[tempMedianOffset];
- if (portMax >= tempMedian - 1) {
- for (;portMax >= tempMedian - 1;) {
- portMap.put(currentMedain, mask[tempMedianOffset]);
- currentMedain = tempMedian;
- tempMedian = tempMedian + offset[tempMedianOffset];
- }
- }
- }
- return portMap;
- }
-
- /**
- * Return Long that represents OF port for strings where OF is explicitly provided
- *
- * @param ofPortIdentifier the string with encoded OF port (example format "OFPort|999")
- * @return the OFport or null
- */
- public static Long parseExplicitOFPort(String ofPortIdentifier) {
- if (ofPortIdentifier != null) {
- String[] pair = ofPortIdentifier.split("\\|");
- if ((pair.length > 1) && (pair[0].equalsIgnoreCase("OFPort"))) {
- return new Long(pair[1]);
- }
- }
- return null;
- }
-}
+++ /dev/null
-/*
- * Copyright (C) 2014 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.utils.mdsal.openflow;
-
-import static org.junit.Assert.assertTrue;
-import org.junit.Test;
-
-public class MatchUtilsTest {
-
- @Test
- public void testCreateInPortMatch () {
- assertTrue(true);
- }
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-parent</artifactId>
- <version>0.7.0-SNAPSHOT</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>utils.mdsal-utils</artifactId>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>bundle</packaging>
-
- <developers>
- <developer>
- <name>Anil Vishnoi</name>
- <email>vishnoianil@gmail.com</email>
- <url>https://github.com/vishnoianil</url>
- </developer>
- </developers>
- <scm>
- <connection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</connection>
- <developerConnection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</developerConnection>
- <tag>HEAD</tag>
- <url>https://wiki.opendaylight.org/view/OVSDB_Integration:Main</url>
- </scm>
-
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-binding-api</artifactId>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-core</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <extensions>true</extensions>
- <configuration>
- <instructions>
- <Export-Package>
- org.opendaylight.netvirt.utils.mdsal.utils
- </Export-Package>
- </instructions>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-/*
- * Copyright (c) 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.utils.mdsal.utils;
-
-import com.google.common.base.Optional;
-import com.google.common.util.concurrent.CheckedFuture;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
-import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
-import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class MdsalUtils {
- private static final Logger LOG = LoggerFactory.getLogger(MdsalUtils.class);
- private DataBroker databroker = null;
-
- /**
- * Class constructor setting the data broker.
- *
- * @param dataBroker the {@link org.opendaylight.controller.md.sal.binding.api.DataBroker}
- */
- public MdsalUtils(DataBroker dataBroker) {
- this.databroker = dataBroker;
- }
-
- /**
- * Executes delete as a blocking transaction.
- *
- * @param store {@link LogicalDatastoreType} which should be modified
- * @param path {@link InstanceIdentifier} to read from
- * @param <D> the data object type
- * @return the result of the request
- */
- public <D extends org.opendaylight.yangtools.yang.binding.DataObject> boolean delete(
- final LogicalDatastoreType store, final InstanceIdentifier<D> path) {
- boolean result = false;
- final WriteTransaction transaction = databroker.newWriteOnlyTransaction();
- transaction.delete(store, path);
- CheckedFuture<Void, TransactionCommitFailedException> future = transaction.submit();
- try {
- future.checkedGet();
- result = true;
- } catch (TransactionCommitFailedException e) {
- LOG.warn("Failed to delete {} ", path, e);
- }
- return result;
- }
-
- /**
- * Executes merge as a blocking transaction.
- *
- * @param logicalDatastoreType {@link LogicalDatastoreType} which should be modified
- * @param path {@link InstanceIdentifier} for path to read
- * @param <D> the data object type
- * @return the result of the request
- */
- public <D extends org.opendaylight.yangtools.yang.binding.DataObject> boolean merge(
- final LogicalDatastoreType logicalDatastoreType, final InstanceIdentifier<D> path, D data) {
- boolean result = false;
- final WriteTransaction transaction = databroker.newWriteOnlyTransaction();
- transaction.merge(logicalDatastoreType, path, data, true);
- CheckedFuture<Void, TransactionCommitFailedException> future = transaction.submit();
- try {
- future.checkedGet();
- result = true;
- } catch (TransactionCommitFailedException e) {
- LOG.warn("Failed to merge {} ", path, e);
- }
- return result;
- }
-
- /**
- * Executes put as a blocking transaction.
- *
- * @param logicalDatastoreType {@link LogicalDatastoreType} which should be modified
- * @param path {@link InstanceIdentifier} for path to read
- * @param <D> the data object type
- * @return the result of the request
- */
- public <D extends org.opendaylight.yangtools.yang.binding.DataObject> boolean put(
- final LogicalDatastoreType logicalDatastoreType, final InstanceIdentifier<D> path, D data) {
- boolean result = false;
- final WriteTransaction transaction = databroker.newWriteOnlyTransaction();
- transaction.put(logicalDatastoreType, path, data, true);
- CheckedFuture<Void, TransactionCommitFailedException> future = transaction.submit();
- try {
- future.checkedGet();
- result = true;
- } catch (TransactionCommitFailedException e) {
- LOG.warn("Failed to put {} ", path, e);
- }
- return result;
- }
-
- /**
- * Executes read as a blocking transaction.
- *
- * @param store {@link LogicalDatastoreType} to read
- * @param path {@link InstanceIdentifier} for path to read
- * @param <D> the data object type
- * @return the result as the data object requested
- */
- public <D extends org.opendaylight.yangtools.yang.binding.DataObject> D read(
- final LogicalDatastoreType store, final InstanceIdentifier<D> path) {
- D result = null;
- final ReadOnlyTransaction transaction = databroker.newReadOnlyTransaction();
- Optional<D> optionalDataObject;
- CheckedFuture<Optional<D>, ReadFailedException> future = transaction.read(store, path);
- try {
- optionalDataObject = future.checkedGet();
- if (optionalDataObject.isPresent()) {
- result = optionalDataObject.get();
- } else {
- LOG.debug("{}: Failed to read {}",
- Thread.currentThread().getStackTrace()[1], path);
- }
- } catch (ReadFailedException e) {
- LOG.warn("Failed to read {} ", path, e);
- }
- transaction.close();
- return result;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.utils.mdsal.utils;
-
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-/**
- * This class provides methods for checking or waiting for various md-sal operations to complete.
- * Once an instance is created one must invoke the registerDataChangeListener method
- * with a DataBroker.
- */
-public class NotifyingDataChangeListener implements AutoCloseable, DataChangeListener {
- private static final Logger LOG = LoggerFactory.getLogger(NotifyingDataChangeListener.class);
- private LogicalDatastoreType type;
- private final Set<InstanceIdentifier<?>> createdIids = new HashSet<>();
- private final Set<InstanceIdentifier<?>> removedIids = new HashSet<>();
- private final Set<InstanceIdentifier<?>> updatedIids = new HashSet<>();
- private InstanceIdentifier<?> iid;
- private final int RETRY_WAIT = 100;
- private final int MDSAL_TIMEOUT = 1000;
- private ListenerRegistration<?> listenerRegistration;
- private List<NotifyingDataChangeListener> waitList = null;
-
- /**
- * Create a new NotifyingDataChangeListener
- * @param type
- * @param iid of the md-sal object we're waiting for
- * @param waitList for tracking outstanding changes
- */
- public NotifyingDataChangeListener(LogicalDatastoreType type,
- InstanceIdentifier<?> iid, List<NotifyingDataChangeListener> waitList) {
- this.type = type;
- this.iid = iid;
- this.waitList = waitList;
- if(this.waitList != null) {
- this.waitList.add(this);
- }
- }
-
- /**
- * Completely reset the state of this NotifyingDataChangeListener.
- * @param type
- * @param iid of the md-sal object we're waiting for
- * @throws Exception
- */
- private void modify(LogicalDatastoreType type, InstanceIdentifier<?> iid) throws Exception {
- this.close();
- this.clear();
- this.type = type;
- this.iid = iid;
- }
-
- @Override
- public void onDataChanged(
- AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> asyncDataChangeEvent) {
- LOG.info("{} DataChanged: created {} for {}", type, asyncDataChangeEvent.getCreatedData().keySet(), iid);
- LOG.info("{} DataChanged: updated {} for {}", type, asyncDataChangeEvent.getUpdatedData().keySet(), iid);
- LOG.info("{} DataChanged: removed {} for {}", type, asyncDataChangeEvent.getRemovedPaths(), iid);
- createdIids.addAll(asyncDataChangeEvent.getCreatedData().keySet());
- removedIids.addAll(asyncDataChangeEvent.getRemovedPaths());
- updatedIids.addAll(asyncDataChangeEvent.getUpdatedData().keySet());
- synchronized (this) {
- notifyAll();
- }
- }
-
- public boolean isCreated(InstanceIdentifier<?> iid) {
- return createdIids.remove(iid);
- }
-
- public boolean isUpdated(InstanceIdentifier<?> iid) {
- return updatedIids.remove(iid);
- }
-
- public boolean isRemoved(InstanceIdentifier<?> iid) {
- return removedIids.remove(iid);
- }
-
- public void clear() {
- createdIids.clear();
- removedIids.clear();
- updatedIids.clear();
- }
-
- public void registerDataChangeListener(DataBroker dataBroker) {
- listenerRegistration = dataBroker.registerDataChangeListener(type, iid, this,
- AsyncDataBroker.DataChangeScope.SUBTREE);
- }
-
- public void waitForCreation() throws InterruptedException {
- waitForCreation(MDSAL_TIMEOUT);
- }
-
- public void waitForCreation(long timeout) throws InterruptedException {
- synchronized (this) {
- long _start = System.currentTimeMillis();
- LOG.info("Waiting for {} DataChanged creation on {}", type, iid);
- while (!isCreated(iid) && (System.currentTimeMillis() - _start) < timeout) {
- wait(RETRY_WAIT);
- }
- LOG.info("Woke up, waited {}ms for creation of {}", (System.currentTimeMillis() - _start), iid);
- }
- }
-
- public void waitForUpdate() throws InterruptedException {
- waitForUpdate(MDSAL_TIMEOUT);
- }
-
- public void waitForUpdate(long timeout) throws InterruptedException {
- synchronized (this) {
- long _start = System.currentTimeMillis();
- LOG.info("Waiting for {} DataChanged update on {}", type, iid);
- while (!isUpdated(iid) && (System.currentTimeMillis() - _start) < timeout) {
- wait(RETRY_WAIT);
- }
- LOG.info("Woke up, waited {}ms for update of {}", (System.currentTimeMillis() - _start), iid);
- }
- }
-
- public void waitForDeletion() throws InterruptedException {
- waitForDeletion(MDSAL_TIMEOUT);
- }
-
- public void waitForDeletion(long timeout) throws InterruptedException {
- synchronized (this) {
- long _start = System.currentTimeMillis();
- LOG.info("Waiting for {} DataChanged deletion on {}", type, iid);
- while (!isRemoved(iid) && (System.currentTimeMillis() - _start) < timeout) {
- wait(RETRY_WAIT);
- }
- LOG.info("Woke up, waited {}ms for deletion of {}", (System.currentTimeMillis() - _start), iid);
- }
- }
-
- @Override
- public void close() throws Exception {
- if (listenerRegistration != null) {
- try {
- listenerRegistration.close();
- } catch (final Exception ex) {
- LOG.warn("Failed to close registration {}, iid {}", listenerRegistration, iid, ex);
- }
- }
- if (waitList != null) {
- waitList.remove(this);
- }
- listenerRegistration = null;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Inocybe 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.netvirt.utils.mdsal.utils;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyBoolean;
-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 org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
-import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
-import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-
-import com.google.common.base.Optional;
-import com.google.common.util.concurrent.CheckedFuture;
-
-/**
- * Unit test for class {@link MdsalUtils}
- *
- */
-@RunWith(MockitoJUnitRunner.class)
-@SuppressWarnings({ "unchecked", "rawtypes" })
-public class MdsalUtilsTest {
-
- @InjectMocks private MdsalUtils mdsalUtils;
-
- @Mock private DataBroker databroker;
-
- @Test
- public void testDelete() {
- WriteTransaction writeTransaction = mock(WriteTransaction.class);
- when(databroker.newWriteOnlyTransaction()).thenReturn(writeTransaction);
- CheckedFuture<Void, TransactionCommitFailedException> future = mock(CheckedFuture.class);
- when(writeTransaction.submit()).thenReturn(future );
-
- boolean result = mdsalUtils.delete(LogicalDatastoreType.CONFIGURATION, mock(InstanceIdentifier.class));
-
- verify(writeTransaction, times(1)).delete(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(writeTransaction, times(1)).submit();
-
- assertTrue("Error, the delete transaction failed", result);
- }
-
- @Test
- public void testMerge() {
- WriteTransaction writeTransaction = mock(WriteTransaction.class);
- when(databroker.newWriteOnlyTransaction()).thenReturn(writeTransaction);
- CheckedFuture<Void, TransactionCommitFailedException> future = mock(CheckedFuture.class);
- when(writeTransaction.submit()).thenReturn(future );
-
- boolean result = mdsalUtils.merge(LogicalDatastoreType.CONFIGURATION, mock(InstanceIdentifier.class), mock(DataObject.class));
-
- verify(writeTransaction, times(1)).merge(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(DataObject.class), anyBoolean());
- verify(writeTransaction, times(1)).submit();
-
- assertTrue("Error, the merge transaction failed", result);
- }
-
- @Test
- public void testPut() {
- WriteTransaction writeTransaction = mock(WriteTransaction.class);
- when(databroker.newWriteOnlyTransaction()).thenReturn(writeTransaction);
- CheckedFuture<Void, TransactionCommitFailedException> future = mock(CheckedFuture.class);
- when(writeTransaction.submit()).thenReturn(future );
-
- boolean result = mdsalUtils.put(LogicalDatastoreType.CONFIGURATION, mock(InstanceIdentifier.class), mock(DataObject.class));
-
- verify(writeTransaction, times(1)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(DataObject.class), anyBoolean());
- verify(writeTransaction, times(1)).submit();
-
- assertTrue("Error, the put transaction failed", result);
- }
-
- @Test
- public void testRead() throws ReadFailedException {
- ReadOnlyTransaction readOnlyTransaction = mock(ReadOnlyTransaction.class);
- when(databroker.newReadOnlyTransaction()).thenReturn(readOnlyTransaction);
- CheckedFuture<Optional, ReadFailedException> future = mock(CheckedFuture.class);
- DataObject obj = mock(DataObject.class);
- Optional opt = Optional.of(obj);
- when(future.checkedGet()).thenReturn(opt);
- when(readOnlyTransaction.read(any(LogicalDatastoreType.class), any(InstanceIdentifier.class))).thenReturn(future);
-
- DataObject result = mdsalUtils.read(LogicalDatastoreType.CONFIGURATION, mock(InstanceIdentifier.class));
-
- verify(readOnlyTransaction, times(1)).read(any(LogicalDatastoreType.class), any(InstanceIdentifier.class));
- verify(readOnlyTransaction, times(1)).close();
-
- assertEquals("Error, the read transaction failed", obj, result);
- }
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-Copyright (C) 2016 Red Hat, Inc. and others. All rights reserved.
-
-This program and the accompanying materials are made available under the
-terms of the Eclipse Public License v1.0 which accompanies this distribution,
-and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
-
- <parent>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-parent</artifactId>
- <version>0.7.0-SNAPSHOT</version>
- <relativePath/>
- </parent>
-
- <modelVersion>4.0.0</modelVersion>
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>utils.netvirt-it-utils</artifactId>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>bundle</packaging>
-
- <scm>
- <connection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</connection>
- <developerConnection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</developerConnection>
- <tag>HEAD</tag>
- <url>https://wiki.opendaylight.org/view/OVSDB_Integration:Main</url>
- </scm>
-
- <properties>
- <ovsdb.version>1.5.0-SNAPSHOT</ovsdb.version>
- <openflowplugin.version>0.5.0-SNAPSHOT</openflowplugin.version>
- </properties>
-
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-binding-api</artifactId>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>utils.mdsal-utils</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>openstack.net-virt</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>utils.neutron-utils</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.ovsdb</groupId>
- <artifactId>utils.mdsal-utils</artifactId>
- <version>${ovsdb.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.ovsdb</groupId>
- <artifactId>southbound-api</artifactId>
- <version>${ovsdb.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.ovsdb</groupId>
- <artifactId>utils.southbound-utils</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>utils.mdsal-openflow</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.ovsdb</groupId>
- <artifactId>utils.ovsdb-it-utils</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>ietf-inet-types-2013-07-15</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>ietf-topology</artifactId>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.openflowplugin</groupId>
- <artifactId>openflowplugin-extension-api</artifactId>
- <version>${openflowplugin.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.openflowplugin</groupId>
- <artifactId>openflowplugin-extension-nicira</artifactId>
- <version>${openflowplugin.version}</version>
- </dependency>
- </dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <extensions>true</extensions>
- <configuration>
- <instructions>
- <Embed-Dependency>
- utils.mdsal-openflow;groupId=org.opendaylight.netvirt;type=!pom;inline=false
- </Embed-Dependency>
- <Embed-Transitive>true</Embed-Transitive>
- <Export-Package>
- org.opendaylight.netvirt.utils.netvirt.it.utils
- </Export-Package>
- </instructions>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-/*
- * Copyright (c) 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.utils.netvirt.it.utils;
-
-/**
- * Constants for SouthboundIT.
- */
-public final class ItConstants {
- private ItConstants() {
- throw new AssertionError("This class should not be instantiated.");
- }
-
- public static final String ORG_OPS4J_PAX_LOGGING_CFG = "etc/org.ops4j.pax.logging.cfg";
- 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 USERSPACE_ENABLED = "ovsdb.userspace.enabled";
- public static final String SERVER_EXTRAS = "ovsdbserver.extras";
- public static final String CONNECTION_TYPE = "ovsdbserver.connection";
- public static final String CONNECTION_TYPE_ACTIVE = "active";
- public static final String CONNECTION_TYPE_PASSIVE = "passive";
- public static final int CONNECTION_INIT_TIMEOUT = 10000;
- public static final String DEFAULT_SERVER_IPADDRESS = "127.0.0.1";
- public static final String DEFAULT_SERVER_PORT = "6640";
- public static final String DEFAULT_OPENFLOW_PORT = "6653";
- public static final String DEFAULT_SERVER_EXTRAS = "false";
- public static final String BRIDGE_NAME = "brtest";
- public static final String PORT_NAME = "porttest";
- public static final String INTEGRATION_BRIDGE_NAME = "br-int";
- public static final String OPENFLOW_CONNECTION_PROTOCOL = "tcp";
- public static final String NETVIRT_TOPOLOGY_ID = "netvirt:1";
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.utils.netvirt.it.utils;
-
-import static org.junit.Assert.assertNotNull;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Objects;
-import org.junit.Assert;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
-import org.opendaylight.netvirt.utils.mdsal.openflow.FlowUtils;
-import org.opendaylight.ovsdb.utils.mdsal.utils.MdsalUtils;
-import org.opendaylight.ovsdb.utils.mdsal.utils.NotifyingDataChangeListener;
-import org.opendaylight.ovsdb.utils.southbound.utils.SouthboundUtils;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
-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.flow.Match;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.GeneralAugMatchNodesNodeTableFlow;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.GeneralAugMatchNotifPacketIn;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.GeneralAugMatchNotifSwitchFlowRemoved;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.GeneralAugMatchNotifUpdateFlowStats;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.GeneralAugMatchRpcAddFlow;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.GeneralAugMatchRpcRemoveFlow;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.GeneralAugMatchRpcUpdateFlowOriginal;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.GeneralAugMatchRpcUpdateFlowUpdated;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.GeneralExtensionListGrouping;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.general.extension.list.grouping.ExtensionList;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.AllMatchesGrouping;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxAugMatchNodesNodeTableFlow;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxAugMatchNotifPacketIn;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxAugMatchNotifSwitchFlowRemoved;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxAugMatchNotifUpdateFlowStats;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxAugMatchRpcAddFlow;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxAugMatchRpcRemoveFlow;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxAugMatchRpcUpdateFlowOriginal;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxAugMatchRpcUpdateFlowUpdated;
-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.TopologyId;
-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.yangtools.yang.binding.Augmentation;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * This class contains various utility methods used in netvirt integration tests (IT).
- */
-public class NetvirtItUtils {
- private static final Logger LOG = LoggerFactory.getLogger(NetvirtItUtils.class);
- MdsalUtils mdsalUtils;
- SouthboundUtils southboundUtils;
- DataBroker dataBroker;
-
- private final static Class[] MATCH_AUGMENTATIONS = {GeneralAugMatchNodesNodeTableFlow.class,
- GeneralAugMatchNotifUpdateFlowStats.class,
- GeneralAugMatchNotifPacketIn.class,
- GeneralAugMatchNotifSwitchFlowRemoved.class,
- GeneralAugMatchRpcAddFlow.class,
- GeneralAugMatchRpcRemoveFlow.class,
- GeneralAugMatchRpcUpdateFlowOriginal.class,
- GeneralAugMatchRpcUpdateFlowUpdated.class};
-
- private final static Class[] EXT_LIST_AUGMENTATIONS = {NxAugMatchNodesNodeTableFlow.class,
- NxAugMatchNotifUpdateFlowStats.class,
- NxAugMatchNotifPacketIn.class,
- NxAugMatchNotifSwitchFlowRemoved.class,
- NxAugMatchRpcAddFlow.class,
- NxAugMatchRpcRemoveFlow.class,
- NxAugMatchRpcUpdateFlowOriginal.class,
- NxAugMatchRpcUpdateFlowUpdated.class};
-
- private static Integer DEFAULT_PRIORITY = 32768;
-
- /**
- * Create a new NetvirtItUtils instance.
- * @param dataBroker md-sal data broker
- */
- public NetvirtItUtils(DataBroker dataBroker) {
- this.dataBroker = dataBroker;
- mdsalUtils = new MdsalUtils(dataBroker);
- southboundUtils = new SouthboundUtils(mdsalUtils);
- }
-
- /**
- * Check that the netvirt topology is in the operational mdsal.
- * @return true if the netvirt topology was successfully retrieved
- */
- public Boolean getNetvirtTopology() {
- LOG.info("getNetvirtTopology: looking for {}...", ItConstants.NETVIRT_TOPOLOGY_ID);
- final TopologyId topologyId = new TopologyId(new Uri(ItConstants.NETVIRT_TOPOLOGY_ID));
- InstanceIdentifier<Topology> path =
- InstanceIdentifier.create(NetworkTopology.class).child(Topology.class, new TopologyKey(topologyId));
- NotifyingDataChangeListener waitForIt = new NotifyingDataChangeListener(LogicalDatastoreType.OPERATIONAL,
- path, null);
- waitForIt.registerDataChangeListener(dataBroker);
- try {
- waitForIt.waitForCreation(60 * 1000);
- } catch (InterruptedException e) {
- LOG.info("getNetvirtTopology: InterruptedException while wait(ing)ForCreation");
- }
-
- boolean found = null != mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, path);
-
- LOG.info("getNetvirtTopology: found {} == {}", ItConstants.NETVIRT_TOPOLOGY_ID, found);
-
- return found;
- }
-
- private static final int FLOW_WAIT = 30 * 1000;
-
- /**
- * Verify <strong>by flow id</strong> that the given flow was installed in a table. This method will wait 10
- * seconds for the flows to appear in each of the md-sal CONFIGURATION and OPERATIONAL data stores
- * @param datapathId dpid where flow is installed
- * @param flowId The "name" of the flow, e.g., "TunnelFloodOut_100"
- * @param table integer value of table
- * @throws InterruptedException if interrupted while waiting for flow to appear in mdsal
- */
- public void verifyFlow(long datapathId, String flowId, short table) throws Exception {
- org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder nodeBuilder =
- FlowUtils.createNodeBuilder(datapathId);
- FlowBuilder flowBuilder =
- FlowUtils.initFlowBuilder(new FlowBuilder(), flowId, table);
-
- InstanceIdentifier<Flow> iid = FlowUtils.createFlowPath(flowBuilder, nodeBuilder);
-
- NotifyingDataChangeListener waitForIt = new NotifyingDataChangeListener(LogicalDatastoreType.CONFIGURATION,
- NotifyingDataChangeListener.BIT_CREATE, iid, null);
- waitForIt.registerDataChangeListener(dataBroker);
- waitForIt.waitForCreation(FLOW_WAIT);
-
- Flow flow = FlowUtils.getFlow(flowBuilder, nodeBuilder,
- dataBroker.newReadOnlyTransaction(), LogicalDatastoreType.CONFIGURATION);
- assertNotNull("Could not find flow in config: " + flowBuilder.build() + "--" + nodeBuilder.build(), flow);
-
- waitForIt.close();
- waitForIt = new NotifyingDataChangeListener(LogicalDatastoreType.OPERATIONAL,
- NotifyingDataChangeListener.BIT_CREATE, iid, null);
- waitForIt.registerDataChangeListener(dataBroker);
- waitForIt.waitForCreation(FLOW_WAIT);
-
- flow = FlowUtils.getFlow(flowBuilder, nodeBuilder,
- dataBroker.newReadOnlyTransaction(), LogicalDatastoreType.OPERATIONAL);
- assertNotNull("Could not find flow in operational: " + flowBuilder.build() + "--" + nodeBuilder.build(),
- flow);
- waitForIt.close();
- }
-
- /*public void verifyFlowByFields(long datapathId, String flowId, short tableId, int waitFor)
- throws Exception {
- verifyFlow(datapathId, flowId, tableId);
- }*/
-
- /**
- * Verify that a flow in CONFIGURATION exists also in OPERATIONAL. This is done by looking up the flow in
- * CONFIGURATION by flowId and searching the flow's priority and matches in the OPERATIONAL.
- * @param datapathId dpid where flow is installed
- * @param flowId The "name" of the flow, e.g., "TunnelFloodOut_100"
- * @param tableId integer value of table
- * @param waitFor Retry every second for waitFor milliseconds
- * @throws InterruptedException if interrupted while waiting for flow to appear in mdsal
- */
- public void verifyFlowByFields(long datapathId, String flowId, short tableId, int waitFor) throws Exception {
- long start = System.currentTimeMillis();
- do {
- try {
- verifyFlowByFields(datapathId, flowId, tableId);
- return;
- } catch (AssertionError e) {
- if((System.currentTimeMillis() - start) >= waitFor) {
- throw e;
- }
- Thread.sleep(1000);
- }
- } while (true);
- }
-
- /**
- * Verify that a flow in CONFIGURATION exists also in OPERATIONAL. This is done by looking up the flow in
- * CONFIGURATION by flowId and searching the flow's priority and matches in the OPERATIONAL.
- * @param datapathId dpid where flow is installed
- * @param flowId The "name" of the flow, e.g., "TunnelFloodOut_100"
- * @param tableId integer value of table
- * @throws InterruptedException if interrupted while waiting for flow to appear in mdsal
- */
- public void verifyFlowByFields(long datapathId, String flowId, short tableId) throws Exception {
- org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder nodeBuilder =
- FlowUtils.createNodeBuilder(datapathId);
- FlowBuilder flowBuilder =
- FlowUtils.initFlowBuilder(new FlowBuilder(), flowId, tableId);
-
- InstanceIdentifier<Flow> iid = FlowUtils.createFlowPath(flowBuilder, nodeBuilder);
-
- NotifyingDataChangeListener waitForIt = new NotifyingDataChangeListener(LogicalDatastoreType.CONFIGURATION,
- NotifyingDataChangeListener.BIT_CREATE, iid, null);
- waitForIt.registerDataChangeListener(dataBroker);
- waitForIt.waitForCreation(10000);
-
- Flow configFlow = FlowUtils.getFlow(flowBuilder, nodeBuilder,
- dataBroker.newReadOnlyTransaction(), LogicalDatastoreType.CONFIGURATION);
- assertNotNull("Could not read flow " + flowId + " from configuration", configFlow);
-
- LOG.info("verifyFlowByFields: flowId:{} configFlow:{}", flowId, configFlow);
- waitForIt.close();
- Table table = FlowUtils.getTable(nodeBuilder, tableId, dataBroker.newReadOnlyTransaction(),
- LogicalDatastoreType.OPERATIONAL);
- assertNotNull("Could not read table " + tableId + " from operational", table);
-
- List<Flow> flows = table.getFlow();
- LOG.info("verifyFlowByFields: tableId:{} operatioanlFlows:{}", tableId, flows);
- Assert.assertNotNull("No flows found for table", flows);
-
- for (Flow opFlow : flows) {
- if (checkFlowsEqual(configFlow, opFlow)) {
- return;
- }
- }
- Assert.fail("Could not find matching flow in operational for " + flowId);
- }
-
- private boolean checkFlowsEqual(Flow configFlow, Flow opFlow) {
- Integer configPrio = configFlow.getPriority();
- Integer opPrio = opFlow.getPriority();
- LOG.info("checkFlowsEqual-Priority: ConfigPriority:{} OperationalPriority:{}", configPrio, opPrio);
- if (!Objects.equals(configPrio == null ? DEFAULT_PRIORITY : configPrio,
- opPrio == null ? DEFAULT_PRIORITY : opPrio)) {
- return false;
- }
- LOG.info("checkFlowsEqual-MatchesEquals: Config:{} operational:{}", configFlow.getMatch(), opFlow.getMatch());
- return areMatchesEqual(configFlow.getMatch(), opFlow.getMatch());
- }
-
- private boolean areMatchesEqual(Match m1, Match m2) {
- if (m1 == null && m2 == null) {
- return true;
- }
-
- if (m1 == null || m2 == null) {
- return false;
- }
-
- if (!Objects.equals(m1.getInPort(), m2.getInPort())) { return false; }
- if (!Objects.equals(m1.getInPhyPort(), m2.getInPhyPort())) { return false; }
- if (!Objects.equals(m1.getMetadata(), m2.getMetadata())) { return false; }
- if (!Objects.equals(m1.getTunnel(), m2.getTunnel())) { return false; }
- if (!Objects.equals(m1.getEthernetMatch(), m2.getEthernetMatch())) { return false; }
- if (!Objects.equals(m1.getVlanMatch(), m2.getVlanMatch())) { return false; }
- if (!Objects.equals(m1.getIpMatch(), m2.getIpMatch())) { return false; }
- if (!Objects.equals(m1.getLayer3Match(), m2.getLayer3Match())) { return false; }
- if (!Objects.equals(m1.getLayer4Match(), m2.getLayer4Match())) { return false; }
- if (!Objects.equals(m1.getIcmpv4Match(), m2.getIcmpv4Match())) { return false; }
- if (!Objects.equals(m1.getIcmpv6Match(), m2.getIcmpv6Match())) { return false; }
- if (!Objects.equals(m1.getProtocolMatchFields(), m2.getProtocolMatchFields())) { return false; }
- if (!Objects.equals(m1.getTcpFlagsMatch(), m2.getTcpFlagsMatch())) { return false; }
-
- MatchAugmentationIterator it = new MatchAugmentationIterator(m1);
- List<AllMatchesGrouping> side1Matches = new ArrayList<>();
- AllMatchesGrouping aug;
- while (null != (aug = it.next())) {
- side1Matches.add(aug);
- }
-
- it = new MatchAugmentationIterator(m2);
- while(null != (aug = it.next())) {
- if (!isMatchInList(aug, side1Matches)) {
- return false;
- }
- }
-
- return true;
- }
-
- private boolean isMatchInList(AllMatchesGrouping match, List<AllMatchesGrouping> matchList) {
- for (AllMatchesGrouping match2 : matchList) {
- if (areMatchAugmentationsEqual(match, match2)) {
- return true;
- }
- }
-
- return false;
- }
-
- class MatchAugmentationIterator {
-
- Match myMatch;
-
- public MatchAugmentationIterator(Match match) {
- this.myMatch = match;
- }
-
- private int matchAugmentationIdx = 0;
- private int extListListIdx = 0;
- private int extListAugmentationIdx = 0;
-
- public AllMatchesGrouping next() {
-
- while (matchAugmentationIdx < MATCH_AUGMENTATIONS.length) {
- GeneralExtensionListGrouping extensionListGrouping = (GeneralExtensionListGrouping)
- myMatch.getAugmentation(MATCH_AUGMENTATIONS[matchAugmentationIdx]);
-
- if (null != extensionListGrouping) {
- List<ExtensionList> extListList = extensionListGrouping.getExtensionList();
-
- while (extListListIdx < extListList.size()) {
-
- ExtensionList extList = extListList.get(extListListIdx);
-
- while(extListAugmentationIdx < EXT_LIST_AUGMENTATIONS.length) {
- Augmentation res = extList.getExtension().getAugmentation(
- EXT_LIST_AUGMENTATIONS[extListAugmentationIdx]);
- ++extListAugmentationIdx;
- if (res != null) {
- return (AllMatchesGrouping) res;
- }
- }
- extListAugmentationIdx = 0;
- ++extListListIdx;
- }
- extListListIdx = 0;
- }
- ++matchAugmentationIdx;
-
- }
-
- return null;
- }
-
- }
-
- private boolean areMatchAugmentationsEqual(AllMatchesGrouping obj1, AllMatchesGrouping obj2) {
- if (obj1 == null && obj2 == null) {
- return true;
- }
-
- if (obj1 == null || obj2 == null) {
- return false;
- }
- if (!Objects.equals(obj1.getNxmOfEthSrc(), obj2.getNxmOfEthSrc())) { return false; }
- if (!Objects.equals(obj1.getNxmOfArpOp(), obj2.getNxmOfArpOp())) { return false; }
- if (!Objects.equals(obj1.getNxmOfUdpDst(), obj2.getNxmOfUdpDst())) { return false; }
- if (!Objects.equals(obj1.getNxmNxNshc3(), obj2.getNxmNxNshc3())) { return false; }
- if (!Objects.equals(obj1.getNxmNxCtZone(), obj2.getNxmNxCtZone())) { return false; }
- if (!Objects.equals(obj1.getNxmNxArpSha(), obj2.getNxmNxArpSha())) { return false; }
- if (!Objects.equals(obj1.getNxmOfIcmpType(), obj2.getNxmOfIcmpType())) { return false; }
- if (!Objects.equals(obj1.getNxmNxNshc1(), obj2.getNxmNxNshc1())) { return false; }
- if (!Objects.equals(obj1.getNxmOfArpSpa(), obj2.getNxmOfArpSpa())) { return false; }
- if (!Objects.equals(obj1.getNxmNxTunIpv4Dst(), obj2.getNxmNxTunIpv4Dst())) { return false; }
- if (!Objects.equals(obj1.getNxmOfTcpSrc(), obj2.getNxmOfTcpSrc())) { return false; }
- if (!Objects.equals(obj1.getNxmNxNshc4(), obj2.getNxmNxNshc4())) { return false; }
- if (!Objects.equals(obj1.getNxmOfArpTpa(), obj2.getNxmOfArpTpa())) { return false; }
- if (!Objects.equals(obj1.getNxmOfTcpDst(), obj2.getNxmOfTcpDst())) { return false; }
- if (!Objects.equals(obj1.getNxmNxNsi(), obj2.getNxmNxNsi())) { return false; }
- if (!Objects.equals(obj1.getNxmNxNshc2(), obj2.getNxmNxNshc2())) { return false; }
- if (!Objects.equals(obj1.getNxmNxArpTha(), obj2.getNxmNxArpTha())) { return false; }
- if (!Objects.equals(obj1.getNxmNxReg(), obj2.getNxmNxReg())) { return false; }
- if (!Objects.equals(obj1.getNxmOfIpSrc(), obj2.getNxmOfIpSrc())) { return false; }
- if (!Objects.equals(obj1.getNxmOfEthType(), obj2.getNxmOfEthType())) { return false; }
- if (!Objects.equals(obj1.getNxmOfEthDst(), obj2.getNxmOfEthDst())) { return false; }
- if (!Objects.equals(obj1.getNxmOfUdpSrc(), obj2.getNxmOfUdpSrc())) { return false; }
- if (!Objects.equals(obj1.getNxmNxCtState(), obj2.getNxmNxCtState())) { return false; }
- if (!Objects.equals(obj1.getNxmNxTunIpv4Src(), obj2.getNxmNxTunIpv4Src())) { return false; }
- if (!Objects.equals(obj1.getNxmOfIpDst(), obj2.getNxmOfIpDst())) { return false; }
- if (!Objects.equals(obj1.getNxmNxNsp(), obj2.getNxmNxNsp())) { return false; }
-
- return true;
- }
-
- /**
- * Log the flows in a given table.
- * @param datapathId dpid
- * @param tableNum table number
- * @param store configuration or operational
- */
- public void logFlows(long datapathId, short tableNum, LogicalDatastoreType store) {
- org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder nodeBuilder =
- FlowUtils.createNodeBuilder(datapathId);
- Table table = FlowUtils.getTable(nodeBuilder, tableNum, dataBroker.newReadOnlyTransaction(), store);
- if (table == null) {
- LOG.info("logFlows: Could not find table {} in {}", tableNum, store);
- }
- //TBD: Log table and store in one line, flows in following lines
- for (Flow flow : table.getFlow()) {
- LOG.info("logFlows: table {} flow {} in {}", tableNum, flow.getFlowName(), store);
- }
- }
-
- /**
- * Log the flows in a given table.
- * @param datapathId dpid
- * @param table table number
- */
- public void logFlows(long datapathId, short table) {
- logFlows(datapathId, table, LogicalDatastoreType.CONFIGURATION);
- }
-
- /**
- * Get a DataBroker and assert that it is not null.
- * @param providerContext ProviderContext from which to retrieve the DataBroker
- * @return the Databroker
- */
- public static DataBroker getDatabroker(BindingAwareBroker.ProviderContext providerContext) {
- DataBroker dataBroker = providerContext.getSALService(DataBroker.class);
- assertNotNull("dataBroker should not be null", dataBroker);
- return dataBroker;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.utils.netvirt.it.utils;
-
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.UUID;
-import org.junit.Assert;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityGroup;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSubnet;
-import org.opendaylight.netvirt.utils.neutron.utils.NeutronUtils;
-import org.opendaylight.ovsdb.utils.southbound.utils.SouthboundUtils;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-
-/**
- * A utility class used in integration tests that need to create neutron networks with some ports.
- * Please see NetvirtIT#testNeutronNet for an example of how this class is used
- */
-public class NeutronNetItUtil {
-
- public final String tenantId;
- public final String id;
- public final String subnetId;
- public NeutronNetwork neutronNetwork;
- public NeutronSubnet neutronSubnet;
- public String segId = "100";
- public String macPfx;
- public String ipPfx;
- public String cidr;
-
- public SouthboundUtils southboundUtils;
- public NeutronUtils neutronUtils;
-
- /**
- * Information about a port created using createPort() - fields should be pretty self explanatory
- */
- public class PortInfo {
- public PortInfo(String name, long ofPort) {
- this.name = name;
- this.ofPort = ofPort;
- this.ip = ipFor(ofPort);
- this.mac = macFor(ofPort);
- }
-
- public String name;
- public NeutronPort neutronPort;
- public String ip;
- public String mac;
- public long ofPort;
- }
-
- /**
- * Maps port names (the ones you pass in to createPort() to their PortInfo objects
- */
- public Map<String, PortInfo> portInfoByName = new HashMap<>();
-
- /**
- * Construct a new NeutronNetItUtil.
- * @param southboundUtils used to create termination points
- * @param tenantId tenant ID
- */
- public NeutronNetItUtil(SouthboundUtils southboundUtils, String tenantId) {
- this(southboundUtils, tenantId, "101", "f4:00:00:0f:00:", "10.0.0.", "10.0.0.0/24");
- }
-
- /**
- * Construct a new NeutronNetItUtil.
- * @param southboundUtils used to create termination points
- * @param tenantId tenant ID
- * @param segId the segmentation id to use for the neutron network
- * @param macPfx the first characters of the mac addresses generated for ports. Format is "f7:00:00:0f:00:"
- * @param ipPfx the first characters of the ip addresses generated for ports. Format is "10.0.0."
- * @param cidr the cidr for this network, e.g., "10.0.0.0/24"
- */
- public NeutronNetItUtil(SouthboundUtils southboundUtils, String tenantId,
- String segId, String macPfx, String ipPfx, String cidr) {
- this.tenantId = tenantId;
- this.segId = segId;
- this.macPfx = macPfx;
- this.ipPfx = ipPfx;
- this.cidr = cidr;
-
- this.id = UUID.randomUUID().toString();
- this.subnetId = UUID.randomUUID().toString();
-
- this.southboundUtils = southboundUtils;
- neutronUtils = new NeutronUtils();
- neutronNetwork = null;
- neutronSubnet = null;
- }
-
- /**
- * Create the network and subnet.
- */
- public void create() {
- neutronNetwork = neutronUtils.createNeutronNetwork(id, tenantId, "vxlan", segId);
- neutronSubnet = neutronUtils.createNeutronSubnet(subnetId, tenantId, id, "10.0.0.0/24");
- }
-
- /**
- * Clean up all created neutron objects.
- */
- public void destroy() {
- for (PortInfo portInfo : portInfoByName.values()) {
- neutronUtils.removeNeutronPort(portInfo.neutronPort.getID());
- }
- //TODO: probably more polite to clean up everything else as well...
- //TODO: for now just assume that the docker image will be recreated
- //TODO: before each test
- portInfoByName.clear();
-
- if (neutronSubnet != null) {
- neutronUtils.removeNeutronSubnet(neutronSubnet.getID());
- neutronSubnet = null;
- }
-
- if (neutronNetwork != null) {
- neutronUtils.removeNeutronNetwork(neutronNetwork.getID());
- neutronNetwork = null;
- }
- }
-
- /**
- * Create a port on the network. The deviceOwner will be set to "compute:None".
- * @param bridge bridge where the port will be created on OVS
- * @param portName name for this port
- * @throws InterruptedException if we're interrupted while waiting for objects to be created
- */
- public void createPort(Node bridge, String portName) throws InterruptedException, IOException {
- createPort(bridge, portName, "compute:None");
- }
-
- /**
- * Create a port on the network. The deviceOwner will be set to "compute:None".
- * @param bridge bridge where the port will be created on OVS
- * @param portName name for this port
- * @param owner deviceOwner, e.g., "network:dhcp"
- * @param secGroups Optional NeutronSecurityGroup objects see NeutronUtils.createNeutronSecurityGroup()
- * @throws InterruptedException if we're interrupted while waiting for objects to be created
- */
- public void createPort(Node bridge, String portName, String owner, NeutronSecurityGroup... secGroups)
- throws InterruptedException, IOException {
- PortInfo portInfo = buildPortInfo(portName);
- doCreatePort(bridge, portInfo, owner, "internal", secGroups);
- }
-
- protected PortInfo buildPortInfo(String portName) {
- Assert.assertFalse("Can't have two ports with the same name", portInfoByName.containsKey(portName));
-
- long idx = portInfoByName.size() + 1;
- Assert.assertTrue(idx < 256);
- return new PortInfo(portName, idx);
- }
-
- protected void doCreatePort(Node bridge, PortInfo portInfo, String owner,
- String portType, NeutronSecurityGroup ... secGroups) throws InterruptedException {
-
- String portId = UUID.randomUUID().toString();
- portInfo.neutronPort = neutronUtils.createNeutronPort(
- id, subnetId, portId, owner, portInfo.ip, portInfo.mac, secGroups);
-
- //TBD: Use NotifyingDataChangeListener
- Thread.sleep(1000);
-
- Map<String, String> externalIds = new HashMap<>();
- externalIds.put("attached-mac", portInfo.mac);
- externalIds.put("iface-id", portId);
- southboundUtils.addTerminationPoint(bridge, portInfo.name, portType, null, externalIds, portInfo.ofPort);
-
- portInfoByName.put(portInfo.name, portInfo);
- }
-
- /**
- * Get the mac address for the n'th port created on this network (starts at 1).
- * @param portNum index of port created
- * @return the mac address
- */
- public String macFor(long portNum) {
- return macPfx + String.format("%02x", 5 - portNum);
- }
-
- /**
- * Get the ip address for the n'th port created on this network (starts at 1).
- * @param portNum index of port created
- * @return the mac address
- */
- public String ipFor(long portNum) {
- return ipPfx + portNum;
- }
-}
-
+++ /dev/null
-/*
- * Copyright (c) 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.utils.netvirt.it.utils;
-
-import org.junit.Assert;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityGroup;
-import org.opendaylight.ovsdb.utils.ovsdb.it.utils.DockerOvs;
-import org.opendaylight.ovsdb.utils.southbound.utils.SouthboundUtils;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-
-import java.io.IOException;
-
-/**
- * This class adds the ability to issue pings from one port to another to its base class, NeutronNetItUtil.
- * Please see NetvirtIT#testNeutronNet for an example of how this class is used
- * N.B. At this point this class only supports DockerOvs runs where the docker-compose file runs a single
- * docker container with OVS. A little work will need to be invested to extend this functionality to support
- * configuring "ping-ability" on multiple docker containers.
- */
-public class PingableNeutronNetItUtil extends NeutronNetItUtil {
-
- private static final int DEFAULT_WAIT = 30 * 1000;
- private DockerOvs dockerOvs;
- private final Boolean isUserSpace;
-
- public PingableNeutronNetItUtil(DockerOvs dockerOvs, SouthboundUtils southboundUtils, String tenantId,
- Boolean isUserSpace) {
- super(southboundUtils, tenantId);
- this.dockerOvs = dockerOvs;
- this.isUserSpace = isUserSpace;
- }
-
- public PingableNeutronNetItUtil(DockerOvs dockerOvs, SouthboundUtils southboundUtils, String tenantId,
- String segId, String macPfx, String ipPfx, String cidr, Boolean isUserSpace) {
- super(southboundUtils, tenantId, segId, macPfx, ipPfx, cidr);
- this.dockerOvs = dockerOvs;
- this.isUserSpace = isUserSpace;
- }
-
- /**
- * Create a port on the network. The deviceOwner will be set to "compute:None".
- * @param bridge bridge where the port will be created on OVS
- * @param portName name for this port
- * @param owner deviceOwner, e.g., "network:dhcp"
- * @param secGroups Optional NeutronSecurityGroup objects see NeutronUtils.createNeutronSecurityGroup()
- * @throws InterruptedException if we're interrupted while waiting for objects to be created
- */
- public void createPort(Node bridge, String portName, String owner, NeutronSecurityGroup... secGroups)
- throws InterruptedException, IOException {
- if (dockerOvs.usingExternalDocker()) {
- super.createPort(bridge, portName, owner, secGroups);
- return;
- }
-
- PortInfo portInfo = buildPortInfo(portName);
-
- if (isUserSpace) {
- dockerOvs.runInContainer(DEFAULT_WAIT, 0, "ip", "tuntap", "add", portInfo.name, "mode", "tap");
- dockerOvs.runInContainer(DEFAULT_WAIT, 0, "ip", "link", "set", "dev",
- portInfo.name, "address", portInfo.mac);
-
- doCreatePort(bridge, portInfo, owner, "tap", secGroups);
- } else {
- doCreatePort(bridge, portInfo, owner, "internal", secGroups);
- dockerOvs.runInContainer(DEFAULT_WAIT, 0, "ip", "link", "set", "dev",
- portInfo.name, "address", portInfo.mac);
- }
- }
-
- /**
- * This method must be run on a port before calling ping() or pingIp()
- * @param portName The name of the port used when it was created using createPort()
- * @throws IOException if an IO error occurs with one of the spawned procs
- * @throws InterruptedException because we sleep
- */
- public void preparePortForPing(String portName) throws IOException, InterruptedException {
- if (dockerOvs.usingExternalDocker()) {
- return;
- }
-
- String nsName = "ns-" + portName;
-
- PortInfo portInfo = portInfoByName.get(portName);
- Assert.assertNotNull(portInfo);
- dockerOvs.runInContainer(DEFAULT_WAIT, 0, "ip", "netns", "add", nsName);
- dockerOvs.runInContainer(DEFAULT_WAIT, 0, "ip", "link", "set", portName, "netns", nsName);
- dockerOvs.runInContainer(DEFAULT_WAIT, 0, "ip", "netns", "exec", nsName, "ip", "addr",
- "add", "dev", portName, portInfo.ip + "/24");
- dockerOvs.runInContainer(DEFAULT_WAIT, 0, "ip", "netns", "exec", nsName, "ip", "link",
- "set", "dev", "lo", "up");
- dockerOvs.runInContainer(DEFAULT_WAIT, 0, "ip", "netns", "exec", nsName, "ip", "link",
- "set", "dev", portName, "up");
- dockerOvs.runInContainer(DEFAULT_WAIT, 0, "ip", "netns", "exec", nsName, "ip", "route",
- "add", "default", "via", portInfo.ip);
- }
-
- /**
- * Ping from one port to the other
- * @param fromPort name of the port to ping from. This is the name you used for createPort.
- * @param toPort name of the port to ping to. This is the name you used for createPort.
- * @throws IOException if an IO error occurs with one of the spawned procs
- * @throws InterruptedException because we sleep
- */
- public void ping(String fromPort, String toPort) throws IOException, InterruptedException {
- if (dockerOvs.usingExternalDocker()) {
- return;
- }
-
- PortInfo portInfo = portInfoByName.get(toPort);
- Assert.assertNotNull(portInfo);
- pingIp(fromPort, portInfo.ip);
- }
-
- /**
- * Ping from one port to an IP address
- * @param fromPort name of the port to ping from. This is the name you used for createPort.
- * @param ip The IP address to ping
- * @throws IOException if an IO error occurs with one of the spawned procs
- * @throws InterruptedException because we sleep
- */
- public void pingIp(String fromPort, String ip) throws IOException, InterruptedException {
- if (dockerOvs.usingExternalDocker()) {
- return;
- }
-
- String fromNs = "ns-" + fromPort;
- dockerOvs.runInContainer(0, DEFAULT_WAIT, 0, "ip", "netns", "exec", fromNs, "ping", "-c", "4", ip);
- }
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-Copyright (C) 2015 Red Hat, Inc. and others. All rights reserved.
-
-This program and the accompanying materials are made available under the
-terms of the Eclipse Public License v1.0 which accompanies this distribution,
-and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-parent</artifactId>
- <version>0.7.0-SNAPSHOT</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>utils.neutron-utils</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <packaging>bundle</packaging>
-
- <properties>
- <neutron.version>0.9.0-SNAPSHOT</neutron.version>
- </properties>
-
- <dependencies>
- <!-- project specific dependencies -->
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>utils.mdsal-utils</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>utils.servicehelper</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>openstack.net-virt</artifactId>
- <version>${project.version}</version>
- </dependency>
- <!-- neutron dependencies -->
- <dependency>
- <groupId>org.opendaylight.neutron</groupId>
- <artifactId>model</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- </dependency>
- </dependencies>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-/*
- * Copyright © 2016 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.utils.neutron.utils;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.UUID;
-
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityGroup;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityRule;
-import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSubnet;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronNetworkCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronPortCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSecurityGroupCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSecurityRuleCRUD;
-import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSubnetCRUD;
-import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper;
-
-public class NeutronUtils {
- public NeutronPort createNeutronPort(String networkId, String subnetId,
- String id, String owner, String ipaddr, String mac, NeutronSecurityGroup... secGroups) {
- INeutronPortCRUD iNeutronPortCRUD =
- (INeutronPortCRUD) ServiceHelper.getGlobalInstance(INeutronPortCRUD.class, this);
- NeutronPort np = new NeutronPort();
- np.initDefaults();
- np.setID(id);
- np.setDeviceOwner(owner);
- np.setMacAddress(mac);
- np.setNetworkUUID(networkId);
- List<org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs> srcAddressList =
- new ArrayList<>();
- org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs nip = new org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs();
- nip.setIpAddress(ipaddr);
- nip.setSubnetUUID(subnetId);
- srcAddressList.add(nip);
- np.setFixedIPs(srcAddressList);
- List<NeutronSecurityGroup> nsgs = Arrays.asList(secGroups);
- np.setSecurityGroups(nsgs);
- iNeutronPortCRUD.addPort(np);
- return np;
- }
-
- public boolean removeNeutronPort(String uuid) {
- INeutronPortCRUD iNeutronPortCRUD =
- (INeutronPortCRUD) ServiceHelper.getGlobalInstance(INeutronPortCRUD.class, this);
- return iNeutronPortCRUD.removePort(uuid);
- }
-
- public NeutronSubnet createNeutronSubnet(String subnetId, String tenantId,
- String networkId, String cidr) {
- INeutronSubnetCRUD iNeutronSubnetCRUD =
- (INeutronSubnetCRUD) ServiceHelper.getGlobalInstance(INeutronSubnetCRUD.class, this);
- NeutronSubnet ns = new NeutronSubnet();
- ns.setID(subnetId);
- ns.setCidr(cidr);
- ns.initDefaults();
- ns.setNetworkUUID(networkId);
- ns.setTenantID(tenantId);
- iNeutronSubnetCRUD.addSubnet(ns);
- return ns;
- }
-
- public boolean removeNeutronSubnet(String uuid) {
- INeutronSubnetCRUD iNeutronSubnetCRUD =
- (INeutronSubnetCRUD) ServiceHelper.getGlobalInstance(INeutronSubnetCRUD.class, this);
- return iNeutronSubnetCRUD.removeSubnet(uuid);
- }
-
- public NeutronNetwork createNeutronNetwork(String uuid, String tenantID, String networkTypeVxlan, String segId) {
- INeutronNetworkCRUD iNeutronNetworkCRUD =
- (INeutronNetworkCRUD) ServiceHelper.getGlobalInstance(INeutronNetworkCRUD.class, this);
- NeutronNetwork nn = new NeutronNetwork();
- nn.setID(uuid);
- nn.initDefaults();
- nn.setTenantID(tenantID);
- nn.setProviderNetworkType(networkTypeVxlan);
- nn.setProviderSegmentationID(segId);
- iNeutronNetworkCRUD.addNetwork(nn);
- return nn;
- }
-
- public boolean removeNeutronNetwork(String uuid) {
- INeutronNetworkCRUD iNeutronNetworkCRUD =
- (INeutronNetworkCRUD) ServiceHelper.getGlobalInstance(INeutronNetworkCRUD.class, this);
- return iNeutronNetworkCRUD.removeNetwork(uuid);
-
- }
-
- /**
- * Build a NeutronSecurityRule that can be passed in to createNeutronSecurityGroup.
- * @param direction e.g., "ingress". May be null.
- * @param ethertype e.g., "IPv4". May be null.
- * @param protocol e.g., "TCP". May be null.
- * @param ipPrefix e.g., "10.9.8.0/24". May be null.
- * @param portMin or null
- * @param portMax or null
- * @return A new NeutronSecurityRule
- */
- public NeutronSecurityRule buildNeutronSecurityRule(String direction, String ethertype, String protocol,
- String ipPrefix, Integer portMin, Integer portMax) {
- NeutronSecurityRule rule = new NeutronSecurityRule();
- rule.setID(UUID.randomUUID().toString());
- rule.setSecurityRemoteGroupID(null);
- rule.setSecurityRuleDirection(direction);
- rule.setSecurityRuleEthertype(ethertype);
- rule.setSecurityRuleProtocol(protocol);
- rule.setSecurityRuleRemoteIpPrefix(ipPrefix);
- rule.setSecurityRulePortMin(portMin);
- rule.setSecurityRulePortMax(portMax);
-
- return rule;
- }
-
- /**
- * Create a new NeutronSecurityGroup and create the NeutronSecurityRules passed in. This method will first create
- * teh NeutronSecurityRules and then the NeutronSecurityGroup in md-sal.
- * @param tenantId The tenant ID for both the rules and groups
- * @param rules NeutronSecurityRules. You can create them with buildNeutronSecurityRule.
- * @return A new NeutronSecurityGroup
- */
- public NeutronSecurityGroup createNeutronSecurityGroup(String tenantId, NeutronSecurityRule... rules) {
- INeutronSecurityGroupCRUD groupCRUD =
- (INeutronSecurityGroupCRUD) ServiceHelper.getGlobalInstance(INeutronSecurityGroupCRUD.class, this);
- INeutronSecurityRuleCRUD ruleCRUD =
- (INeutronSecurityRuleCRUD) ServiceHelper.getGlobalInstance(INeutronSecurityRuleCRUD.class, this);
-
- String id = UUID.randomUUID().toString();
- NeutronSecurityGroup sg = new NeutronSecurityGroup();
- sg.setSecurityGroupName("SG-" + id);
- sg.setID(id);
- sg.setSecurityGroupTenantID(tenantId);
-
- List<NeutronSecurityRule> ruleList = new ArrayList<>(rules.length);
- for (NeutronSecurityRule rule : rules) {
- rule.setSecurityRuleTenantID(tenantId);
- rule.setSecurityRuleGroupID(id);
- ruleList.add(rule);
- ruleCRUD.addNeutronSecurityRule(rule);
- }
-
- groupCRUD.addNeutronSecurityGroup(sg);
-
- return sg;
- }
-
- /**
- * Remove the NeutronSecurityGroup and its associated NeutronSecurityRules from md-sal
- * @param sg NeutronSecurityGroup to remove
- */
- public void removeNeutronSecurityGroupAndRules(NeutronSecurityGroup sg) {
- INeutronSecurityGroupCRUD groupCRUD =
- (INeutronSecurityGroupCRUD) ServiceHelper.getGlobalInstance(INeutronSecurityGroupCRUD.class, this);
-
- groupCRUD.removeNeutronSecurityGroup(sg.getID());
- }
-
- /**
- * Get the NeutronSecurityRule and its associated NeutronSecurityGroup
- * @param sg NeutronSecurityGroup to to get the rules for
- * @return List of NeutronSecurityRule
- */
- public List<NeutronSecurityRule> getNeutronSecurityGroupRules(NeutronSecurityGroup sg) {
- INeutronSecurityRuleCRUD ruleCRUD =
- (INeutronSecurityRuleCRUD) ServiceHelper.getGlobalInstance(INeutronSecurityRuleCRUD.class, this);
-
- List<NeutronSecurityRule> rules = new ArrayList<>();
- List<NeutronSecurityRule> securityRules = ruleCRUD.getAllNeutronSecurityRules();
- for (NeutronSecurityRule securityRule : securityRules) {
- if (sg.getID().equals(securityRule.getSecurityRuleGroupID())) {
- rules.add(securityRule);
- }
- }
- return rules;
- }
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-Copyright (C) 2015 Red Hat, Inc. and others. All rights reserved.
-
-This program and the accompanying materials are made available under the
-terms of the Eclipse Public License v1.0 which accompanies this distribution,
-and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>odlparent-lite</artifactId>
- <version>2.0.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>utils</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <packaging>pom</packaging>
- <description>The OVSDB Plugin integration project is a project for OpenDaylight that will implement the Open vSwitch Database RFC 7047 management protocol allowing the Southbound configuration of vSwitches and a network virtualization implementation.</description>
- <licenses>
- <license>
- <name>Eclipse Public License v1.0</name>
- <url>http://www.eclipse.org/legal/epl-v10.html</url>
- </license>
- </licenses>
- <developers>
- <developer>
- <name>Sam Hague</name>
- <email>shague@gmail.com</email>
- <url>https://github.com/shague</url>
- </developer>
- </developers>
- <scm>
- <connection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</connection>
- <developerConnection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</developerConnection>
- <tag>HEAD</tag>
- <url>https://wiki.opendaylight.org/view/OVSDB_Integration:Main</url>
- </scm>
-
- <modules>
- <module>config</module>
- <module>mdsal-openflow</module>
- <module>mdsal-utils</module>
- <module>netvirt-it-utils</module>
- <module>neutron-utils</module>
- <module>servicehelper</module>
- </modules>
-
-<!-- DO NOT install or deploy the repo root pom as it's only needed to initiate a build -->
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-deploy-plugin</artifactId>
- <configuration>
- <skip>true</skip>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-install-plugin</artifactId>
- <configuration>
- <skip>true</skip>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-Copyright (C) 2015 Red Hat, Inc. and others. All rights reserved.
-
-This program and the accompanying materials are made available under the
-terms of the Eclipse Public License v1.0 which accompanies this distribution,
-and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-parent</artifactId>
- <version>0.7.0-SNAPSHOT</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.netvirt</groupId>
- <artifactId>utils.servicehelper</artifactId>
- <name>ODL :: netvirt :: ${project.artifactId}</name>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>bundle</packaging>
- <description>The OVSDB Plugin integration project is a project for OpenDaylight that will implement the Open vSwitch Database RFC 7047 management protocol allowing the Southbound configuration of vSwitches and a network virtualization implementation.</description>
- <licenses>
- <license>
- <name>Eclipse Public License v1.0</name>
- <url>http://www.eclipse.org/legal/epl-v10.html</url>
- </license>
- </licenses>
- <developers>
- <developer>
- <name>Sam Hague</name>
- <email>shague@gmail.com</email>
- <url>https://github.com/shague</url>
- </developer>
- </developers>
- <scm>
- <connection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</connection>
- <developerConnection>scm:git:ssh://git.opendaylight.org:29418/netvirt.git</developerConnection>
- <tag>HEAD</tag>
- <url>https://wiki.opendaylight.org/view/OVSDB_Integration:Main</url>
- </scm>
-
- <dependencies>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.core</artifactId>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-core</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-api-mockito</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-core</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-module-junit4</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework.osgi</groupId>
- <artifactId>spring-osgi-mock</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-simple</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <extensions>true</extensions>
- <configuration>
- <instructions>
- <Export-Package>
- org.opendaylight.netvirt.utils.servicehelper
- </Export-Package>
- </instructions>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.jacoco</groupId>
- <artifactId>jacoco-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>default-instrument</id>
- <goals>
- <goal>instrument</goal>
- </goals>
- </execution>
- <execution>
- <id>default-restore-instrumented-classes</id>
- <goals>
- <goal>restore-instrumented-classes</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
-
- <!--
- Maven Site Configuration
-
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
-
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
-</project>
+++ /dev/null
-/*
- * Copyright (c) 2013, 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.netvirt.utils.servicehelper;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.osgi.framework.Bundle;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.FrameworkUtil;
-import org.osgi.framework.ServiceReference;
-
-/**
- * The class helps to register and retrieve OSGi service registry
- */
-public final class ServiceHelper {
- private static final Logger LOG = LoggerFactory.getLogger(ServiceHelper.class);
- private static final Map<Class<?>, Object> OVERRIDES = new HashMap<>();
-
- /**
- * Override a global instance. This should generally only be used for testing.
- *
- * @param clazz The target class.
- * @param instance The instance to return for the class.
- */
- public static <T> void overrideGlobalInstance(Class<T> clazz, T instance) {
- ServiceHelper.OVERRIDES.put(clazz, instance);
- }
-
- /**
- * Retrieve global instance of a class via OSGI registry, if
- * there are many only the first is returned.
- *
- * @param clazz The target class
- * @param bundle The caller
- */
- public static Object getGlobalInstance(Class<?> clazz, Object bundle) {
- return getGlobalInstance(clazz, bundle, null);
- }
-
- /**
- * Retrieve global instance of a class via OSGI registry, if
- * there are many only the first is returned. On this version an LDAP
- * type of filter is applied
- *
- * @param clazz The target class
- * @param bundle The caller
- * @param serviceFilter LDAP filter to be applied in the search
- */
- public static Object getGlobalInstance(Class<?> clazz, Object bundle,
- String serviceFilter) {
- if (OVERRIDES.containsKey(clazz)) {
- return OVERRIDES.get(clazz);
- }
- Object[] instances = getGlobalInstances(clazz, bundle, serviceFilter);
- if (instances != null && instances.length > 0) {
- return instances[0];
- }
- return null;
- }
-
- /**
- * Retrieve all the Instances of a Service, optionally
- * filtered via serviceFilter if non-null else all the results are
- * returned if null
- *
- * @param clazz The target class
- * @param bundle The caller
- * @param serviceFilter LDAP filter to be applied in the search
- */
- private static Object[] getGlobalInstances(Class<?> clazz, Object bundle,
- String serviceFilter) {
- Object instances[] = null;
- try {
- Bundle ourBundle = FrameworkUtil.getBundle(bundle.getClass());
- if (ourBundle != null) {
- BundleContext bCtx = ourBundle.getBundleContext();
-
- ServiceReference<?>[] services = bCtx.getServiceReferences(clazz
- .getName(), serviceFilter);
-
- if (services != null) {
- instances = new Object[services.length];
- for (int i = 0; i < services.length; i++) {
- instances[i] = bCtx.getService(services[i]);
- }
- }
- }
- } catch (Exception e) {
- LOG.error("Error retrieving global instances of {} from caller {} with filter {}",
- clazz, bundle, serviceFilter, e);
- }
- return instances;
- }
-}
+++ /dev/null
-/*
- * Copyright (C) 2015 Red Hat, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netvirt.utils.servicehelper;
-
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.mockito.Matchers.any;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.FrameworkUtil;
-import org.powermock.api.mockito.PowerMockito;
-import org.powermock.core.classloader.annotations.PrepareForTest;
-import org.powermock.modules.junit4.PowerMockRunner;
-import org.springframework.osgi.mock.MockBundle;
-
-/**
- * JUnit test for
- * {@link ServiceHelper}
- */
-@RunWith(PowerMockRunner.class)
-@PrepareForTest(FrameworkUtil.class)
-public class ServiceHelperTest {
- @Test
- /**
- * Test method for
- * {@link ServiceHelper#getGlobalInstance(Class, Object)}
- */
- public void getGlobalInstanceTest () {
- Bundle bundle = new MockBundle();
-
- PowerMockito.mockStatic(FrameworkUtil.class);
-
- PowerMockito.when(FrameworkUtil.getBundle(any(Class.class)))
- .thenReturn(null);
- Object object = ServiceHelper.getGlobalInstance(Test.class, this);
- assertNull("Service should be null", object);
-
- PowerMockito.when(FrameworkUtil.getBundle(any(Class.class)))
- .thenReturn(bundle);
- object = ServiceHelper.getGlobalInstance(Test.class, this);
- assertNotNull("Service should not be null", object);
- }
-}