To run the integration tests:
mvn clean install
+ # The first time you need to set everything up
+ fig up -d
+ # Later runs only need the containers to be started
fig start
# OSX
mvn verify -Pintegrationtest -Dovsdbserver.ipaddress=$(boot2docker ip 2>/dev/null) -Dovsdbserver.port=6640
mvn verify -Pintegrationtest -Dovsdbserver.ipaddress=127.0.0.1 -Dovsdbserver.port=6640
fig stop
+On Linux you'll generally need to run fig as root (sudo fig ...).
+
Skipping unit tests and karaf tests
====================
mininet.vm.provider "vmware_fusion" do |vf|
vf.vmx["memsize"] = "2048"
end
+ mininet.vm.provider :libvirt do |lv|
+ lv.memory = 2048
+ end
mininet.vm.provision "puppet" do |puppet|
puppet.hiera_config_path = "resources/puppet/hiera.yaml"
puppet.working_directory = "/vagrant/resources/puppet"
control.vm.provider "vmware_fusion" do |vf|
vf.vmx["memsize"] = "4096"
end
+ control.vm.provider :libvirt do |lv|
+ lv.memory = 4096
+ end
control.vm.provision "puppet" do |puppet|
puppet.hiera_config_path = "resources/puppet/hiera.yaml"
puppet.working_directory = "/vagrant/resources/puppet"
compute.vm.provider "vmware_fusion" do |vf|
vf.vmx["memsize"] = "4096"
end
+ compute.vm.provider :libvirt do |lv|
+ lv.memory = 4096
+ end
compute.vm.provision "puppet" do |puppet|
puppet.hiera_config_path = "resources/puppet/hiera.yaml"
puppet.working_directory = "/vagrant/resources/puppet"
</scm>
<dependencies>
- <dependency>
- <groupId>org.yaml</groupId>
- <artifactId>snakeyaml</artifactId>
- </dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
</exclusions>
</dependency>
<dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-binding-broker-impl</artifactId>
+ <groupId>org.opendaylight.controller.model</groupId>
+ <artifactId>model-inventory</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.ops4j.pax.exam</groupId>
+ <artifactId>pax-exam</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.ops4j.pax.exam</groupId>
+ <artifactId>pax-exam-spi</artifactId>
+ <!-- Should be in a parent POM -->
+ <version>4.4.0</version>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.ovsdb</groupId>
+ <artifactId>library</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.core</artifactId>
+ <scope>provided</scope>
+ </dependency>
<!-- Cache surefire in Maven Local repo for offline builds -->
<dependency>
*/
package org.opendaylight.ovsdb.integrationtest;
-import static junit.framework.Assert.assertFalse;
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.junit.Assert.fail;
@RunWith(PaxExam.class)
public class OvsdbLibraryIT extends OvsdbIntegrationTestBase {
- private Logger log = LoggerFactory.getLogger(OvsdbLibraryIT.class);
+ private static final Logger LOG = LoggerFactory.getLogger(OvsdbLibraryIT.class);
@Inject
private BundleContext bc;
private OvsdbClient client = null;
for (Bundle element : b) {
int state = element.getState();
if (state != Bundle.ACTIVE && state != Bundle.RESOLVED) {
- log.info("Bundle:" + element.getSymbolicName() + " state:"
- + stateToString(state));
+ LOG.info("Bundle: {} state: {}", element.getSymbolicName(), stateToString(state));
debugit = true;
}
}
if (debugit) {
- log.debug("Do some debugging because some bundle is unresolved");
+ LOG.debug("Do some debugging because some bundle is unresolved");
Thread.sleep(600000);
}
ListenableFuture<List<String>> databases = client.getDatabases();
List<String> dbNames = databases.get();
assertNotNull(dbNames);
- if (dbNames.contains(schema)) return true;
- return false;
+ return dbNames.contains(schema);
}
static String testBridgeName = "br_test";
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
-import junit.framework.Assert;
-
import org.junit.After;
+import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.ovsdb.lib.MonitorCallBack;
import org.opendaylight.ovsdb.lib.schema.DatabaseSchema;
import org.opendaylight.ovsdb.lib.schema.GenericTableSchema;
import org.opendaylight.ovsdb.lib.schema.TableSchema;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
public class OvsdbClientTestIT extends OvsdbTestBase {
- Logger logger = LoggerFactory.getLogger(OvsdbClientTestIT.class);
OvsdbClient ovs;
DatabaseSchema dbSchema = null;
System.out.println("t = " + t);
}
});
- if (updates != null) results.add(updates);
+ if (updates != null) {
+ results.add(updates);
+ }
for (int i = 0; i < 3 ; i++) { //wait 3 seconds to get a result
System.out.println("waiting on monitor response for Bridge Table...");
- if (!results.isEmpty()) break;
+ if (!results.isEmpty()) {
+ break;
+ }
Thread.sleep(1000);
}
Assert.assertTrue(update.getRows().size() > 0);
for (UUID uuid : update.getRows().keySet()) {
Row<GenericTableSchema> aNew = update.getNew(uuid);
- if (!aNew.getColumn(name).getData().equals(testBridgeName)) continue;
+ if (!aNew.getColumn(name).getData().equals(testBridgeName)) {
+ continue;
+ }
if (filter) {
Assert.assertEquals(builder.getColumns().size(), aNew.getColumns().size());
} else {
@After
public void tearDown() throws InterruptedException, ExecutionException {
- if (dbSchema == null) return;
+ if (dbSchema == null) {
+ return;
+ }
TableSchema<GenericTableSchema> bridge = dbSchema.table("Bridge", GenericTableSchema.class);
ColumnSchema<GenericTableSchema, String> name = bridge.column("name", String.class);
GenericTableSchema ovsTable = dbSchema.table("Open_vSwitch", GenericTableSchema.class);
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
-import junit.framework.Assert;
-
import org.junit.After;
+import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.ovsdb.lib.OvsdbClient;
import org.opendaylight.ovsdb.lib.schema.DatabaseSchema;
import org.opendaylight.ovsdb.lib.schema.GenericTableSchema;
import org.opendaylight.ovsdb.lib.schema.TableSchema;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
public class OvsdbClientTestITTyped extends OvsdbTestBase {
- Logger logger = LoggerFactory.getLogger(OvsdbClientTestITTyped.class);
OvsdbClient ovs;
DatabaseSchema dbSchema = null;
static String testBridgeName = "br_test";
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-import junit.framework.Assert;
-
+import org.junit.Assert;
import org.junit.Rule;
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
* will test both the options.
*/
@TypedColumn(name="name", method=MethodType.GETDATA)
- public String getName();
+ String getName();
@TypedColumn(name="name", method=MethodType.GETCOLUMN)
- public Column<GenericTableSchema, String> getNameColumn();
+ Column<GenericTableSchema, String> getNameColumn();
@TypedColumn(name="name", method=MethodType.SETDATA)
- public void setName(String name);
+ void setName(String name);
/*
* Annotations are NOT added to the Status column on purpose to test the backup
* functionality on getter, setter, column name derivation etc. TyperHelper.java.
*/
- public Column<GenericTableSchema, Map<String, String>> getStatusColumn();
- public void setStatus(Map<String, String> status);
+ Column<GenericTableSchema, Map<String, String>> getStatusColumn();
+ void setStatus(Map<String, String> status);
/*
* TypedColumn's name Annotation should override the method name based Column derivation.
* resolution priority of TyperHelper.java
*/
@TypedColumn(name="flood_vlans", method=MethodType.GETCOLUMN)
- public Column<GenericTableSchema, Set<Integer>> getFloodVlansColumn();
+ Column<GenericTableSchema, Set<Integer>> getFloodVlansColumn();
@TypedColumn(name="flood_vlans", method=MethodType.SETDATA)
- public void setFloodVlans(Set<Integer> vlans);
+ void setFloodVlans(Set<Integer> vlans);
@TypedColumn(name="ports", method=MethodType.GETCOLUMN)
- public Column<GenericTableSchema, Set<UUID>> getPortsColumn();
+ Column<GenericTableSchema, Set<UUID>> getPortsColumn();
@TypedColumn(name="ports", method=MethodType.SETDATA)
- public void setPorts(Set<UUID> ports);
+ void setPorts(Set<UUID> ports);
@TypedColumn(name="mirrors", method=MethodType.GETCOLUMN)
- public Column<GenericTableSchema, Set<UUID>> getMirrorsColumn();
+ Column<GenericTableSchema, Set<UUID>> getMirrorsColumn();
@TypedColumn(name="mirrors", method=MethodType.SETDATA)
- public void setMirrors(Set<UUID> mirrors);
+ void setMirrors(Set<UUID> mirrors);
@TypedColumn(name="controller", method=MethodType.GETCOLUMN)
- public Column<GenericTableSchema, Set<UUID>> getControllerColumn();
+ Column<GenericTableSchema, Set<UUID>> getControllerColumn();
@TypedColumn(name="controller", method=MethodType.SETDATA)
- public void setController(Set<UUID> controller);
+ void setController(Set<UUID> controller);
@TypedColumn(name="datapath_id", method=MethodType.GETCOLUMN)
- public Column<GenericTableSchema, Set<String>> getDatapathIdColumn();
+ Column<GenericTableSchema, Set<String>> getDatapathIdColumn();
@TypedColumn(name="datapath_id", method=MethodType.SETDATA)
- public void setDatapathId(Set<String> datapathId);
+ void setDatapathId(Set<String> datapathId);
@TypedColumn(name="datapath_type", method=MethodType.GETCOLUMN)
- public Column<GenericTableSchema, String> getDatapathTypeColumn();
+ Column<GenericTableSchema, String> getDatapathTypeColumn();
@TypedColumn(name="datapath_type", method=MethodType.SETDATA)
- public void setDatapathType(String datapathType);
+ void setDatapathType(String datapathType);
@TypedColumn(name="fail_mode", method=MethodType.GETCOLUMN)
- public Column<GenericTableSchema, Set<String>> getFailModeColumn();
+ Column<GenericTableSchema, Set<String>> getFailModeColumn();
@TypedColumn(name="fail_mode", method=MethodType.SETDATA)
- public void setFailMode(Set<String> failMode);
+ void setFailMode(Set<String> failMode);
@TypedColumn(name="sflow", method=MethodType.GETCOLUMN)
- public Column<GenericTableSchema, Set<UUID>> getSflowColumn();
+ Column<GenericTableSchema, Set<UUID>> getSflowColumn();
@TypedColumn(name="sflow", method=MethodType.SETDATA)
- public void setSflow(Set<UUID> sflow);
+ void setSflow(Set<UUID> sflow);
@TypedColumn(name="netflow", method=MethodType.GETCOLUMN)
- public Column<GenericTableSchema, Set<UUID>> getNetflowColumn();
+ Column<GenericTableSchema, Set<UUID>> getNetflowColumn();
@TypedColumn(name="netflow", method=MethodType.SETDATA)
- public void setNetflow(Set<UUID> netflow);
+ void setNetflow(Set<UUID> netflow);
@TypedColumn(name="flow_tables", method=MethodType.GETCOLUMN)
- public Column<GenericTableSchema, Map<Integer, UUID>> getFlowTablesColumn();
+ Column<GenericTableSchema, Map<Integer, UUID>> getFlowTablesColumn();
@TypedColumn(name="flow_tables", method=MethodType.SETDATA)
- public void setFlowTables(Map<Integer, UUID> flowTables);
+ void setFlowTables(Map<Integer, UUID> flowTables);
@TypedColumn(name="stp_enable", method=MethodType.GETCOLUMN)
- public Column<GenericTableSchema, Boolean> getStpEnableColumn();
+ Column<GenericTableSchema, Boolean> getStpEnableColumn();
@TypedColumn(name="stp_enable", method=MethodType.SETDATA)
- public void setStpEnable(Boolean stp_enable);
+ void setStpEnable(Boolean stp_enable);
@TypedColumn(name="protocols", method=MethodType.GETCOLUMN)
- public Column<GenericTableSchema, Set<String>> getProtocolsColumn();
+ Column<GenericTableSchema, Set<String>> getProtocolsColumn();
@TypedColumn(name="protocols", method=MethodType.SETDATA)
- public void setProtocols(Set<String> protocols);
+ void setProtocols(Set<String> protocols);
@TypedColumn(name="other_config", method=MethodType.GETCOLUMN)
- public Column<GenericTableSchema, Map<String, String>> getOtherConfigColumn();
+ Column<GenericTableSchema, Map<String, String>> getOtherConfigColumn();
@TypedColumn(name="other_config", method=MethodType.SETDATA)
- public void setOtherConfig(Map<String, String> other_config);
+ void setOtherConfig(Map<String, String> other_config);
@TypedColumn(name="external_ids", method=MethodType.GETCOLUMN)
- public Column<GenericTableSchema, Map<String, String>> getExternalIdsColumn();
+ Column<GenericTableSchema, Map<String, String>> getExternalIdsColumn();
@TypedColumn(name="external_ids", method=MethodType.SETDATA)
- public void setExternalIds(Map<String, String> externalIds);
+ void setExternalIds(Map<String, String> externalIds);
@TypedColumn(name="ipfix", method=MethodType.GETCOLUMN)
- public Column<GenericTableSchema, Set<UUID>> getIpfixColumn();
+ Column<GenericTableSchema, Set<UUID>> getIpfixColumn();
@TypedColumn(name="ipfix", method=MethodType.SETDATA)
- public void setIpfix(Set<UUID> ipfix);
+ void setIpfix(Set<UUID> ipfix);
}
@RunWith(PaxExam.class)
public class OvsdbPluginIT extends OvsdbIntegrationTestBase {
- private Logger log = LoggerFactory.getLogger(OvsdbPluginIT.class);
+ private static final Logger LOG = LoggerFactory.getLogger(OvsdbPluginIT.class);
@Inject
private BundleContext bc;
private OvsdbConfigurationService ovsdbConfigurationService = null;
for (Bundle element : b) {
int state = element.getState();
if (state != Bundle.ACTIVE && state != Bundle.RESOLVED) {
- log.info("Bundle:" + element.getSymbolicName() + " state:"
- + stateToString(state));
+ LOG.info("Bundle: {} state: {}", element.getSymbolicName(), stateToString(state));
debugit = true;
}
}
if (debugit) {
- log.debug("Do some debugging because some bundle is unresolved");
+ LOG.debug("Do some debugging because some bundle is unresolved");
}
assertFalse(debugit);
final int currControllersSize = bridge.getControllerColumn().getData().size();
- log.debug("Bridge has " + bridge.getControllerColumn().getData().size() + " controllers");
+ LOG.debug("Bridge has {} controllers", currControllersSize);
// ** Note: we assert against 2 or less -- instead of 1 -- to account for the _real_ controller's connection
assertTrue( "Too few controllers added to bridge object. Is this bug 960?", currControllersSize >= 1 );
}
for (Row bridgeRow : bridgeRows.values()) {
Bridge bridge = ovsdbConfigurationService.getTypedRow(node, Bridge.class, bridgeRow);
- log.trace("Test clean up removing Bridge " + bridge.getUuid());
+ LOG.trace("Test clean up removing Bridge {}", bridge.getUuid());
Status delStatus = ovsdbConfigurationService.deleteRow(node,
bridge.getSchema().getName(),
bridge.getUuid().toString());
}
if (bridgesRemoved > 0) {
- log.debug("Test clean up removed " + bridgesRemoved + " bridges");
+ LOG.debug("Test clean up removed {} bridges", bridgesRemoved);
Thread.sleep(2000); // TODO : Remove this Sleep once the Select operation is resolved.
}
}
public String getOpenVSwitchTableUUID(Connection connection) throws Exception {
OpenVSwitch openVSwitch = connection.getClient().getTypedRowWrapper(OpenVSwitch.class, null);
ConcurrentMap<String, Row> row = ovsdbConfigurationService.getRows(node, openVSwitch.getSchema().getName());
- if (row == null || row.size() == 0) return null;
+ if (row == null || row.size() == 0) {
+ return null;
+ }
return (String)row.keySet().toArray()[0];
}
@RunWith(PaxExam.class)
@ExamReactorStrategy(PerSuite.class)
public class OvsdbPluginV3IT extends OvsdbIntegrationTestBase {
- private Logger log = LoggerFactory.getLogger(OvsdbPluginV3IT.class);
+ private static final Logger LOG = LoggerFactory.getLogger(OvsdbPluginV3IT.class);
@Inject
private BundleContext bc;
private OvsdbConfigurationService ovsdbConfigurationService = null;
identifier = connectionInfo.getRemoteAddress().getHostAddress()+":"+connectionInfo.getRemotePort();
}
assertEquals(node, connectionService.getNode("OVS|" + identifier));
- log.info("Nodes = "+ connectionService.getNodes());
+ LOG.info("Nodes = {}", connectionService.getNodes());
/*
* Test sequence :
* 1. Print Cache and Assert to make sure the bridge is not created yet.
Row bridgeRow = ovsdbConfigurationService.getRow(node, databaseName, bridge.getSchema().getName(), status.getUuid());
assertNotNull(bridgeRow);
bridge = connection.getClient().getTypedRowWrapper(Bridge.class, bridgeRow);
- log.info("Bridge UUID "+bridge.getUuid()+" Status Uuid "+status.getUuid());
+ LOG.info("Bridge UUID {} Status Uuid {}", bridge.getUuid(), status.getUuid());
assertEquals(bridge.getUuid(), status.getUuid());
bridge = connection.getClient().createTypedRowWrapper(Bridge.class);
public String getOpenVSwitchTableUUID(Connection connection) throws Exception {
OpenVSwitch openVSwitch = connection.getClient().getTypedRowWrapper(OpenVSwitch.class, null);
ConcurrentMap<UUID, Row<GenericTableSchema>> rows = ovsdbConfigurationService.getRows(node, databaseName, openVSwitch.getSchema().getName());
- if (rows == null || rows.size() == 0) return null;
+ if (rows == null || rows.size() == 0) {
+ return null;
+ }
return rows.keySet().toArray()[0].toString();
}
public void printCache() throws Exception {
List<String> tables = ovsdbConfigurationService.getTables(node, databaseName);
- log.info("Tables = "+tables);
+ LOG.info("Tables = {}", tables);
assertNotNull(tables);
for (String table : tables) {
- log.info("Table "+table);
+ LOG.info("Table {}", table);
ConcurrentMap<UUID, Row<GenericTableSchema>> rows = ovsdbConfigurationService.getRows(node, databaseName, table);
- log.info(rows.toString());
+ LOG.info(rows.toString());
}
}
import java.util.Set;
import java.util.concurrent.ExecutionException;
import javax.inject.Inject;
-import junit.framework.Assert;
+import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+/*
+ * 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.ovsdb.northbound;
import com.fasterxml.jackson.databind.SerializationFeature;
OvsdbClient client = NodeResource.getOvsdbClient(nodeId, this);
try {
List<String> databases = client.getDatabases().get();
- if (databases == null) return ciDatabaseName;
+ if (databases == null) {
+ return ciDatabaseName;
+ }
for (String csDatabaseName : databases) {
- if (csDatabaseName.equalsIgnoreCase(ciDatabaseName)) return csDatabaseName;
+ if (csDatabaseName.equalsIgnoreCase(ciDatabaseName)) {
+ return csDatabaseName;
+ }
}
return ciDatabaseName;
} catch (Exception e) {
+/*
+ * 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.ovsdb.northbound;
import com.fasterxml.jackson.databind.SerializationFeature;
public Response getNodes() throws JsonProcessingException {
OvsdbConnectionService connectionService = (OvsdbConnectionService)ServiceHelper.getGlobalInstance(OvsdbConnectionService.class, this);
List<Node> nodes = connectionService.getNodes();
- if (nodes == null) return Response.noContent().build();
+ if (nodes == null) {
+ return Response.noContent().build();
+ }
List<String> nodeIds = Lists.newArrayList();
for (Node node : nodes) {
/*
- * Copyright (C) 2014 Red Hat, Inc. and others
+ * 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
- *
- * Authors : Madhu Venugopal, Brent Salisbury, Dave Tucker
*/
+
package org.opendaylight.ovsdb.northbound;
import java.io.IOException;
import org.codehaus.enunciate.jaxrs.TypeHint;
import org.opendaylight.controller.northbound.commons.RestMessages;
import org.opendaylight.controller.northbound.commons.exception.BadRequestException;
-import org.opendaylight.controller.northbound.commons.exception.ResourceConflictException;
import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException;
import org.opendaylight.controller.northbound.commons.exception.UnauthorizedException;
import org.opendaylight.controller.northbound.commons.utils.NorthboundUtils;
import org.opendaylight.ovsdb.plugin.api.StatusWithUuid;
import org.opendaylight.ovsdb.utils.servicehelper.ServiceHelper;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.JsonNode;
@Path("/v2/")
@Deprecated
public class OvsdbNorthboundV2 {
- protected static final Logger logger = LoggerFactory.getLogger(OvsdbNorthboundV2.class);
@Context
private UriInfo _uriInfo;
return username;
}
- private void handleNameMismatch(String name, String nameinURL) {
- if (name == null || nameinURL == null) {
- throw new BadRequestException(RestMessages.INVALIDDATA.toString() + " : Name is null");
- }
-
- if (name.equalsIgnoreCase(nameinURL)) {
- return;
- }
- throw new ResourceConflictException(RestMessages.INVALIDDATA.toString()
- + " : Table Name in URL does not match the row name in request body");
- }
-
/**
* Create a Row for Open_vSwitch schema
*
OvsdbClient client = connectionService.getConnection(node).getClient();
String bckCompatibleTableName = this.getBackwardCompatibleTableName(client, OvsVswitchdSchemaConstants.DATABASE_NAME, tableName);
- Row row = null;
+ Row row;
try {
row = ovsdbTable.getRow(node, bckCompatibleTableName, rowUuid);
} catch (Exception e) {
Node node = connectionService.getNode(nodeId);
OvsdbClient client = connectionService.getConnection(node).getClient();
String bckCompatibleTableName = this.getBackwardCompatibleTableName(client, OvsVswitchdSchemaConstants.DATABASE_NAME, tableName);
- Map<String, Row> rows = null;
+ Map<String, Row> rows;
try {
rows = ovsdbTable.getRows(node, bckCompatibleTableName);
} catch (Exception e) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
- Status status = ovsdbTable.updateRow(node, bckCompatibleTableName, localRow.getParentUuid(), rowUuid, localRow.getRow());
+ ovsdbTable.updateRow(node, bckCompatibleTableName, localRow.getParentUuid(), rowUuid, localRow.getRow());
return NorthboundUtils.getResponse(
new org.opendaylight.controller.sal.utils.Status(
org.opendaylight.controller.sal.utils.StatusCode.SUCCESS));
private String getBackwardCompatibleTableName(OvsdbClient client, String databaseName, String tableName) {
DatabaseSchema dbSchema = client.getDatabaseSchema(databaseName);
- if (dbSchema == null || tableName == null) return tableName;
+ if (dbSchema == null || tableName == null) {
+ return tableName;
+ }
for (String dbTableName : dbSchema.getTables()) {
- if (dbTableName.equalsIgnoreCase(tableName)) return dbTableName;
+ if (dbTableName.equalsIgnoreCase(tableName)) {
+ return dbTableName;
+ }
}
return tableName;
}
/*
- * Copyright (C) 2014 Red Hat, Inc. and others
+ * 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
- *
- * Authors : Madhu Venugopal
*/
+
package org.opendaylight.ovsdb.northbound;
import org.opendaylight.controller.northbound.commons.exception.UnauthorizedException;
/*
- * Copyright (C) 2013 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal, Brent Salisbury
*/
+
package org.opendaylight.ovsdb.northbound;
import java.io.IOException;
String parentUuid = null;
if (parentUuidNode != null) {
parentUuid = parentUuidNode.asText();
- }
+ }
JsonNode parentTableNode = json.get(PARENTTABLE);
String parentTable = null;
if (parentTableNode != null) {
/*
- * Copyright (C) 2013 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal, Brent Salisbury
*/
+
package org.opendaylight.ovsdb.northbound;
import java.util.Map;
+/*
+ * 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.ovsdb.northbound;
import com.fasterxml.jackson.databind.SerializationFeature;
+/*
+ * 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.ovsdb.northbound;
import com.fasterxml.jackson.databind.SerializationFeature;
return ciTableName;
}
for (String tableName : tables) {
- if (tableName.equalsIgnoreCase(ciTableName)) return tableName;
+ if (tableName.equalsIgnoreCase(ciTableName)) {
+ return tableName;
+ }
}
return ciTableName;
}
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
@RunWith(PowerMockRunner.class)
@PrepareForTest(ServiceHelper.class)
public class NodeResourceTest {
- static final Logger LOG = LoggerFactory.getLogger(NodeResourceTest.class);
private static final String OVS = "OVS";
private static final String IDENTIFIER = "192.168.120.31:45001";
private static final String IDENTIFIER2 = "192.168.120.31:45002";
.thenReturn(connectionService)
.thenReturn(connectionService);
- Node node = null;
try {
- node = NodeResource.getOvsdbNode(IDENTIFIER, this);
+ NodeResource.getOvsdbNode(IDENTIFIER, this);
fail("Expected an ServiceUnavailableException to be thrown");
} catch (ServiceUnavailableException e) {
assertSame(ServiceUnavailableException.class, e.getClass());
}
try {
- node = NodeResource.getOvsdbNode(BAD_IDENTIFIER, this);
+ NodeResource.getOvsdbNode(BAD_IDENTIFIER, this);
fail("Expected an ResourceNotFoundException to be thrown");
} catch (ResourceNotFoundException e) {
assertSame(ResourceNotFoundException.class, e.getClass());
}
- node = NodeResource.getOvsdbNode(OVS_IDENTIFIER, this);
+ Node node = NodeResource.getOvsdbNode(OVS_IDENTIFIER, this);
assertNotNull("Node " + OVS_IDENTIFIER + " is null", node);
}
.thenReturn(connectionService)
.thenReturn(connectionService);
- Connection testConnection = null;
try {
- testConnection = NodeResource.getOvsdbConnection(IDENTIFIER, this);
+ NodeResource.getOvsdbConnection(IDENTIFIER, this);
fail("Expected an ServiceUnavailableException to be thrown");
} catch (ServiceUnavailableException e) {
assertSame(ServiceUnavailableException.class, e.getClass());
}
try {
- testConnection = NodeResource.getOvsdbConnection(BAD_IDENTIFIER, this);
+ NodeResource.getOvsdbConnection(BAD_IDENTIFIER, this);
fail("Expected an ResourceNotFoundException to be thrown");
} catch (ResourceNotFoundException e) {
assertSame(ResourceNotFoundException.class, e.getClass());
}
- testConnection = NodeResource.getOvsdbConnection(IDENTIFIER, this);
+ Connection testConnection = NodeResource.getOvsdbConnection(IDENTIFIER, this);
assertNotNull("Connection " + OVS_IDENTIFIER + " is null", testConnection);
}
Response response = nodeResource.getNodes();
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
assertNotNull("entity should not be null", response.getEntity());
- String id = new String();
+ String id = "";
List<String> ids = Lists.newArrayList();
ids.add(id);
assertEquals("there should be no nodes", ids.toString(), response.getEntity());
Response response = nodeResource.getNodes();
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
assertNotNull("entity should not be null", response.getEntity());
- String id = new String("\"" + OVS_IDENTIFIER + "\"");
+ String id = "\"" + OVS_IDENTIFIER + "\"";
List<String> ids = Lists.newArrayList();
ids.add(id);
assertEquals(OVS_IDENTIFIER + " should be found", ids.toString(), response.getEntity());
Response response = nodeResource.getNodes();
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
assertNotNull("entity should not be null", response.getEntity());
- String id = new String("\"" + OVS_IDENTIFIER + "\"");
- String id2 = new String("\"" + OVS_IDENTIFIER2 + "\"");
+ String id = "\"" + OVS_IDENTIFIER + "\"";
+ String id2 = "\"" + OVS_IDENTIFIER2 + "\"";
List<String> ids = Lists.newArrayList();
ids.add(id);
ids.add(id2);
<version>${sonar-jacoco-listeners.version}</version>
<scope>test</scope>
</dependency>
+ <!-- AbstractConfigTestBase::getKarafDistro() needs this to find its version -->
+ <dependency>
+ <groupId>org.opendaylight.ovsdb</groupId>
+ <artifactId>karaf</artifactId>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<build>
<plugins>
karafUrl = maven()
.groupId("org.opendaylight.ovsdb")
.artifactId("karaf")
- .version("1.2.0-SNAPSHOT")
+ .versionAsInProject()
.type("zip");
return karafUrl;
<ovsdb.utils.servicehelper.version>1.2.0-SNAPSHOT</ovsdb.utils.servicehelper.version>
<powermock.version>1.5.2</powermock.version>
<sonar-jacoco-listeners.version>2.4</sonar-jacoco-listeners.version>
+ <liblldp.version>0.9.1-SNAPSHOT</liblldp.version>
<root.directory>${env.PWD}</root.directory>
<sonar.jacoco.itReportPath>${root.directory}/target/code-coverage/jacoco-it.exec</sonar.jacoco.itReportPath>
</properties>
<dependencies>
- <dependency>
- <groupId>org.apache.felix</groupId>
- <artifactId>org.apache.felix.dependencymanager</artifactId>
- </dependency>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.core</artifactId>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-common-api</artifactId>
</dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-common-util</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-core-api</artifactId>
- </dependency>
<dependency>
<groupId>org.opendaylight.controller.model</groupId>
<artifactId>model-inventory</artifactId>
<groupId>org.opendaylight.yangtools.model</groupId>
<artifactId>opendaylight-l2-types</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.ovsdb</groupId>
+ <artifactId>utils.servicehelper</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>concepts</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools.model</groupId>
+ <artifactId>ietf-topology</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.ovsdb</groupId>
+ <artifactId>southbound-api</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.openflowplugin</groupId>
+ <artifactId>openflowplugin-api</artifactId>
+ <version>${openflowplugin.version}</version>
+ </dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>liblldp</artifactId>
+ <version>${liblldp.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>com.google.code.findbugs</groupId>
+ <artifactId>jsr305</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>io.netty</groupId>
+ <artifactId>netty-buffer</artifactId>
+ <!-- Should be in a parent POM -->
+ <version>4.0.26.Final</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-lang3</artifactId>
+ </dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.powermock</groupId>
+ <artifactId>powermock-api-support</artifactId>
+ <version>${powermock.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.powermock</groupId>
+ <artifactId>powermock-reflect</artifactId>
+ <version>${powermock.version}</version>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${sonar-jacoco-listeners.version}</version>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-simple</artifactId>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<build>
+/*
+ * 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.ovsdb.openstack.netvirt.providers;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;
+
import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.ProviderContext;
+import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
import org.opendaylight.ovsdb.openstack.netvirt.api.*;
import org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.AbstractServiceInstance;
import org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.OF13Provider;
import org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.PipelineOrchestratorImpl;
import org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.Service;
import org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.services.*;
+import org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.services.arp.GatewayMacResolverService;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
private static final Logger LOG = LoggerFactory.getLogger(ConfigActivator.class);
private List<ServiceRegistration<?>> registrations = new ArrayList<ServiceRegistration<?>>();
private ProviderContext providerContext;
- private ServiceTracker NetworkingProviderManagerTracker;
public ConfigActivator(ProviderContext providerContext) {
this.providerContext = providerContext;
registerService(context, OutboundNatProvider.class.getName(),
outboundNatService, Service.OUTBOUND_NAT);
+ GatewayMacResolverService gatewayMacResolverService = new GatewayMacResolverService();
+ registerService(context, GatewayMacResolver.class.getName(),
+ gatewayMacResolverService, Service.GATEWAY_RESOLVER);
+ getNotificationProviderService().registerNotificationListener(gatewayMacResolverService);
+
+
pipelineOrchestrator.setDependencies(context, null);
outboundNatService.setDependencies(context, null);
egressAclService.setDependencies(context, null);
arpResponderService.setDependencies(context, null);
classifierService.setDependencies(context, null);
of13Provider.setDependencies(context, null);
+ gatewayMacResolverService.setDependencies(context, null);
@SuppressWarnings("unchecked")
- ServiceTracker NetworkingProviderManagerTracker = new ServiceTracker(context,
+ ServiceTracker networkingProviderManagerTracker = new ServiceTracker(context,
NetworkingProviderManager.class, null) {
@Override
public Object addingService(ServiceReference reference) {
return service;
}
};
- NetworkingProviderManagerTracker.open();
- this.NetworkingProviderManagerTracker = NetworkingProviderManagerTracker;
+ networkingProviderManagerTracker.open();
}
@Override
public void stop(BundleContext context) throws Exception {
LOG.info("ConfigActivator stop");
- /* ServiceTrackers and services are already released when bundle stops
- NetworkingProviderManagerTracker.close();
- for (ServiceRegistration registration : registrations) {
- if (registration != null) {
- registration.unregister();
- }
- }*/
+ // 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,
new String[] {AbstractServiceInstance.class.getName(), interfaceClassName},
properties, impl);
}
+
+ private NotificationProviderService getNotificationProviderService(){
+ return this.providerContext.getSALService(NotificationProviderService.class);
+ }
}
+/*
+ * 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.ovsdb.openstack.netvirt.providers;
import org.osgi.framework.BundleContext;
+/*
+ * 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.ovsdb.openstack.netvirt.providers;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
private BundleContext bundleContext = null;
private static DataBroker dataBroker = null;
private ConfigActivator activator;
+ private static ProviderContext providerContext = null;
public NetvirtProvidersProvider(BundleContext bundleContext) {
LOG.info("NetvirtProvidersProvider: bundleContext: {}", bundleContext);
return dataBroker;
}
+ public static ProviderContext getProviderContext() {
+ return providerContext;
+ }
+
@Override
public void close() throws Exception {
activator.stop(bundleContext);
}
@Override
- public void onSessionInitiated(ProviderContext providerContext) {
- dataBroker = providerContext.getSALService(DataBroker.class);
+ public void onSessionInitiated(ProviderContext providerContextRef) {
+ dataBroker = providerContextRef.getSALService(DataBroker.class);
+ providerContext = providerContextRef;
LOG.info("NetvirtProvidersProvider: onSessionInitiated dataBroker: {}", dataBroker);
- this.activator = new ConfigActivator(providerContext);
+ this.activator = new ConfigActivator(providerContextRef);
try {
activator.start(bundleContext);
} catch (Exception e) {
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal
*/
+
package org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.CheckedFuture;
+
import java.util.List;
import java.util.concurrent.ExecutionException;
+
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
*/
public abstract class AbstractServiceInstance {
public static final String SERVICE_PROPERTY ="serviceProperty";
- private static final Logger logger = LoggerFactory.getLogger(AbstractServiceInstance.class);
+ private static final Logger LOG = LoggerFactory.getLogger(AbstractServiceInstance.class);
public static final String OPENFLOW = "openflow:";
private DataBroker dataBroker = null;
// OSGi Services that we are dependent on.
public boolean isBridgeInPipeline (Node node){
String bridgeName = southbound.getBridgeName(node);
- if (bridgeName != null && Constants.INTEGRATION_BRIDGE.equals(bridgeName)) {
- return true;
- }
- return false;
+ return bridgeName != null && Constants.INTEGRATION_BRIDGE.equals(bridgeName);
}
public short getTable() {
return builder;
}
- private static final InstanceIdentifier<Flow> createFlowPath(FlowBuilder flowBuilder, NodeBuilder nodeBuilder) {
+ private 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())
.child(Flow.class, flowBuilder.getKey()).build();
}
- private static final
- InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node>
+ 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,
}
protected void writeFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder) {
- logger.debug("writeFlow: flowBuilder: {}, nodeBuilder: {}",
+ LOG.debug("writeFlow: flowBuilder: {}, nodeBuilder: {}",
flowBuilder.build(), nodeBuilder.build());
WriteTransaction modification = dataBroker.newWriteOnlyTransaction();
modification.put(LogicalDatastoreType.CONFIGURATION, createNodePath(nodeBuilder),
CheckedFuture<Void, TransactionCommitFailedException> commitFuture = modification.submit();
try {
commitFuture.get(); // TODO: Make it async (See bug 1362)
- logger.debug("Transaction success for write of Flow "+flowBuilder.getFlowName());
+ LOG.debug("Transaction success for write of Flow {}", flowBuilder.getFlowName());
} catch (Exception e) {
- logger.error(e.getMessage(), e);
+ LOG.error(e.getMessage(), e);
modification.cancel();
}
}
CheckedFuture<Void, TransactionCommitFailedException> commitFuture = modification.submit();
try {
commitFuture.get(); // TODO: Make it async (See bug 1362)
- logger.debug("Transaction success for deletion of Flow " + flowBuilder.getFlowName());
+ LOG.debug("Transaction success for deletion of Flow {}", flowBuilder.getFlowName());
} catch (Exception e) {
- logger.error(e.getMessage(), e);
+ LOG.error(e.getMessage(), e);
modification.cancel();
}
}
return data.get();
}
} catch (InterruptedException|ExecutionException e) {
- logger.error(e.getMessage(), e);
+ LOG.error(e.getMessage(), 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(e.getMessage(), e);
}
- logger.debug("Cannot find data for Flow " + flowBuilder.getFlowName());
+ LOG.debug("Cannot find data for Node {}", nodeId);
return null;
}
- private Long getDpid(Node node) {
- Long dpid = 0L;
- dpid = southbound.getDataPathId(node);
+ private long getDpid(Node node) {
+ long dpid = southbound.getDataPathId(node);
if (dpid == 0) {
- logger.warn("getDpid: dpid not found: {}", node);
+ LOG.warn("getDpid: dpid not found: {}", node);
}
return dpid;
}
*/
protected void programDefaultPipelineRule(Node node) {
if (!isBridgeInPipeline(node)) {
- //logger.trace("Bridge is not in pipeline {} ", node);
+ //LOG.trace("Bridge is not in pipeline {} ", node);
return;
}
MatchBuilder matchBuilder = new MatchBuilder();
FlowBuilder flowBuilder = new FlowBuilder();
- Long dpid = getDpid(node);
+ long dpid = getDpid(node);
if (dpid == 0L) {
- logger.info("could not find dpid: {}", node.getNodeId());
+ LOG.info("could not find dpid: {}", node.getNodeId());
return;
}
String nodeName = OPENFLOW + getDpid(node);
-/**
- * Copyright (C) 2013 Red Hat, Inc.
+/*
+ * 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.ovsdb.openstack.netvirt.providers.openflow13;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
import org.opendaylight.neutron.spi.NeutronNetwork;
+import org.opendaylight.neutron.spi.NeutronPort;
+import org.opendaylight.neutron.spi.Neutron_IPs;
import org.opendaylight.ovsdb.openstack.netvirt.MdsalHelper;
import org.opendaylight.ovsdb.openstack.netvirt.NetworkHandler;
import org.opendaylight.ovsdb.openstack.netvirt.api.BridgeConfigurationManager;
* @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 logger = LoggerFactory.getLogger(OF13Provider.class);
+ 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 volatile L2ForwardingProvider l2ForwardingProvider;
public static final String NAME = "OF13Provider";
- private volatile NetworkingProviderManager networkingProviderManager;
private volatile BundleContext bundleContext;
private volatile Southbound southbound;
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) {
- logger.error("Tunnel Endpoint not configured for Node {}", node);
+ LOG.error("Tunnel Endpoint not configured for Node {}", node);
return new Status(StatusCode.NOTFOUND, "Tunnel Endpoint not configured for "+ node);
}
if (!bridgeConfigurationManager.isNodeNeutronReady(node)) {
- logger.error(node+" is not Overlay ready");
+ LOG.error("{} is not Overlay ready", node);
return new Status(StatusCode.NOTACCEPTABLE, node+" is not Overlay ready");
}
if (!tenantNetworkManager.isTenantNetworkPresentInNode(node, tunnelKey)) {
- logger.debug(node + " has no VM corresponding to segment " + 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 boolean addTunnelPort (Node node, String tunnelType, InetAddress src, InetAddress dst) {
String tunnelBridgeName = configurationService.getIntegrationBridgeName();
String portName = getTunnelName(tunnelType, dst);
- logger.info("addTunnelPort enter: portName: {}", portName);
+ LOG.info("addTunnelPort enter: portName: {}", portName);
if (southbound.extractTerminationPointAugmentation(node, portName) != null
|| southbound.isTunnelTerminationPointExist(node, tunnelBridgeName, portName)) {
- logger.info("Tunnel {} is present in {} of {}", portName, tunnelBridgeName, node.getNodeId().getValue());
+ LOG.info("Tunnel {} is present in {} of {}", portName, tunnelBridgeName, node.getNodeId().getValue());
return true;
}
options.put("remote_ip", dst.getHostAddress());
if (!southbound.addTunnelTerminationPoint(node, tunnelBridgeName, portName, tunnelType, options)) {
- logger.error("Failed to insert Tunnel port {} in {}", portName, tunnelBridgeName);
+ LOG.error("Failed to insert Tunnel port {} in {}", portName, tunnelBridgeName);
return false;
}
- logger.info("addTunnelPort exit: portName: {}", portName);
+ LOG.info("addTunnelPort exit: portName: {}", portName);
return true;
}
handleVlanMiss(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD, segmentationId, ethPort, false);
}
- private Long getDpid(Node node) {
- Long dpid = 0L;
- dpid = southbound.getDataPathId(node);
+ private long getDpid(Node node) {
+ long dpid = southbound.getDataPathId(node);
if (dpid == 0) {
- logger.warn("getDpid: dpid not found: {}", node);
+ LOG.warn("getDpid: dpid not found: {}", node);
}
return dpid;
}
- private Long getIntegrationBridgeOFDPID(Node node) {
- Long dpid = 0L;
+ private long getIntegrationBridgeOFDPID(Node node) {
+ long dpid = 0L;
if (southbound.getBridgeName(node).equals(configurationService.getIntegrationBridgeName())) {
dpid = getDpid(node);
}
return dpid;
}
- private Long getExternalBridgeDpid(Node node) {
- Long dpid = 0L;
- if (southbound.getBridgeName(node).equals(configurationService.getExternalBridgeName())) {
- 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) {
- logger.debug("programLocalRules: node: {}, intf: {}, networkType: {}, segmentationId: {}",
+ LOG.debug("programLocalRules: node: {}, intf: {}, networkType: {}, segmentationId: {}",
node.getNodeId(), intf.getName(), networkType, segmentationId);
try {
- Long dpid = getIntegrationBridgeOFDPID(node);
+ long dpid = getIntegrationBridgeOFDPID(node);
if (dpid == 0L) {
- logger.debug("programLocalRules: Openflow Datapath-ID not set for the integration bridge in {}",
+ LOG.debug("programLocalRules: Openflow Datapath-ID not set for the integration bridge in {}",
node);
return;
}
long localPort = southbound.getOFPort(intf);
if (localPort == 0) {
- logger.info("programLocalRules: could not find ofPort for Port {} on Node {}",intf.getName(), node.getNodeId());
+ 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) {
- logger.warn("No AttachedMac seen in {}", intf);
+ LOG.warn("No AttachedMac seen in {}", intf);
return;
}
/* Program local rules based on network type */
- if (networkType.equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VLAN)) {
- logger.debug("Program local vlan rules for interface {}", intf.getName());
+ if (isVlan(networkType)) {
+ LOG.debug("Program local vlan rules for interface {}", intf.getName());
programLocalVlanRules(node, dpid, segmentationId, attachedMac, localPort);
}
+ if ((isTunnel(networkType)|| isVlan(networkType))) {
+ LOG.debug("programLocalRules: Program fixed security group rules for interface {}", intf.getName());
+ // Get the DHCP port for the subnet to which the interface belongs to.
+ NeutronPort dhcpPort = securityServicesManager.getDHCPServerPort(intf);
+ if (null != dhcpPort) {
+ boolean isComputePort =securityServicesManager.isComputePort(intf);
+ boolean isLastPortinBridge = securityServicesManager.isLastPortinBridge(node, intf);
+ boolean isLastPortinSubnet =false;
+ List<Neutron_IPs> srcAddressList = null;
+ if(isComputePort) {
+ isLastPortinSubnet = securityServicesManager.isLastPortinSubnet(node, intf);
+ srcAddressList = securityServicesManager.getIpAddress(node, intf);
+ if (null == srcAddressList) {
+ LOG.warn("programLocalRules: No Ip address assigned {}", intf);
+ return;
+ }
+ }
+ ingressAclProvider.programFixedSecurityACL(dpid,segmentationId, dhcpPort.getMacAddress(), localPort,
+ isLastPortinSubnet,isComputePort, true);
+ egressAclProvider.programFixedSecurityACL(dpid, segmentationId, attachedMac, localPort,
+ srcAddressList, isLastPortinBridge, isComputePort,true);
+ } else {
+ LOG.warn("programLocalRules: No DCHP port seen in network of {}", intf);
+ }
+ }
/* If the network type is tunnel based (VXLAN/GRRE/etc) with Neutron Port Security ACLs */
/* TODO SB_MIGRATION */
/*if ((networkType.equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_GRE) || networkType.equalsIgnoreCase
(NetworkHandler.NETWORK_TYPE_VXLAN)) && securityServicesManager.isPortSecurityReady(intf)) {
- logger.debug("Neutron port has a Port Security Group");
+ LOG.debug("Neutron port has a Port Security Group");
// Retrieve the security group UUID from the Neutron Port
NeutronSecurityGroup securityGroupInPort = securityServicesManager.getSecurityGroupInPort(intf);
- logger.debug("Program Local rules for networkType: {} does contain a Port Security Group: {} " +
+ LOG.debug("Program Local rules for networkType: {} does contain a Port Security Group: {} " +
"to be installed on DPID: {}", networkType, securityGroupInPort, dpid);
ingressAclProvider.programPortSecurityACL(dpid, segmentationId, attachedMac, localPort,
securityGroupInPort);
egressAclProvider.programPortSecurityACL(dpid, segmentationId, attachedMac, localPort,
securityGroupInPort);
}*/
- if (networkType.equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_GRE) ||
- networkType.equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VXLAN)) {
- logger.debug("Program local bridge rules for interface {}, "
- + "dpid: {}, segmentationId: {}, attachedMac: {}, localPort: {}",
+ 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) {
- logger.error("Exception in programming Local Rules for "+intf+" on "+node, e);
+ LOG.error("Exception in programming Local Rules for " + intf + " on " + node, e);
}
}
private void removeLocalRules (String networkType, String segmentationId, Node node,
OvsdbTerminationPointAugmentation intf) {
- logger.debug("removeLocalRules: node: {}, intf: {}, networkType: {}, segmentationId: {}",
+ LOG.debug("removeLocalRules: node: {}, intf: {}, networkType: {}, segmentationId: {}",
node.getNodeId(), intf.getName(), networkType, segmentationId);
try {
- Long dpid = getIntegrationBridgeOFDPID(node);
+ long dpid = getIntegrationBridgeOFDPID(node);
if (dpid == 0L) {
- logger.debug("removeLocalRules: Openflow Datapath-ID not set for the integration bridge in {}", node);
+ LOG.debug("removeLocalRules: Openflow Datapath-ID not set for the integration bridge in {}", node);
return;
}
long localPort = southbound.getOFPort(intf);
if (localPort == 0) {
- logger.info("removeLocalRules: could not find ofPort");
+ LOG.info("removeLocalRules: could not find ofPort");
return;
}
String attachedMac = southbound.getInterfaceExternalIdsValue(intf, Constants.EXTERNAL_ID_VM_MAC);
if (attachedMac == null) {
- logger.warn("No AttachedMac seen in {}", intf);
+ LOG.warn("No AttachedMac seen in {}", intf);
return;
}
/* Program local rules based on network type */
- if (networkType.equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VLAN)) {
- logger.debug("Remove local vlan rules for interface {}", intf.getName());
+ if (isVlan(networkType)) {
+ LOG.debug("Remove local vlan rules for interface {}", intf.getName());
removeLocalVlanRules(node, dpid, segmentationId, attachedMac, localPort);
- } else if (networkType.equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_GRE) ||
- networkType.equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VXLAN)) {
- logger.debug("Remove local bridge rules for interface {}", intf.getName());
+ } else if (isTunnel(networkType)) {
+ LOG.debug("Remove local bridge rules for interface {}", intf.getName());
removeLocalBridgeRules(node, dpid, segmentationId, attachedMac, localPort);
}
+ if (isTunnel(networkType)|| isVlan(networkType)) {
+ LOG.debug("removeLocalRules: Remove fixed security group rules for interface {}", intf.getName());
+ NeutronPort dhcpPort = securityServicesManager.getDHCPServerPort(intf);
+ if (null != dhcpPort) {
+ List<Neutron_IPs> srcAddressList = securityServicesManager.getIpAddress(node, intf);
+ if (null == srcAddressList) {
+ LOG.warn("removeLocalRules: No Ip address assigned {}", intf);
+ return;
+ }
+ boolean isLastPortinBridge = securityServicesManager.isLastPortinBridge(node, intf);
+ boolean isComputePort =securityServicesManager.isComputePort(intf);
+ boolean isLastPortinSubnet =false;
+ if (isComputePort)
+ {
+ isLastPortinSubnet = securityServicesManager.isLastPortinSubnet(node, intf);
+ }
+ ingressAclProvider.programFixedSecurityACL(dpid, segmentationId, dhcpPort.getMacAddress(), localPort,
+ isLastPortinSubnet, isComputePort, false);
+ egressAclProvider.programFixedSecurityACL(dpid, segmentationId, attachedMac, localPort,
+ srcAddressList, isLastPortinBridge, isComputePort, false);
+ }else{
+ LOG.warn("removeLocalRules: No DCHP port seen in network of {}", intf);
+ }
+ }
} catch (Exception e) {
- logger.error("Exception in removing Local Rules for "+intf+" on "+node, e);
+ LOG.error("Exception in removing Local Rules for " + intf + " on " + node, e);
}
}
// so we don't see those updates in this case - we only see the new nodes interface updates.
private void programTunnelRules (String tunnelType, String segmentationId, InetAddress dst, Node node,
OvsdbTerminationPointAugmentation intf, boolean local) {
- logger.debug("programTunnelRules: node: {}, intf: {}, local: {}, tunnelType: {}, "
- + "segmentationId: {}, dstAddr: {}",
+ LOG.debug("programTunnelRules: node: {}, intf: {}, local: {}, tunnelType: {}, "
+ + "segmentationId: {}, dstAddr: {}",
node.getNodeId(), intf.getName(), local, tunnelType, segmentationId, dst.getHostAddress());
try {
- Long dpid = getIntegrationBridgeOFDPID(node);
+ long dpid = getIntegrationBridgeOFDPID(node);
if (dpid == 0L) {
- logger.debug("programTunnelRules: Openflow Datapath-ID not set for the integration bridge in {}", node);
+ LOG.debug("programTunnelRules: Openflow Datapath-ID not set for the integration bridge in {}", node);
return;
}
long localPort = southbound.getOFPort(intf);
if (localPort == 0) {
- logger.info("programTunnelRules: could not find ofPort for Port {} on Node{}",intf.getName(),node.getNodeId());
+ 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) {
- logger.warn("programTunnelRules: No AttachedMac seen in {}", intf);
+ LOG.warn("programTunnelRules: No AttachedMac seen in {}", intf);
return;
}
if(tunnelPort != null){
long tunnelOFPort = southbound.getOFPort(tunnelPort);
if (tunnelOFPort == 0) {
- logger.error("programTunnelRules: Could not Identify Tunnel port {} -> OF ({}) on {}",
+ LOG.error("programTunnelRules: Could not Identify Tunnel port {} -> OF ({}) on {}",
tunnelPort.getName(), tunnelOFPort, node);
return;
}
- logger.debug("programTunnelRules: Identified Tunnel port {} -> OF ({}) on {}",
+ LOG.debug("programTunnelRules: Identified Tunnel port {} -> OF ({}) on {}",
tunnelPort.getName(), tunnelOFPort, node);
if (!local) {
- logger.trace("programTunnelRules: program remote egress tunnel rules: node {}, intf {}",
- node.getNodeId().getValue(), intf.getName());
+ LOG.trace("programTunnelRules: program remote egress tunnel rules: node {}, intf {}",
+ node.getNodeId().getValue(), intf.getName());
programRemoteEgressTunnelBridgeRules(node, dpid, segmentationId, attachedMac,
tunnelOFPort, localPort);
- }
-
- if (local) {
- logger.trace("programTunnelRules: program local ingress tunnel rules: node {}, intf {}",
+ } else {
+ LOG.trace("programTunnelRules: program local ingress tunnel rules: node {}, intf {}",
node.getNodeId().getValue(), intf.getName());
programLocalIngressTunnelBridgeRules(node, dpid, segmentationId, attachedMac,
tunnelOFPort, localPort);
}
- return;
}
} catch (Exception e) {
- logger.trace("", e);
+ LOG.trace("", e);
}
}
private void removeTunnelRules (String tunnelType, String segmentationId, InetAddress dst, Node node,
OvsdbTerminationPointAugmentation intf,
boolean local, boolean isLastInstanceOnNode) {
- logger.debug("removeTunnelRules: node: {}, intf: {}, local: {}, tunnelType: {}, "
+ LOG.debug("removeTunnelRules: node: {}, intf: {}, local: {}, tunnelType: {}, "
+ "segmentationId: {}, dstAddr: {}, isLastinstanceOnNode: {}",
node.getNodeId(), intf.getName(), local, tunnelType, segmentationId, dst, isLastInstanceOnNode);
try {
- Long dpid = getIntegrationBridgeOFDPID(node);
+ long dpid = getIntegrationBridgeOFDPID(node);
if (dpid == 0L) {
- logger.debug("removeTunnelRules: Openflow Datapath-ID not set for the integration bridge in {}", node);
+ LOG.debug("removeTunnelRules: Openflow Datapath-ID not set for the integration bridge in {}", node);
return;
}
long localPort = southbound.getOFPort(intf);
if (localPort == 0) {
- logger.info("removeTunnelRules: could not find ofPort");
+ LOG.info("removeTunnelRules: could not find ofPort");
return;
}
String attachedMac = southbound.getInterfaceExternalIdsValue(intf, Constants.EXTERNAL_ID_VM_MAC);
if (attachedMac == null) {
- logger.error("removeTunnelRules: No AttachedMac seen in {}", intf);
+ LOG.error("removeTunnelRules: No AttachedMac seen in {}", intf);
return;
}
if (tunIntf.getName().equals(getTunnelName(tunnelType, dst))) {
long tunnelOFPort = southbound.getOFPort(tunIntf);
if (tunnelOFPort == 0) {
- logger.error("Could not Identify Tunnel port {} -> OF ({}) on {}",
+ LOG.error("Could not Identify Tunnel port {} -> OF ({}) on {}",
tunIntf.getName(), tunnelOFPort, node);
return;
}
- logger.debug("Identified Tunnel port {} -> OF ({}) on {}",
+ LOG.debug("Identified Tunnel port {} -> OF ({}) on {}",
tunIntf.getName(), tunnelOFPort, node);
if (!local) {
}
}
} catch (Exception e) {
- logger.error("", e);
+ LOG.error("", e);
}
}
private void programVlanRules (NeutronNetwork network, Node node, OvsdbTerminationPointAugmentation intf) {
- logger.debug("programVlanRules: node: {}, network: {}, intf: {}",
+ LOG.debug("programVlanRules: node: {}, network: {}, intf: {}",
node.getNodeId(), network.getNetworkUUID(), intf.getName());
- Long dpid = getIntegrationBridgeOFDPID(node);
+ long dpid = getIntegrationBridgeOFDPID(node);
if (dpid == 0L) {
- logger.debug("programVlanRules: Openflow Datapath-ID not set for the integration bridge in {}", node);
+ LOG.debug("programVlanRules: Openflow Datapath-ID not set for the integration bridge in {}", node);
return;
}
long localPort = southbound.getOFPort(intf);
if (localPort == 0) {
- logger.debug("programVlanRules: could not find ofPort for {}", intf.getName());
+ LOG.debug("programVlanRules: could not find ofPort for {}", intf.getName());
return;
}
String attachedMac = southbound.getInterfaceExternalIdsValue(intf, Constants.EXTERNAL_ID_VM_MAC);
if (attachedMac == null) {
- logger.debug("programVlanRules: No AttachedMac seen in {}", intf);
+ LOG.debug("programVlanRules: No AttachedMac seen in {}", intf);
return;
}
bridgeConfigurationManager.getPhysicalInterfaceName(node, network.getProviderPhysicalNetwork());
long ethOFPort = southbound.getOFPort(node, phyIfName);
if (ethOFPort == 0) {
- logger.warn("programVlanRules: could not find ofPort for physical port {}", phyIfName);
+ LOG.warn("programVlanRules: could not find ofPort for physical port {}", phyIfName);
return;
}
- logger.debug("programVlanRules: Identified eth port {} -> ofPort ({}) on {}",
+ 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(),
private void removeVlanRules (NeutronNetwork network, Node node, OvsdbTerminationPointAugmentation intf,
boolean isLastInstanceOnNode) {
- logger.debug("removeVlanRules: node: {}, network: {}, intf: {}, isLastInstanceOnNode",
+ LOG.debug("removeVlanRules: node: {}, network: {}, intf: {}, isLastInstanceOnNode",
node.getNodeId(), network.getNetworkUUID(), intf.getName(), isLastInstanceOnNode);
- Long dpid = getIntegrationBridgeOFDPID(node);
+ long dpid = getIntegrationBridgeOFDPID(node);
if (dpid == 0L) {
- logger.debug("removeVlanRules: Openflow Datapath-ID not set for the integration bridge in {}", node);
+ LOG.debug("removeVlanRules: Openflow Datapath-ID not set for the integration bridge in {}", node);
return;
}
long localPort = southbound.getOFPort(intf);
if (localPort == 0) {
- logger.debug("removeVlanRules: programVlanRules: could not find ofPort for {}", intf.getName());
+ 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) {
- logger.debug("removeVlanRules: No AttachedMac seen in {}", intf);
+ LOG.debug("removeVlanRules: No AttachedMac seen in {}", intf);
return;
}
bridgeConfigurationManager.getPhysicalInterfaceName(node, network.getProviderPhysicalNetwork());
long ethOFPort = southbound.getOFPort(node, phyIfName);
if (ethOFPort == 0) {
- logger.warn("removeVlanRules: could not find ofPort for physical port {}", phyIfName);
+ LOG.warn("removeVlanRules: could not find ofPort for physical port {}", phyIfName);
return;
}
- logger.debug("removeVlanRules: Identified eth port {} -> ofPort ({}) on {}",
+ LOG.debug("removeVlanRules: Identified eth port {} -> ofPort ({}) on {}",
phyIfName, ethOFPort, node);
removeRemoteEgressVlanRules(node, dpid, network.getProviderSegmentationID(),
Node srcBridgeNode = southbound.getBridgeNode(srcNode, configurationService.getIntegrationBridgeName());
programLocalRules(networkType, network.getProviderSegmentationID(), srcBridgeNode, intf);
- if (networkType.equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VLAN)) {
+ if (isVlan(networkType)) {
programVlanRules(network, srcNode, intf);
- } else if (networkType.equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_GRE)
- || networkType.equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VXLAN)){
+ } else if (isTunnel(networkType)){
- boolean sourceTunnelStatus = false;
+ boolean sourceTunnelStatus;
boolean destTunnelStatus = false;
for (Node dstNode : nodes.values()) {
InetAddress src = configurationService.getTunnelEndPoint(srcNode);
programTunnelRules(networkType, segmentationId, src, dstBridgeNode, intf, false);
}
} else {
- logger.warn("Tunnel end-point configuration missing. Please configure it in OpenVSwitch Table. "
+ 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");
}
private void triggerInterfaceUpdates(Node node) {
- logger.debug("enter triggerInterfaceUpdates for {}", node.getNodeId());
+ 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) {
- logger.warn("Trigger Interface update for {}", port);
+ LOG.warn("Trigger Interface update for {}", port);
handleInterfaceUpdate(neutronNetwork, node, port);
}
}
} else {
- logger.warn("triggerInterfaceUpdates: tps are null");
+ LOG.warn("triggerInterfaceUpdates: tps are null");
}
- logger.debug("exit triggerInterfaceUpdates for {}", node.getNodeId());
+ LOG.debug("exit triggerInterfaceUpdates for {}", node.getNodeId());
}
@Override
nodeCacheManager.getOvsdbNodes();
nodes.remove(southbound.extractBridgeOvsdbNodeId(srcNode));
- logger.info("Delete intf " + intf.getName() + " isLastInstanceOnNode " + isLastInstanceOnNode);
+ LOG.info("Delete intf " + intf.getName() + " isLastInstanceOnNode " + isLastInstanceOnNode);
List<String> phyIfName = bridgeConfigurationManager.getAllPhysicalInterfaceNames(srcNode);
if (southbound.isTunnel(intf)) {
// Delete tunnel port
MdsalHelper.createOvsdbInterfaceType(intf.getInterfaceType()),
src, dst);
} catch (Exception e) {
- logger.error(e.getMessage(), e);
+ LOG.error(e.getMessage(), e);
}
} else if (phyIfName.contains(intf.getName())) {
deletePhysicalPort(srcNode, intf.getName());
removeLocalRules(network.getProviderNetworkType(), network.getProviderSegmentationID(),
srcNode, intf);
- if (network.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VLAN)) {
+ if (isVlan(network.getProviderNetworkType())) {
removeVlanRules(network, srcNode, intf, isLastInstanceOnNode);
- } else if (network.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_GRE)
- || network.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VXLAN)) {
+ } else if (isTunnel(network.getProviderNetworkType())) {
for (Node dstNode : nodes.values()) {
InetAddress src = configurationService.getTunnelEndPoint(srcNode);
InetAddress dst = configurationService.getTunnelEndPoint(dstNode);
if ((src != null) && (dst != null)) {
- logger.info("Remove tunnel rules for interface "
+ LOG.info("Remove tunnel rules for interface "
+ intf.getName() + " on srcNode " + srcNode.getNodeId().getValue());
removeTunnelRules(tunnelType, network.getProviderSegmentationID(),
dst, srcNode, intf, true, isLastInstanceOnNode);
Node dstBridgeNode = southbound.getBridgeNode(dstNode, Constants.INTEGRATION_BRIDGE);
if(dstBridgeNode != null){
- logger.info("Remove tunnel rules for interface "
+ LOG.info("Remove tunnel rules for interface "
+ intf.getName() + " on dstNode " + dstNode.getNodeId().getValue());
removeTunnelRules(tunnelType, network.getProviderSegmentationID(),
src, dstBridgeNode, intf, false, isLastInstanceOnNode);
}
} else {
- logger.warn("Tunnel end-point configuration missing. Please configure it in "
- + "OpenVSwitch Table. "
- + "Check source {} or destination {}",
+ 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");
}
private void initializeFlowRules(Node node, String bridgeName) {
Long dpid = southbound.getDataPathId(node);
String datapathId = southbound.getDatapathId(node);
- logger.info("initializeFlowRules: bridgeName: {}, dpid: {} - {}",
+ LOG.info("initializeFlowRules: bridgeName: {}, dpid: {} - {}",
bridgeName, dpid, datapathId);
if (dpid == 0L) {
- logger.debug("Openflow Datapath-ID not set for the integration bridge in {}", node);
+ LOG.debug("Openflow Datapath-ID not set for the integration bridge in {}", node);
return;
}
* 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) {
* 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) {
* 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);
return data.get();
}
} catch (InterruptedException|ExecutionException e) {
- logger.error(e.getMessage(), e);
+ LOG.error(e.getMessage(), e);
}
- logger.debug("Cannot find data for Group " + groupBuilder.getGroupName());
+ LOG.debug("Cannot find data for Group " + groupBuilder.getGroupName());
return null;
}
CheckedFuture<Void, TransactionCommitFailedException> commitFuture = modification.submit();
try {
commitFuture.get(); // TODO: Make it async (See bug 1362)
- logger.debug("Transaction success for write of Group "+groupBuilder.getGroupName());
+ LOG.debug("Transaction success for write of Group " + groupBuilder.getGroupName());
} catch (InterruptedException|ExecutionException e) {
- logger.error(e.getMessage(), e);
+ LOG.error(e.getMessage(), e);
}
}
try {
commitFuture.get(); // TODO: Make it async (See bug 1362)
- logger.debug("Transaction success for deletion of Group "+groupBuilder.getGroupName());
+ LOG.debug("Transaction success for deletion of Group " + groupBuilder.getGroupName());
} catch (InterruptedException|ExecutionException e) {
- logger.error(e.getMessage(), e);
+ LOG.error(e.getMessage(), e);
}
}
- private Flow getFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder) {
- 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();
-
- ReadOnlyTransaction readTx = dataBroker.newReadOnlyTransaction();
- try {
- Optional<Flow> data = readTx.read(LogicalDatastoreType.CONFIGURATION, path1).get();
- if (data.isPresent()) {
- return data.get();
- }
- } catch (InterruptedException|ExecutionException e) {
- logger.error(e.getMessage(), e);
- }
-
- logger.debug("Cannot find data for Flow " + flowBuilder.getFlowName());
- return null;
- }
-
private void writeFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder) {
ReadWriteTransaction modification = dataBroker.newReadWriteTransaction();
InstanceIdentifier<Flow> path1 =
CheckedFuture<Void, TransactionCommitFailedException> commitFuture = modification.submit();
try {
commitFuture.get(); // TODO: Make it async (See bug 1362)
- logger.debug("Transaction success for write of Flow "+flowBuilder.getFlowName());
- } catch (InterruptedException|ExecutionException e) {
- logger.error(e.getMessage(), e);
- }
- }
-
- private void removeFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder) {
- WriteTransaction modification = dataBroker.newWriteOnlyTransaction();
- 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.delete(LogicalDatastoreType.OPERATIONAL, nodeBuilderToInstanceId(nodeBuilder));
- //modification.delete(LogicalDatastoreType.OPERATIONAL, path1);
- //modification.delete(LogicalDatastoreType.CONFIGURATION, nodeBuilderToInstanceId(nodeBuilder));
- modification.delete(LogicalDatastoreType.CONFIGURATION, path1);
-
- CheckedFuture<Void, TransactionCommitFailedException> commitFuture = modification.submit();
- try {
- commitFuture.get(); // TODO: Make it async (See bug 1362)
- logger.debug("Transaction success for deletion of Flow "+flowBuilder.getFlowName());
+ LOG.debug("Transaction success for write of Flow " + flowBuilder.getFlowName());
} catch (InterruptedException|ExecutionException e) {
- logger.error(e.getMessage(), e);
+ LOG.error(e.getMessage(), e);
}
}
* @param port Long representing a port on a switch/node
* @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);
- logger.debug("createOutputGroupInstructions() Node Connector ID is - Type=openflow: DPID={} port={} existingInstructions={}", dpidLong, port, instructions);
+ LOG.debug("createOutputGroupInstructions() Node Connector ID is - Type=openflow: DPID={} port={} existingInstructions={}", dpidLong, port, instructions);
List<Action> actionList = Lists.newArrayList();
ActionBuilder ab = new ActionBuilder();
OutputActionBuilder oab = new OutputActionBuilder();
oab.setOutputNodeConnector(ncid);
ab.setAction(new OutputActionCaseBuilder().setOutputAction(oab.build()).build());
- logger.debug("createOutputGroupInstructions(): output action {}", ab.build());
+ LOG.debug("createOutputGroupInstructions(): output action {}", ab.build());
boolean addNew = true;
boolean groupActionAdded = false;
groupBuilder.setGroupType(GroupTypes.GroupAll);
groupBuilder.setKey(key);
group = getGroup(groupBuilder, nodeBuilder);
- logger.debug("createOutputGroupInstructions: group {}", group);
+ LOG.debug("createOutputGroupInstructions: group {}", group);
break;
}
}
- logger.debug("createOutputGroupInstructions: groupActionAdded {}", groupActionAdded);
+ 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();
- logger.debug("createOutputGroupInstructions: bucketActions {}", bucketActions);
+ LOG.debug("createOutputGroupInstructions: bucketActions {}", bucketActions);
for (Action action : bucketActions) {
if (action.getAction() instanceof OutputActionCase) {
OutputActionCase opAction = (OutputActionCase)action.getAction();
}
}
}
- logger.debug("createOutputGroupInstructions: addNew {}", addNew);
+ LOG.debug("createOutputGroupInstructions: addNew {}", addNew);
if (addNew) {
/* the new output action is not in the bucket, add to bucket */
if (!buckets.getBucket().isEmpty()) {
bucketList.add(bucketBuilder.build());
bucketsBuilder.setBucket(bucketList);
groupBuilder.setBuckets(bucketsBuilder.build());
- logger.debug("createOutputGroupInstructions: bucketList {}", bucketList);
+ LOG.debug("createOutputGroupInstructions: bucketList {}", bucketList);
}
}
} else {
groupId++;
}
- logger.debug("createOutputGroupInstructions: group {}", groupBuilder.build());
- logger.debug("createOutputGroupInstructions: actionList {}", actionList);
+ LOG.debug("createOutputGroupInstructions: group {}", groupBuilder.build());
+ LOG.debug("createOutputGroupInstructions: actionList {}", actionList);
if (addNew) {
/* rewrite the group to group table */
* @param port Long representing a port on a switch/node
* @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);
- logger.debug("removeOutputPortFromGroup() Node Connector ID is - Type=openflow: DPID={} port={} existingInstructions={}", dpidLong, port, instructions);
+ LOG.debug("removeOutputPortFromGroup() Node Connector ID is - Type=openflow: DPID={} port={} existingInstructions={}", dpidLong, port, instructions);
List<Action> actionList = Lists.newArrayList();
ActionBuilder ab;
bucketList.add(bucketBuilder.build());
bucketsBuilder.setBucket(bucketList);
groupBuilder.setBuckets(bucketsBuilder.build());
- logger.debug("removeOutputPortFromGroup: bucketList {}", bucketList);
+ LOG.debug("removeOutputPortFromGroup: bucketList {}", bucketList);
writeGroup(groupBuilder, nodeBuilder);
ApplyActionsBuilder aab = new ApplyActionsBuilder();
@Override
public void initializeOFFlowRules(Node openflowNode) {
String bridgeName = southbound.getBridgeName(openflowNode);
- logger.info("initializeOFFlowRules: bridgeName: {}", bridgeName);
+ LOG.info("initializeOFFlowRules: bridgeName: {}", bridgeName);
if (bridgeName.equals(configurationService.getIntegrationBridgeName())) {
initializeFlowRules(openflowNode, configurationService.getIntegrationBridgeName());
triggerInterfaceUpdates(openflowNode);
} else if (bridgeName.equals(configurationService.getExternalBridgeName())) {
initializeFlowRules(openflowNode, configurationService.getExternalBridgeName());
- logger.info("initializeOFFlowRules after writeFlow: bridgeName: {}", bridgeName);
+ LOG.info("initializeOFFlowRules after writeFlow: bridgeName: {}", bridgeName);
triggerInterfaceUpdates(openflowNode);
- logger.info("initializeOFFlowRules after triggerUpdates: bridgeName: {}", bridgeName);
+ LOG.info("initializeOFFlowRules after triggerUpdates: bridgeName: {}", bridgeName);
}
}
@Override
public void setDependencies(Object impl) {
if (impl instanceof NetworkingProviderManager) {
- networkingProviderManager = (NetworkingProviderManager)impl;
+ NetworkingProviderManager networkingProviderManager = (NetworkingProviderManager) impl;
networkingProviderManager.providerAdded(
- bundleContext.getServiceReference(NetworkingProvider.class.getName()),this);
+ bundleContext.getServiceReference(NetworkingProvider.class.getName()), this);
}
}
}
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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.ovsdb.openstack.netvirt.providers.openflow13;
+
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
import org.osgi.framework.ServiceReference;
* @author Madhu Venugopal
*/
public interface PipelineOrchestrator {
- public Service getNextServiceInPipeline(Service service);
+ Service getNextServiceInPipeline(Service service);
AbstractServiceInstance getServiceInstance(Service service);
- public void enqueue(Node node);
- public void registerService(final ServiceReference ref, AbstractServiceInstance serviceInstance);
- public void unregisterService(final ServiceReference ref);
+ void enqueue(Node node);
+ void registerService(final ServiceReference ref, AbstractServiceInstance serviceInstance);
+ void unregisterService(final ServiceReference ref);
}
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Dave Tucker, Madhu Venugopal
*/
package org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13;
import org.slf4j.LoggerFactory;
public class PipelineOrchestratorImpl implements ConfigInterface, NodeCacheListener, PipelineOrchestrator {
- private static final Logger logger = LoggerFactory.getLogger(PipelineOrchestratorImpl.class);
+ private static final Logger LOG = LoggerFactory.getLogger(PipelineOrchestratorImpl.class);
private List<Service> staticPipeline = Lists.newArrayList(
Service.CLASSIFIER,
Service.ARP_RESPONDER,
public PipelineOrchestratorImpl() {
eventHandler = Executors.newSingleThreadExecutor();
- this.queue = new LinkedBlockingQueue<Node>();
- logger.info("PipelineOrchestratorImpl constructor");
+ 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);
- logger.info("registerService {} - {}", serviceInstance, service);
+ LOG.info("registerService {} - {}", serviceInstance, service);
serviceRegistry.put(service, serviceInstance);
}
@Override
public Service getNextServiceInPipeline(Service service) {
int index = staticPipeline.indexOf(service);
- if (index >= staticPipeline.size() - 1) return null;
+ if (index >= staticPipeline.size() - 1) {
+ return null;
+ }
return staticPipeline.get(index + 1);
}
@Override
public AbstractServiceInstance getServiceInstance(Service service) {
- if (service == null) return null;
+ if (service == null) {
+ return null;
+ }
return serviceRegistry.get(service);
}
* causes programming issues. Hence delaying the programming by a second to
* avoid the clash. This hack/workaround should be removed once Bug 1997 is resolved.
*/
- logger.info(">>>>> dequeue: {}", node);
+ LOG.info(">>>>> dequeue: {}", node);
Thread.sleep(1000);
for (Service service : staticPipeline) {
AbstractServiceInstance serviceInstance = getServiceInstance(service);
- //logger.info("pipeline: {} - {}", service, serviceInstance);
+ //LOG.info("pipeline: {} - {}", service, serviceInstance);
if (serviceInstance != null) {
if (southbound.getBridge(node) != null) {
serviceInstance.programDefaultPipelineRule(node);
}
}
} catch (Exception e) {
- logger.warn("Processing interrupted, terminating ", e);
+ LOG.warn("Processing interrupted, terminating ", e);
}
while (!queue.isEmpty()) {
@Override
public void enqueue(Node node) {
- logger.info(">>>>> enqueue: {}", node);
+ LOG.info(">>>>> enqueue: {}", node);
try {
queue.put(node);
} catch (InterruptedException e) {
- logger.warn("Failed to enqueue operation {}", node, e);
+ LOG.warn("Failed to enqueue operation {}", node, e);
}
}
if (action == Action.ADD) {
enqueue(node);
} else {
- logger.info("update ignored: {}", node);
+ LOG.info("update ignored: {}", node);
}
}
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal
*/
package org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13;
public enum Service {
CLASSIFIER ((short) 0, "Classifier"),
+ GATEWAY_RESOLVER((short) 0, "External Network Gateway Resolver"),
DIRECTOR ((short) 10, "Director"),
ARP_RESPONDER ((short) 20, "Distributed ARP Responder"),
INBOUND_NAT ((short) 30, "DNAT for inbound floating-ip traffic"),
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, "SNAT for traffic accessing external network"),
+ OUTBOUND_NAT ((short) 100, "DNAT for outbound floating-ip traffic"),
L2_FORWARDING ((short) 110, "Layer2 mac,vlan based forwarding");
short table;
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal, Dave Tucker
*/
+
package org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.services;
import java.math.BigInteger;
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal
*/
+
package org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.services;
import java.math.BigInteger;
import com.google.common.collect.Lists;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
public class ClassifierService extends AbstractServiceInstance implements ClassifierProvider, ConfigInterface {
public final static long REG_VALUE_FROM_LOCAL = 0x1L;
super(service);
}
- private static final Logger logger = LoggerFactory.getLogger(ClassifierService.class);
-
/*
* (Table:Classifier) Egress VM Traffic Towards TEP
* Match: Destination Ethernet Addr and OpenFlow InPort
if (write) {
// Create the OF Actions and Instructions
- InstructionBuilder ib = new InstructionBuilder();
InstructionsBuilder isb = new InstructionsBuilder();
// Instructions List Stores Individual Instructions
List<Instruction> instructions = Lists.newArrayList();
// Append the default pipeline after the first classification
- ib = this.getMutablePipelineInstructionBuilder();
+ InstructionBuilder ib = this.getMutablePipelineInstructionBuilder();
ib.setOrder(0);
ib.setKey(new InstructionKey(0));
instructions.add(ib.build());
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal
*/
+
package org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.services;
import java.math.BigInteger;
import org.opendaylight.neutron.spi.NeutronSecurityGroup;
import org.opendaylight.neutron.spi.NeutronSecurityRule;
+import org.opendaylight.neutron.spi.Neutron_IPs;
import org.opendaylight.ovsdb.openstack.netvirt.api.Constants;
import org.opendaylight.ovsdb.openstack.netvirt.api.EgressAclProvider;
import org.opendaylight.ovsdb.openstack.netvirt.providers.ConfigInterface;
public class EgressAclService extends AbstractServiceInstance implements EgressAclProvider, ConfigInterface {
- static final Logger logger = LoggerFactory.getLogger(EgressAclService.class);
+ private static final Logger LOG = LoggerFactory.getLogger(EgressAclService.class);
+ final int DHCP_SOURCE_PORT = 67;
+ final int DHCP_DESTINATION_PORT = 68;
+ final String HOST_MASK = "/32";
public EgressAclService() {
super(Service.EGRESS_ACL);
public void programPortSecurityACL(Long dpid, String segmentationId, String attachedMac, long localPort,
NeutronSecurityGroup securityGroup) {
- logger.trace("programLocalBridgeRulesWithSec neutronSecurityGroup: {} ", securityGroup);
+ LOG.trace("programLocalBridgeRulesWithSec neutronSecurityGroup: {} ", securityGroup);
List<NeutronSecurityRule> portSecurityList = securityGroup.getSecurityRules();
/* Iterate over the Port Security Rules in the Port Security Group bound to the port*/
for (NeutronSecurityRule portSecurityRule : portSecurityList) {
*/
if (portSecurityRule.getSecurityRuleEthertype().equalsIgnoreCase("IPv4") &&
portSecurityRule.getSecurityRuleDirection().equalsIgnoreCase("egress")) {
- logger.debug("Egress IPV4 ACL Port Security Rule: {} ", portSecurityRule);
+ LOG.debug("Egress IPV4 ACL Port Security Rule: {} ", portSecurityRule);
// ToDo: Implement Port Range
/**
(!String.valueOf(portSecurityRule.getSecurityRuleRemoteIpPrefix()).equalsIgnoreCase("null") &&
!String.valueOf(portSecurityRule.getSecurityRuleRemoteIpPrefix())
.equalsIgnoreCase("0.0.0.0/0"))) {
- logger.debug(
+ LOG.debug(
"Rule #1 egress PortSec Rule Matches -> TCP Protocol: {}, TCP Port Min: {}, TCP Port Max: {}, IP Prefix: {}",
portSecurityRule.getSecurityRuleProtocol(), portSecurityRule.getSecurityRulePortMin(),
portSecurityRule.getSecurityRulePortMax(),
(!String.valueOf(portSecurityRule.getSecurityRuleRemoteIpPrefix()).equalsIgnoreCase("null") &&
!String.valueOf(portSecurityRule.getSecurityRuleRemoteIpPrefix())
.equalsIgnoreCase("0.0.0.0/0"))) {
- logger.debug(
+ LOG.debug(
"Rule #2 egress PortSec Rule Matches -> TCP Protocol: {}, TCP Port Min: {}, TCP Port Max: {}, IP Prefix: {}",
portSecurityRule.getSecurityRuleProtocol(), portSecurityRule.getSecurityRulePortMin(),
portSecurityRule.getSecurityRulePortMax(),
String.valueOf(portSecurityRule.getSecurityRulePortMin()).equalsIgnoreCase("null") &&
String.valueOf(portSecurityRule.getSecurityRulePortMax()).equalsIgnoreCase("null") &&
!String.valueOf(portSecurityRule.getSecurityRuleRemoteIpPrefix()).equalsIgnoreCase("null")) {
- logger.debug(
+ LOG.debug(
"Rule #3 egress PortSec Rule Matches -> TCP Protocol: {}, TCP Port Min: {}, TCP Port Max: {}, IP Prefix: {}",
portSecurityRule.getSecurityRuleProtocol(), portSecurityRule.getSecurityRulePortMin(),
portSecurityRule.getSecurityRulePortMax(),
(!String.valueOf(portSecurityRule.getSecurityRuleRemoteIpPrefix()).equalsIgnoreCase("null") &&
!String.valueOf(portSecurityRule.getSecurityRuleRemoteIpPrefix())
.equalsIgnoreCase("0.0.0.0/0"))) {
- logger.debug(
+ LOG.debug(
"Rule #4 egress PortSec Rule Matches -> TCP Protocol: {}, TCP Port Min: {}, TCP Port Max: {}, IP Prefix: {}",
portSecurityRule.getSecurityRuleProtocol(), portSecurityRule.getSecurityRulePortMin(),
portSecurityRule.getSecurityRulePortMax(),
!String.valueOf(portSecurityRule.getSecurityRulePortMin()).equalsIgnoreCase("null") &&
!String.valueOf(portSecurityRule.getSecurityRulePortMax()).equalsIgnoreCase("null") &&
String.valueOf(portSecurityRule.getSecurityRuleRemoteIpPrefix()).equalsIgnoreCase("null")) {
- logger.debug(
+ LOG.debug(
"Rule #5 egress PortSec Rule Matches -> TCP Protocol: {}, TCP Port Min: {}, TCP Port Max: {}, IP Prefix: {}",
portSecurityRule.getSecurityRuleProtocol(), portSecurityRule.getSecurityRulePortMin(),
portSecurityRule.getSecurityRulePortMax(),
!String.valueOf(portSecurityRule.getSecurityRulePortMin()).equalsIgnoreCase("null") &&
String.valueOf(portSecurityRule.getSecurityRulePortMax()).equalsIgnoreCase("null") &&
String.valueOf(portSecurityRule.getSecurityRuleRemoteIpPrefix()).equalsIgnoreCase("null")) {
- logger.debug(
+ LOG.debug(
"Rule #6 egress PortSec Rule Matches -> TCP Protocol: {}, TCP Port Min: {}, TCP Port Max: {}, IP Prefix: {}",
portSecurityRule.getSecurityRuleProtocol(), portSecurityRule.getSecurityRulePortMin(),
portSecurityRule.getSecurityRulePortMax(),
((String.valueOf(portSecurityRule.getSecurityRuleRemoteIpPrefix()).equalsIgnoreCase("null")) ||
String.valueOf(portSecurityRule.getSecurityRuleRemoteIpPrefix())
.equalsIgnoreCase("0.0.0.0/0"))) {
- logger.debug(
+ LOG.debug(
"Rule #7 egress PortSec Rule Matches -> TCP Protocol: {}, TCP Port Min: {}, TCP Port Max: {}, IP Prefix: {}",
portSecurityRule.getSecurityRuleProtocol(), portSecurityRule.getSecurityRulePortMin(),
portSecurityRule.getSecurityRulePortMax(),
portSecurityRule.getSecurityRuleProtocol(), Constants.PROTO_MATCH_PRIORITY);
continue;
}
- logger.debug("ACL Match combination not found for rule: {}", portSecurityRule);
+ LOG.debug("ACL Match combination not found for rule: {}", portSecurityRule);
+ }
+ }
+ }
+
+ @Override
+ public void programFixedSecurityACL(Long dpid, String segmentationId, String attachedMac,
+ long localPort, List<Neutron_IPs> srcAddressList, boolean isLastPortinBridge, boolean isComputePort ,boolean write) {
+ // If it is the only port in the bridge add the rule to allow any DHCP client traffic
+ if (isLastPortinBridge) {
+ egressACLDHCPAllowClientTrafficFromVm(dpid, write, Constants.PROTO_DHCP_CLIENT_TRAFFIC_MATCH_PRIORITY);
+ }
+ if(isComputePort) {
+ // add rule to drop the DHCP server traffic originating from the vm.
+ egressACLDHCPDropServerTrafficfromVM(dpid, localPort, write, Constants.PROTO_DHCP_CLIENT_SPOOF_MATCH_PRIORITY_DROP);
+ //Adds rule to check legitimate ip/mac pair for each packet from the vm
+ for(Neutron_IPs srcAddress : srcAddressList) {
+ String addressWithPrefix = srcAddress.getIpAddress() + HOST_MASK;
+ egressACLAllowTrafficFromVmIpMacPair(dpid, localPort, attachedMac, addressWithPrefix, Constants.PROTO_VM_IP_MAC_MATCH_PRIORITY,write);
}
}
}
flowBuilder.setMatch(MatchUtils.createSmacTcpPortWithFlagMatch(matchBuilder,
attachedMac, Constants.TCP_SYN, segmentationId).build());
- logger.debug("MatchBuilder contains: {}", flowBuilder.getMatch());
+ LOG.debug("MatchBuilder contains: {}", flowBuilder.getMatch());
String flowId = "TCP_Syn_Egress_Default_Drop_" + segmentationId + "_" + attachedMac;
flowBuilder.setId(new FlowId(flowId));
// Add InstructionBuilder to the Instruction(s)Builder List
isb.setInstruction(instructions);
- logger.debug("Instructions contain: {}", ib.getInstruction());
+ LOG.debug("Instructions contain: {}", ib.getInstruction());
// Add InstructionsBuilder to FlowBuilder
flowBuilder.setInstructions(isb.build());
writeFlow(flowBuilder, nodeBuilder);
.createSmacTcpSynDstIpPrefixTcpPort(matchBuilder, new MacAddress(attachedMac),
tcpPort, Constants.TCP_SYN, segmentationId, srcIpPrefix).build());
- logger.debug(" MatchBuilder contains: {}", flowBuilder.getMatch());
+ LOG.debug(" MatchBuilder contains: {}", flowBuilder.getMatch());
String flowId = "UcastEgress_" + segmentationId + "_" + attachedMac +
securityRulePortMin + securityRuleIpPrefix;
// Add Flow Attributes
if (write) {
// Instantiate the Builders for the OF Actions and Instructions
- InstructionBuilder ib = new InstructionBuilder();
InstructionsBuilder isb = new InstructionsBuilder();
List<Instruction> instructionsList = Lists.newArrayList();
- ib = this.getMutablePipelineInstructionBuilder();
+ InstructionBuilder ib = this.getMutablePipelineInstructionBuilder();
ib.setOrder(0);
ib.setKey(new InstructionKey(0));
instructionsList.add(ib.build());
isb.setInstruction(instructionsList);
- logger.debug("Instructions contain: {}", ib.getInstruction());
+ LOG.debug("Instructions contain: {}", ib.getInstruction());
// Add InstructionsBuilder to FlowBuilder
flowBuilder.setInstructions(isb.build());
writeFlow(flowBuilder, nodeBuilder);
flowBuilder.setMatch(MatchUtils
.createTunnelIDMatch(matchBuilder, new BigInteger(segmentationId)).build());
- logger.debug("MatchBuilder contains: {}", flowBuilder.getMatch());
+ LOG.debug("MatchBuilder contains: {}", flowBuilder.getMatch());
String flowId = "EgressAllProto_" + segmentationId + "_" +
attachedMac + "_AllowEgressTCPSyn_" + securityRuleProtcol;
// Add Flow Attributes
if (write) {
// Instantiate the Builders for the OF Actions and Instructions
- InstructionBuilder ib = new InstructionBuilder();
InstructionsBuilder isb = new InstructionsBuilder();
List<Instruction> instructionsList = Lists.newArrayList();
- ib = this.getMutablePipelineInstructionBuilder();
+ InstructionBuilder ib = this.getMutablePipelineInstructionBuilder();
ib.setOrder(0);
ib.setKey(new InstructionKey(0));
instructionsList.add(ib.build());
isb.setInstruction(instructionsList);
- logger.debug("Instructions contain: {}", ib.getInstruction());
+ LOG.debug("Instructions contain: {}", ib.getInstruction());
// Add InstructionsBuilder to FlowBuilder
flowBuilder.setInstructions(isb.build());
writeFlow(flowBuilder, nodeBuilder);
boolean write, String securityRuleIpPrefix, Integer protoPortMatchPriority) {
String nodeName = Constants.OPENFLOW_NODE_PREFIX + dpidLong;
- Ipv4Prefix srcIpPrefix = new Ipv4Prefix(securityRuleIpPrefix);
MatchBuilder matchBuilder = new MatchBuilder();
NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
FlowBuilder flowBuilder = new FlowBuilder();
flowBuilder.setMatch(MatchUtils.createTunnelIDMatch(matchBuilder, new BigInteger(segmentationId))
.build());
if (securityRuleIpPrefix != null) {
+ Ipv4Prefix srcIpPrefix = new Ipv4Prefix(securityRuleIpPrefix);
flowBuilder.setMatch(MatchUtils
.createSmacIpTcpSynMatch(matchBuilder, new MacAddress(attachedMac), null, srcIpPrefix)
.build());
.createSmacIpTcpSynMatch(matchBuilder, new MacAddress(attachedMac), null, null)
.build());
}
- logger.debug("MatchBuilder contains: {}", flowBuilder.getMatch());
+ LOG.debug("MatchBuilder contains: {}", flowBuilder.getMatch());
String flowId = "Egress_Proto_ACL" + segmentationId + "_" +
attachedMac + "_Permit_" + securityRuleIpPrefix;
// Add Flow Attributes
if (write) {
// Instantiate the Builders for the OF Actions and Instructions
- InstructionBuilder ib = new InstructionBuilder();
InstructionsBuilder isb = new InstructionsBuilder();
List<Instruction> instructionsList = Lists.newArrayList();
- ib = this.getMutablePipelineInstructionBuilder();
+ InstructionBuilder ib = this.getMutablePipelineInstructionBuilder();
ib.setOrder(0);
ib.setKey(new InstructionKey(0));
instructionsList.add(ib.build());
isb.setInstruction(instructionsList);
- logger.debug("Instructions contain: {}", ib.getInstruction());
+ LOG.debug("Instructions contain: {}", ib.getInstruction());
// Add InstructionsBuilder to FlowBuilder
flowBuilder.setInstructions(isb.build());
writeFlow(flowBuilder, nodeBuilder);
flowBuilder.setMatch(MatchUtils.createSmacTcpSyn(matchBuilder, attachedMac, tcpPort,
Constants.TCP_SYN, segmentationId).build());
- logger.debug("MatchBuilder contains: {}", flowBuilder.getMatch());
+ LOG.debug("MatchBuilder contains: {}", flowBuilder.getMatch());
String flowId = "Ucast_this.getTable()" + segmentationId + "_" + attachedMac + securityRulePortMin;
// Add Flow Attributes
flowBuilder.setId(new FlowId(flowId));
flowBuilder.setHardTimeout(0);
flowBuilder.setIdleTimeout(0);
+ if (write) {
+ // Instantiate the Builders for the OF Actions and Instructions
+ InstructionsBuilder isb = new InstructionsBuilder();
+ List<Instruction> instructionsList = Lists.newArrayList();
+
+ InstructionBuilder ib = this.getMutablePipelineInstructionBuilder();
+ ib.setOrder(0);
+ ib.setKey(new InstructionKey(0));
+ instructionsList.add(ib.build());
+ isb.setInstruction(instructionsList);
+
+ LOG.debug("Instructions contain: {}", ib.getInstruction());
+ // Add InstructionsBuilder to FlowBuilder
+ flowBuilder.setInstructions(isb.build());
+ writeFlow(flowBuilder, nodeBuilder);
+ } else {
+ removeFlow(flowBuilder, nodeBuilder);
+ }
+ }
+
+ /**
+ * Adds flow to allow any DHCP client traffic
+ *
+ * @param dpidLong the dpid
+ * @param write whether to write or delete the flow
+ * @param protoPortMatchPriority the priority
+ */
+ public void egressACLDHCPAllowClientTrafficFromVm(Long dpidLong,
+ boolean write, Integer protoPortMatchPriority) {
+
+ String nodeName = Constants.OPENFLOW_NODE_PREFIX + dpidLong;
+ MatchBuilder matchBuilder = new MatchBuilder();
+ NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
+ FlowBuilder flowBuilder = new FlowBuilder();
+
+ flowBuilder.setMatch(MatchUtils.createDHCPMatch(matchBuilder, DHCP_DESTINATION_PORT, DHCP_SOURCE_PORT).build());
+ LOG.debug("egressACLDHCPAllowClientTrafficFromVm: MatchBuilder contains: {}", flowBuilder.getMatch());
+ String flowId = "Egress_DHCP_Client" + "_Permit_";
+ // Add Flow Attributes
+ flowBuilder.setId(new FlowId(flowId));
+ FlowKey key = new FlowKey(new FlowId(flowId));
+ flowBuilder.setStrict(false);
+ flowBuilder.setPriority(protoPortMatchPriority);
+ flowBuilder.setBarrier(true);
+ flowBuilder.setTableId(this.getTable());
+ flowBuilder.setKey(key);
+ flowBuilder.setFlowName(flowId);
+ flowBuilder.setHardTimeout(0);
+ flowBuilder.setIdleTimeout(0);
+
+ if (write) {
+ // Instantiate the Builders for the OF Actions and Instructions
+ InstructionsBuilder isb = new InstructionsBuilder();
+ List<Instruction> instructionsList = Lists.newArrayList();
+
+ InstructionBuilder ib = this.getMutablePipelineInstructionBuilder();
+ ib.setOrder(0);
+ ib.setKey(new InstructionKey(0));
+ instructionsList.add(ib.build());
+ isb.setInstruction(instructionsList);
+
+ LOG.debug("egressACLDHCPAllowClientTrafficFromVm: Instructions contain: {}", ib.getInstruction());
+ // Add InstructionsBuilder to FlowBuilder
+ flowBuilder.setInstructions(isb.build());
+ writeFlow(flowBuilder, nodeBuilder);
+ } else {
+ removeFlow(flowBuilder, nodeBuilder);
+ }
+ }
+
+ /**
+ * 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 protoPortMatchPriority the priority
+ */
+ public void egressACLDHCPDropServerTrafficfromVM(Long dpidLong, long localPort,
+ boolean write, Integer protoPortMatchPriority) {
+
+ String nodeName = Constants.OPENFLOW_NODE_PREFIX + dpidLong;
+ MatchBuilder matchBuilder = new MatchBuilder();
+ NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
+ FlowBuilder flowBuilder = new FlowBuilder();
+ MatchUtils.createInPortMatch(matchBuilder, dpidLong, localPort);
+ flowBuilder.setMatch(MatchUtils.createDHCPMatch(matchBuilder, DHCP_SOURCE_PORT, DHCP_DESTINATION_PORT).build());
+
+ LOG.debug("egressACLDHCPDropServerTrafficfromVM: MatchBuilder contains: {}", flowBuilder.getMatch());
+ String flowId = "Egress_DHCP_Server" + "_" + localPort + "_DROP_";
+ // Add Flow Attributes
+ flowBuilder.setId(new FlowId(flowId));
+ FlowKey key = new FlowKey(new FlowId(flowId));
+ flowBuilder.setStrict(false);
+ flowBuilder.setPriority(protoPortMatchPriority);
+ flowBuilder.setBarrier(true);
+ flowBuilder.setTableId(this.getTable());
+ flowBuilder.setKey(key);
+ flowBuilder.setFlowName(flowId);
+ flowBuilder.setHardTimeout(0);
+ flowBuilder.setIdleTimeout(0);
+
if (write) {
// Instantiate the Builders for the OF Actions and Instructions
InstructionBuilder ib = new InstructionBuilder();
InstructionsBuilder isb = new InstructionsBuilder();
List<Instruction> instructionsList = Lists.newArrayList();
- ib = this.getMutablePipelineInstructionBuilder();
+ InstructionUtils.createDropInstructions(ib);
ib.setOrder(0);
ib.setKey(new InstructionKey(0));
instructionsList.add(ib.build());
isb.setInstruction(instructionsList);
- logger.debug("Instructions contain: {}", ib.getInstruction());
+ LOG.debug("egressACLDHCPDropServerTrafficfromVM: Instructions contain: {}", ib.getInstruction());
// Add InstructionsBuilder to FlowBuilder
flowBuilder.setInstructions(isb.build());
writeFlow(flowBuilder, nodeBuilder);
}
}
+ /**
+ * 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 protoPortMatchPriority the priority
+ * @param write is write or delete
+ */
+ public void egressACLAllowTrafficFromVmIpMacPair(Long dpidLong, long localPort,
+ String attachedMac, String srcIp, Integer protoPortMatchPriority, boolean write) {
+
+ String nodeName = Constants.OPENFLOW_NODE_PREFIX + dpidLong;
+ MatchBuilder matchBuilder = new MatchBuilder();
+ NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
+ FlowBuilder flowBuilder = new FlowBuilder();
+ MatchUtils.createSrcL3IPv4MatchWithMac(matchBuilder, new Ipv4Prefix(srcIp),new MacAddress(attachedMac));
+ MatchUtils.createInPortMatch(matchBuilder, dpidLong, localPort);
+ flowBuilder.setMatch(matchBuilder.build());
+
+ LOG.debug("egressACLAllowTrafficFromVmIpMacPair: MatchBuilder contains: {}", flowBuilder.getMatch());
+ String flowId = "Egress_Allow_VM_IP_MAC" + "_" + localPort + attachedMac + "_Permit_";
+ // Add Flow Attributes
+ flowBuilder.setId(new FlowId(flowId));
+ FlowKey key = new FlowKey(new FlowId(flowId));
+ flowBuilder.setStrict(false);
+ flowBuilder.setPriority(protoPortMatchPriority);
+ flowBuilder.setBarrier(true);
+ flowBuilder.setTableId(this.getTable());
+ flowBuilder.setKey(key);
+ flowBuilder.setFlowName(flowId);
+ flowBuilder.setHardTimeout(0);
+ flowBuilder.setIdleTimeout(0);
+
+ if (write) {
+ // Instantiate the Builders for the OF Actions and Instructions
+ InstructionsBuilder isb = new InstructionsBuilder();
+ List<Instruction> instructionsList = Lists.newArrayList();
+
+ InstructionBuilder ib = this.getMutablePipelineInstructionBuilder();
+ ib.setOrder(0);
+ ib.setKey(new InstructionKey(0));
+ instructionsList.add(ib.build());
+ isb.setInstruction(instructionsList);
+
+ LOG.debug("egressACLAllowTrafficFromVmIpMacPair: Instructions contain: {}", ib.getInstruction());
+ // 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(EgressAclProvider.class.getName()), this);
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal, Dave Tucker
*/
+
package org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.services;
import java.math.BigInteger;
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal
*/
+
package org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.services;
import java.math.BigInteger;
public class IngressAclService extends AbstractServiceInstance implements IngressAclProvider, ConfigInterface {
- static final Logger logger = LoggerFactory.getLogger(IngressAclService.class);
+ static final Logger LOG = LoggerFactory.getLogger(IngressAclService.class);
public IngressAclService() {
super(Service.INGRESS_ACL);
public void programPortSecurityACL(Long dpid, String segmentationId, String attachedMac,
long localPort, NeutronSecurityGroup securityGroup) {
- logger.trace("programLocalBridgeRulesWithSec neutronSecurityGroup: {} ", securityGroup);
+ LOG.trace("programLocalBridgeRulesWithSec neutronSecurityGroup: {} ", securityGroup);
List<NeutronSecurityRule> portSecurityList = securityGroup.getSecurityRules();
/* Iterate over the Port Security Rules in the Port Security Group bound to the port*/
for (NeutronSecurityRule portSecurityRule : portSecurityList) {
*/
if (portSecurityRule.getSecurityRuleEthertype().equalsIgnoreCase("IPv4") &&
portSecurityRule.getSecurityRuleDirection().equalsIgnoreCase("ingress")) {
- logger.debug("ACL Rule matching IPv4 and ingress is: {} ", portSecurityRule);
+ LOG.debug("ACL Rule matching IPv4 and ingress is: {} ", portSecurityRule);
/**
* TCP Proto (True), TCP Port Minimum (True), TCP Port Max (True), IP Prefix (True)
*/
(!String.valueOf(portSecurityRule.getSecurityRuleRemoteIpPrefix()).equalsIgnoreCase("null") &&
!String.valueOf(portSecurityRule.getSecurityRuleRemoteIpPrefix())
.equalsIgnoreCase("0.0.0.0/0"))) {
- logger.debug("Rule #1 ingress PortSec Rule Matches -> TCP Protocol: {}, TCP Port Min: {}, TCP Port Max: {}, IP Prefix: {}",
+ LOG.debug("Rule #1 ingress PortSec Rule Matches -> TCP Protocol: {}, TCP Port Min: {}, TCP Port Max: {}, IP Prefix: {}",
portSecurityRule.getSecurityRuleProtocol(), portSecurityRule.getSecurityRulePortMin(),
portSecurityRule.getSecurityRulePortMax(),
portSecurityRule.getSecurityRuleRemoteIpPrefix());
(!String.valueOf(portSecurityRule.getSecurityRuleRemoteIpPrefix()).equalsIgnoreCase("null") &&
!String.valueOf(portSecurityRule.getSecurityRuleRemoteIpPrefix())
.equalsIgnoreCase("0.0.0.0/0"))) {
- logger.debug("Rule #2 ingress PortSec Rule Matches -> TCP Protocol: {}, TCP Port Min: {}, TCP Port Max: {}, IP Prefix: {}",
+ LOG.debug("Rule #2 ingress PortSec Rule Matches -> TCP Protocol: {}, TCP Port Min: {}, TCP Port Max: {}, IP Prefix: {}",
portSecurityRule.getSecurityRuleProtocol(), portSecurityRule.getSecurityRulePortMin(),
portSecurityRule.getSecurityRulePortMax(),
portSecurityRule.getSecurityRuleRemoteIpPrefix());
String.valueOf(portSecurityRule.getSecurityRulePortMin()).equalsIgnoreCase("null") &&
String.valueOf(portSecurityRule.getSecurityRulePortMax()).equalsIgnoreCase("null") &&
!String.valueOf(portSecurityRule.getSecurityRuleRemoteIpPrefix()).equalsIgnoreCase("null")) {
- logger.debug("Rule #3 ingress PortSec Rule Matches -> TCP Protocol: {}, TCP Port Min: {}, TCP Port Max: {}, IP Prefix: {}",
+ LOG.debug("Rule #3 ingress PortSec Rule Matches -> TCP Protocol: {}, TCP Port Min: {}, TCP Port Max: {}, IP Prefix: {}",
portSecurityRule.getSecurityRuleProtocol(), portSecurityRule.getSecurityRulePortMin(),
portSecurityRule.getSecurityRulePortMax(),
portSecurityRule.getSecurityRuleRemoteIpPrefix());
(!String.valueOf(portSecurityRule.getSecurityRuleRemoteIpPrefix()).equalsIgnoreCase("null") &&
!String.valueOf(portSecurityRule.getSecurityRuleRemoteIpPrefix())
.equalsIgnoreCase("0.0.0.0/0"))) {
- logger.debug("Rule #4 ingress PortSec Rule Matches -> TCP Protocol: {}, TCP Port Min: {}, TCP Port Max: {}, IP Prefix: {}",
+ LOG.debug("Rule #4 ingress PortSec Rule Matches -> TCP Protocol: {}, TCP Port Min: {}, TCP Port Max: {}, IP Prefix: {}",
portSecurityRule.getSecurityRuleProtocol(), portSecurityRule.getSecurityRulePortMin(),
portSecurityRule.getSecurityRulePortMax(),
portSecurityRule.getSecurityRuleRemoteIpPrefix());
!String.valueOf(portSecurityRule.getSecurityRulePortMin()).equalsIgnoreCase("null") &&
!String.valueOf(portSecurityRule.getSecurityRulePortMax()).equalsIgnoreCase("null") &&
String.valueOf(portSecurityRule.getSecurityRuleRemoteIpPrefix()).equalsIgnoreCase("null")) {
- logger.debug("Rule #5 ingress PortSec Rule Matches -> TCP Protocol: {}, TCP Port Min: {}, TCP Port Max: {}, IP Prefix: {}",
+ LOG.debug("Rule #5 ingress PortSec Rule Matches -> TCP Protocol: {}, TCP Port Min: {}, TCP Port Max: {}, IP Prefix: {}",
portSecurityRule.getSecurityRuleProtocol(), portSecurityRule.getSecurityRulePortMin(),
portSecurityRule.getSecurityRulePortMax(),
portSecurityRule.getSecurityRuleRemoteIpPrefix());
!String.valueOf(portSecurityRule.getSecurityRulePortMin()).equalsIgnoreCase("null") &&
String.valueOf(portSecurityRule.getSecurityRulePortMax()).equalsIgnoreCase("null") &&
String.valueOf(portSecurityRule.getSecurityRuleRemoteIpPrefix()).equalsIgnoreCase("null")) {
- logger.debug("Rule #6 ingress PortSec Rule Matches -> TCP Protocol: {}, TCP Port Min: {}, TCP Port Max: {}, IP Prefix: {}",
+ LOG.debug("Rule #6 ingress PortSec Rule Matches -> TCP Protocol: {}, TCP Port Min: {}, TCP Port Max: {}, IP Prefix: {}",
portSecurityRule.getSecurityRuleProtocol(), portSecurityRule.getSecurityRulePortMin(),
portSecurityRule.getSecurityRulePortMax(),
portSecurityRule.getSecurityRuleRemoteIpPrefix());
((String.valueOf(portSecurityRule.getSecurityRuleRemoteIpPrefix()).equalsIgnoreCase("null")) ||
String.valueOf(portSecurityRule.getSecurityRuleRemoteIpPrefix())
.equalsIgnoreCase("0.0.0.0/0"))) {
- logger.debug("Rule #7 ingress PortSec Rule Matches -> TCP Protocol: {}, TCP Port Min: {}, TCP Port Max: {}, IP Prefix: {}",
+ LOG.debug("Rule #7 ingress PortSec Rule Matches -> TCP Protocol: {}, TCP Port Min: {}, TCP Port Max: {}, IP Prefix: {}",
portSecurityRule.getSecurityRuleProtocol(), portSecurityRule.getSecurityRulePortMin(),
portSecurityRule.getSecurityRulePortMax(),
portSecurityRule.getSecurityRuleRemoteIpPrefix());
portSecurityRule.getSecurityRuleProtocol(), Constants.PROTO_MATCH_PRIORITY);
continue;
}
- logger.debug("Ingress ACL Match combination not found for rule: {}", portSecurityRule);
+ LOG.debug("Ingress ACL Match combination not found for rule: {}", portSecurityRule);
}
}
}
+ @Override
+ public void programFixedSecurityACL(Long dpid, String segmentationId, String dhcpMacAddress,
+ long localPort, boolean isLastPortinSubnet, boolean isComputePort, boolean write){
+ //If this port is the only port in the compute node add the DHCP server rule.
+ if (isLastPortinSubnet && isComputePort ) {
+ ingressACLDHCPAllowServerTraffic(dpid, segmentationId,dhcpMacAddress, write,Constants.PROTO_DHCP_SERVER_MATCH_PRIORITY);
+ }
+ }
+
public void ingressACLTcpSyn(Long dpidLong, String segmentationId, String attachedMac, boolean write,
Integer securityRulePortMin, Integer protoPortMatchPriority) {
flowBuilder.setMatch(MatchUtils.createDmacTcpSynMatch(matchBuilder, attachedMac, tcpPort,
Constants.TCP_SYN, segmentationId).build());
- logger.debug("ingressACLTcpSyn MatchBuilder contains: {}", flowBuilder.getMatch());
+ LOG.debug("ingressACLTcpSyn MatchBuilder contains: {}", flowBuilder.getMatch());
String flowId = "UcastOut_ACL2_" + segmentationId + "_" + attachedMac + securityRulePortMin;
// Add Flow Attributes
flowBuilder.setId(new FlowId(flowId));
if (write) {
// Instantiate the Builders for the OF Actions and Instructions
- InstructionBuilder ib = new InstructionBuilder();
InstructionsBuilder isb = new InstructionsBuilder();
List<Instruction> instructionsList = Lists.newArrayList();
- ib = this.getMutablePipelineInstructionBuilder();
+ InstructionBuilder ib = this.getMutablePipelineInstructionBuilder();
ib.setOrder(0);
ib.setKey(new InstructionKey(0));
instructionsList.add(ib.build());
isb.setInstruction(instructionsList);
- logger.debug("Instructions are: {}", ib.getInstruction());
+ LOG.debug("Instructions are: {}", ib.getInstruction());
// Add InstructionsBuilder to FlowBuilder
flowBuilder.setInstructions(isb.build());
writeFlow(flowBuilder, nodeBuilder);
.createDmacTcpSynDstIpPrefixTcpPort(matchBuilder, new MacAddress(attachedMac),
tcpPort, Constants.TCP_SYN, segmentationId, srcIpPrefix).build());
- logger.debug(" MatchBuilder contains: {}", flowBuilder.getMatch());
+ LOG.debug(" MatchBuilder contains: {}", flowBuilder.getMatch());
String flowId = "UcastOut2_" + segmentationId + "_" + attachedMac +
securityRulePortMin + securityRuleIpPrefix;
// Add Flow Attributes
if (write) {
// Instantiate the Builders for the OF Actions and Instructions
- InstructionBuilder ib = new InstructionBuilder();
InstructionsBuilder isb = new InstructionsBuilder();
List<Instruction> instructionsList = Lists.newArrayList();
- ib = this.getMutablePipelineInstructionBuilder();
+ InstructionBuilder ib = this.getMutablePipelineInstructionBuilder();
ib.setOrder(0);
ib.setKey(new InstructionKey(0));
instructionsList.add(ib.build());
isb.setInstruction(instructionsList);
- logger.debug("Instructions contain: {}", ib.getInstruction());
+ LOG.debug("Instructions contain: {}", ib.getInstruction());
// Add InstructionsBuilder to FlowBuilder
flowBuilder.setInstructions(isb.build());
writeFlow(flowBuilder, nodeBuilder);
.createDmacIpTcpSynMatch(matchBuilder, new MacAddress(attachedMac), null, null).build());
flowBuilder.setMatch(MatchUtils
.createTunnelIDMatch(matchBuilder, new BigInteger(segmentationId)).build());
- logger.debug("MatchBuilder contains: {}", flowBuilder.getMatch());
+ LOG.debug("MatchBuilder contains: {}", flowBuilder.getMatch());
String flowId = "UcastOut_" + segmentationId + "_" +
attachedMac + "_AllowTCPSynPrefix_" + securityRuleProtcol;
if (write) {
// Instantiate the Builders for the OF Actions and Instructions
- InstructionBuilder ib = new InstructionBuilder();
InstructionsBuilder isb = new InstructionsBuilder();
List<Instruction> instructionsList = Lists.newArrayList();
- ib = this.getMutablePipelineInstructionBuilder();
+ InstructionBuilder ib = this.getMutablePipelineInstructionBuilder();
ib.setOrder(1);
ib.setKey(new InstructionKey(1));
instructionsList.add(ib.build());
isb.setInstruction(instructionsList);
- logger.debug("Instructions contain: {}", ib.getInstruction());
+ LOG.debug("Instructions contain: {}", ib.getInstruction());
// Add InstructionsBuilder to FlowBuilder
flowBuilder.setInstructions(isb.build());
flowBuilder.setMatch(MatchUtils.createDmacTcpPortWithFlagMatch(matchBuilder,
attachedMac, Constants.TCP_SYN, segmentationId).build());
- logger.debug("MatchBuilder contains: {}", flowBuilder.getMatch());
+ LOG.debug("MatchBuilder contains: {}", flowBuilder.getMatch());
String flowId = "PortSec_TCP_Syn_Default_Drop_" + segmentationId + "_" + attachedMac;
flowBuilder.setId(new FlowId(flowId));
FlowKey key = new FlowKey(new FlowId(flowId));
// Add InstructionBuilder to the Instruction(s)Builder List
isb.setInstruction(instructions);
- logger.debug("Instructions contain: {}", ib.getInstruction());
+ LOG.debug("Instructions contain: {}", ib.getInstruction());
// Add InstructionsBuilder to FlowBuilder
flowBuilder.setInstructions(isb.build());
writeFlow(flowBuilder, nodeBuilder);
boolean write, String securityRuleIpPrefix, Integer protoPortMatchPriority) {
String nodeName = Constants.OPENFLOW_NODE_PREFIX + dpidLong;
- Ipv4Prefix srcIpPrefix = new Ipv4Prefix(securityRuleIpPrefix);
MatchBuilder matchBuilder = new MatchBuilder();
NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
FlowBuilder flowBuilder = new FlowBuilder();
flowBuilder.setMatch(MatchUtils.createTunnelIDMatch(matchBuilder, new BigInteger(segmentationId))
.build());
if (securityRuleIpPrefix != null) {
+ Ipv4Prefix srcIpPrefix = new Ipv4Prefix(securityRuleIpPrefix);
flowBuilder.setMatch(MatchUtils
.createDmacIpTcpSynMatch(matchBuilder, new MacAddress(attachedMac), null, srcIpPrefix)
.build());
.build());
}
- logger.debug("MatchBuilder contains: {}", flowBuilder.getMatch());
+ LOG.debug("MatchBuilder contains: {}", flowBuilder.getMatch());
String flowId = "IngressProto_ACL_" + segmentationId + "_" +
attachedMac + "_Permit_" + securityRuleIpPrefix;
// Add Flow Attributes
if (write) {
// Instantiate the Builders for the OF Actions and Instructions
- InstructionBuilder ib = new InstructionBuilder();
InstructionsBuilder isb = new InstructionsBuilder();
List<Instruction> instructionsList = Lists.newArrayList();
- ib = this.getMutablePipelineInstructionBuilder();
+ InstructionBuilder ib = this.getMutablePipelineInstructionBuilder();
ib.setOrder(1);
ib.setKey(new InstructionKey(0));
instructionsList.add(ib.build());
isb.setInstruction(instructionsList);
- logger.debug("Instructions contain: {}", ib.getInstruction());
+ LOG.debug("Instructions contain: {}", ib.getInstruction());
// Add InstructionsBuilder to FlowBuilder
flowBuilder.setInstructions(isb.build());
writeFlow(flowBuilder, nodeBuilder);
}
}
+ /**
+ * 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 write is write or delete
+ * @param protoPortMatchPriority the priority
+ */
+ private void ingressACLDHCPAllowServerTraffic(Long dpidLong, String segmentationId, String dhcpMacAddress,
+ boolean write, Integer protoPortMatchPriority) {
+
+ String nodeName = Constants.OPENFLOW_NODE_PREFIX + dpidLong;
+ MatchBuilder matchBuilder = new MatchBuilder();
+ NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
+ FlowBuilder flowBuilder = new FlowBuilder();
+
+ flowBuilder.setMatch(MatchUtils.createDHCPServerMatch(matchBuilder, dhcpMacAddress, 67, 68).build());
+ LOG.debug("ingressACLDHCPAllowServerTraffic: MatchBuilder contains: {}", flowBuilder.getMatch());
+ String flowId = "Ingress_DHCP_Server" + segmentationId + "_" + dhcpMacAddress + "_Permit_";
+ // Add Flow Attributes
+ flowBuilder.setId(new FlowId(flowId));
+ FlowKey key = new FlowKey(new FlowId(flowId));
+ flowBuilder.setStrict(false);
+ flowBuilder.setPriority(protoPortMatchPriority);
+ flowBuilder.setBarrier(true);
+ flowBuilder.setTableId(this.getTable());
+ flowBuilder.setKey(key);
+ flowBuilder.setFlowName(flowId);
+ flowBuilder.setHardTimeout(0);
+ flowBuilder.setIdleTimeout(0);
+
+ if (write) {
+ // Instantiate the Builders for the OF Actions and Instructions
+ InstructionsBuilder isb = new InstructionsBuilder();
+ List<Instruction> instructionsList = Lists.newArrayList();
+
+ InstructionBuilder ib = this.getMutablePipelineInstructionBuilder();
+ ib.setOrder(0);
+ ib.setKey(new InstructionKey(0));
+ instructionsList.add(ib.build());
+ isb.setInstruction(instructionsList);
+
+ LOG.debug("Instructions contain: {}", ib.getInstruction());
+ // 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(IngressAclProvider.class.getName()), this);
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal
*/
+
package org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.services;
import java.math.BigInteger;
import com.google.common.collect.Lists;
public class L2ForwardingService extends AbstractServiceInstance implements ConfigInterface, L2ForwardingProvider {
- private static final Logger logger = LoggerFactory.getLogger(L2ForwardingService.class);
+ private static final Logger LOG = LoggerFactory.getLogger(L2ForwardingService.class);
public L2ForwardingService() {
super(Service.L2_FORWARDING);
}
List<Instruction> instructions = Lists.newArrayList();
InstructionBuilder ib = new InstructionBuilder();
- List<Action> actionList = null;
+ List<Action> actionList;
if (write) {
if (existingInstructions == null) {
/* First time called there should be no instructions.
actionList.add(ab.build());
} else {
/* Subsequent calls require appending any new local ports for this tenant. */
- ApplyActionsCase aac = (ApplyActionsCase) ib.getInstruction();
Instruction in = existingInstructions.get(0);
actionList = (((ApplyActionsCase) in.getInstruction()).getApplyActions().getAction());
boolean removeFlow = true;
if (instructions != null) {
- ApplyActionsCase aac = (ApplyActionsCase) ib.getInstruction();
Instruction in = instructions.get(0);
List<Action> oldActionList = (((ApplyActionsCase) in.getInstruction()).getApplyActions().getAction());
NodeConnectorId ncid = new NodeConnectorId(OPENFLOW + dpidLong + ":" + localPort);
OutputActionCase opAction = (OutputActionCase) action.getAction();
if (opAction.getOutputAction().getOutputNodeConnector().equals(new Uri(ncidEth))) {
actionList.add(action);
- } else if (opAction.getOutputAction().getOutputNodeConnector().equals(new Uri(ncid)) == false) {
+ } else if (!opAction.getOutputAction().getOutputNodeConnector().equals(new Uri(ncid))) {
ab.setAction(action.getAction());
ab.setOrder(index);
ab.setKey(new ActionKey(index));
ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
}
- if (actionList != null && actionList.size() > 2) {
+ if (actionList.size() > 2) {
// Add InstructionBuilder to the Instruction(s)Builder List
InstructionsBuilder isb = new InstructionsBuilder();
isb.setInstruction(instructions);
if (write) {
// Create the OF Actions and Instructions
- InstructionBuilder ib = new InstructionBuilder();
InstructionsBuilder isb = new InstructionsBuilder();
// Instructions List Stores Individual Instructions
List<Instruction> instructions = Lists.newArrayList();
// Call the InstructionBuilder Methods Containing Actions
- ib = this.getMutablePipelineInstructionBuilder();
+ InstructionBuilder ib = this.getMutablePipelineInstructionBuilder();
ib.setOrder(0);
ib.setKey(new InstructionKey(0));
instructions.add(ib.build());
Long dpidLong, Long port ,
List<Instruction> instructions) {
NodeConnectorId ncid = new NodeConnectorId(OPENFLOW + dpidLong + ":" + port);
- logger.debug("createOutputPortInstructions() Node Connector ID is - Type=openflow: DPID={} port={} existingInstructions={}", dpidLong, port, instructions);
+ LOG.debug("createOutputPortInstructions() Node Connector ID is - Type=openflow: DPID={} port={} existingInstructions={}", dpidLong, port, instructions);
List<Action> actionList = Lists.newArrayList();
ActionBuilder ab = new ActionBuilder();
if (in.getInstruction() instanceof ApplyActionsCase) {
existingActions = (((ApplyActionsCase) in.getInstruction()).getApplyActions().getAction());
// Only include output actions
- for (Action action : existingActions)
- if (action.getAction() instanceof OutputActionCase)
+ for (Action action : existingActions) {
+ if (action.getAction() instanceof OutputActionCase) {
actionList.add(action);
+ }
+ }
}
}
/* Create output action for this port*/
ApplyActionsBuilder aab = new ApplyActionsBuilder();
aab.setAction(actionList);
ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
- logger.debug("createOutputPortInstructions() : applyAction {}", aab.build());
+ LOG.debug("createOutputPortInstructions() : applyAction {}", aab.build());
return ib;
}
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal
*/
+
package org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.services;
import org.opendaylight.ovsdb.openstack.netvirt.api.L2RewriteProvider;
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Dave Tucker
*/
package org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.services;
/*
- * Copyright (C) 2014 SDN Hub, LLC.
+ * 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
- *
- * Authors : Srini Seetharaman, Madhu Venugopal
*/
package org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.services;
import org.opendaylight.ovsdb.openstack.netvirt.api.LoadBalancerConfiguration;
import org.opendaylight.ovsdb.openstack.netvirt.api.LoadBalancerConfiguration.LoadBalancerPoolMember;
import org.opendaylight.ovsdb.openstack.netvirt.api.LoadBalancerProvider;
+import org.opendaylight.ovsdb.openstack.netvirt.api.Southbound;
import org.opendaylight.ovsdb.openstack.netvirt.api.Status;
import org.opendaylight.ovsdb.openstack.netvirt.api.StatusCode;
import org.opendaylight.ovsdb.openstack.netvirt.providers.ConfigInterface;
import org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.Service;
import org.opendaylight.ovsdb.utils.mdsal.openflow.ActionUtils;
import org.opendaylight.ovsdb.utils.mdsal.openflow.MatchUtils;
+import org.opendaylight.ovsdb.utils.servicehelper.ServiceHelper;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.PortNumber;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress;
import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
public class LoadBalancerService extends AbstractServiceInstance implements LoadBalancerProvider, ConfigInterface {
- private static final Logger logger = LoggerFactory.getLogger(LoadBalancerProvider.class);
+ 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);
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
LoadBalancerConfiguration lbConfig, LoadBalancerPoolMember member,
org.opendaylight.ovsdb.openstack.netvirt.api.Action action) {
if (lbConfig == null || member == null) {
- logger.error("Null value for LB config {} or Member {}", lbConfig, member);
+ LOG.error("Null value for LB config {} or Member {}", lbConfig, member);
return new Status(StatusCode.BADREQUEST);
}
if (!lbConfig.isValid()) {
- logger.error("LB config is invalid: {}", lbConfig);
+ LOG.error("LB config is invalid: {}", lbConfig);
return new Status(StatusCode.BADREQUEST);
}
- logger.debug("Performing {} rules for member {} with index {} on LB with VIP {} and total members {}",
+ 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 + node.getNodeId().getValue()));
+ nodeBuilder.setId(new NodeId(Constants.OPENFLOW_NODE_PREFIX + getDpid(node)));
nodeBuilder.setKey(new NodeKey(nodeBuilder.getId()));
//Update the multipath rule
@Override
public Status programLoadBalancerRules(Node node, LoadBalancerConfiguration lbConfig,
org.opendaylight.ovsdb.openstack.netvirt.api.Action action) {
- if (lbConfig == null) {
- logger.error("LB config is invalid: {}", lbConfig);
- return new Status(StatusCode.BADREQUEST);
- }
- if (!lbConfig.isValid()) {
- logger.error("LB config is invalid: {}", lbConfig);
+ if (lbConfig == null || !lbConfig.isValid()) {
+ LOG.error("LB config is invalid: {}", lbConfig);
return new Status(StatusCode.BADREQUEST);
}
- logger.debug("Performing {} rules for VIP {} and {} members", action, lbConfig.getVip(), lbConfig.getMembers().size());
+ 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 + node.getNodeId().getValue()));
+ nodeBuilder.setId(new NodeId(Constants.OPENFLOW_NODE_PREFIX + getDpid(node)));
nodeBuilder.setKey(new NodeKey(nodeBuilder.getId()));
if (action.equals(org.opendaylight.ovsdb.openstack.netvirt.api.Action.ADD)) {
// Match Tunnel-ID, VIP, and Reg0==0
if (lbConfig.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VXLAN) ||
- lbConfig.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_GRE))
+ lbConfig.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_GRE)) {
MatchUtils.createTunnelIDMatch(matchBuilder, new BigInteger(lbConfig.getProviderSegmentationId()));
- else if (lbConfig.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VLAN))
+ } else if (lbConfig.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VLAN)) {
MatchUtils.createVlanIdMatch(matchBuilder, new VlanId(Integer.valueOf(lbConfig.getProviderSegmentationId())), true);
- else
+ } 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));
// 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))
+ lbConfig.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_GRE)) {
MatchUtils.createTunnelIDMatch(matchBuilder, new BigInteger(lbConfig.getProviderSegmentationId()));
- else if (lbConfig.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VLAN))
+ } else if (lbConfig.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VLAN)) {
MatchUtils.createVlanIdMatch(matchBuilder, new VlanId(Integer.valueOf(lbConfig.getProviderSegmentationId())), true);
- else
+ } 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),
// Match Tunnel-ID, MemberIP, and Protocol/Port
if (lbConfig.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VXLAN) ||
- lbConfig.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_GRE))
+ lbConfig.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_GRE)) {
MatchUtils.createTunnelIDMatch(matchBuilder, new BigInteger(lbConfig.getProviderSegmentationId()));
- else if (lbConfig.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VLAN))
+ } else if (lbConfig.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VLAN)) {
MatchUtils.createVlanIdMatch(matchBuilder, new VlanId(Integer.valueOf(lbConfig.getProviderSegmentationId())), true);
- else
+ } else {
return; //Should not get here. TODO: Other types
+ }
MatchUtils.createSrcL3IPv4Match(matchBuilder, MatchUtils.iPv4PrefixFromIPv4Address(member.getIP()));
MatchUtils.createSetSrcTcpMatch(matchBuilder, new PortNumber(member.getPort()));
@Override
public void setDependencies(BundleContext bundleContext, ServiceReference serviceReference) {
super.setDependencies(bundleContext.getServiceReference(LoadBalancerProvider.class.getName()), this);
+ southbound =(Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this);
}
@Override
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal, Dave Tucker
*/
package org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.services;
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal, Dave Tucker
*/
package org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.services;
import java.math.BigInteger;
+import java.net.Inet6Address;
import java.net.InetAddress;
import java.util.List;
import com.google.common.collect.Lists;
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);
}
MatchUtils.createTunnelIDMatch(matchBuilder, new BigInteger(sourceSegId));
}
+ 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);
+ new Status(StatusCode.NOTIMPLEMENTED);
+ }
final String prefixString = address.getHostAddress() + "/" + mask;
MatchUtils.createDstL3IPv4Match(matchBuilder, new Ipv4Prefix(prefixString));
--- /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.ovsdb.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<String, byte[]>(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
+ */
+ public Arp setHardwareLength(short value) {
+ hdrFieldsMap.put(HLEN, Unpooled.buffer(1).writeByte(value).array());
+ return this;
+ }
+
+ /**
+ * @param value protocol length in Bytes
+ */
+ 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.ovsdb.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.rev100924.Ipv4Address;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Prefix;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Uri;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.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
+ */
+ public static EthernetMatch createEthernetMatch(MacAddress destinationMacAddress) {
+ return new EthernetMatchBuilder().setEthernetType(
+ new EthernetTypeBuilder().setType(new EtherType(Long.valueOf(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
+ */
+ 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
+ */
+ 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.ovsdb.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.rev100924.Ipv4Address;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.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.ovsdb.openstack.netvirt.providers.openflow13.services.arp;
+
+import javax.annotation.Nullable;
+
+public enum ArpOperation {
+
+ REQUEST(1), REPLY(2);
+
+ private final int intOperation;
+
+ private 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.ovsdb.openstack.netvirt.providers.openflow13.services.arp;
+
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowInput;
+
+/**
+*
+* @author Anil Vishnoi (avishnoi@Brocade.com)
+*
+*/
+
+public final class ArpResolverMetadata {
+
+ private final Ipv4Address gatewayIpAddress;
+ private final Long externalNetworkBridgeDpid;
+ private final Ipv4Address arpRequestSourceIp;
+ private final MacAddress arpRequestSourceMacAddress;
+ private final boolean periodicRefresh;
+ private RemoveFlowInput flowToRemove;
+ private MacAddress gatewayMacAddress;
+
+ public ArpResolverMetadata(final Long externalNetworkBridgeDpid,
+ final Ipv4Address gatewayIpAddress, final Ipv4Address arpRequestSourceIp,
+ final MacAddress arpRequestMacAddress, final boolean periodicRefresh){
+ this.externalNetworkBridgeDpid = externalNetworkBridgeDpid;
+ this.gatewayIpAddress = gatewayIpAddress;
+ this.arpRequestSourceIp = arpRequestSourceIp;
+ this.arpRequestSourceMacAddress = arpRequestMacAddress;
+ this.periodicRefresh = periodicRefresh;
+ }
+
+ public RemoveFlowInput getFlowToRemove() {
+ return flowToRemove;
+ }
+ public boolean isPeriodicRefresh() {
+ return periodicRefresh;
+ }
+ public void setFlowToRemove(RemoveFlowInput flowToRemove) {
+ this.flowToRemove = flowToRemove;
+ }
+ public Ipv4Address getGatewayIpAddress() {
+ return gatewayIpAddress;
+ }
+ public MacAddress getGatewayMacAddress() {
+ return gatewayMacAddress;
+ }
+ public void setGatewayMacAddress(MacAddress gatewayMacAddress) {
+ this.gatewayMacAddress = gatewayMacAddress;
+ }
+
+ public Long getExternalNetworkBridgeDpid() {
+ return externalNetworkBridgeDpid;
+ }
+ public Ipv4Address getArpRequestSourceIp() {
+ return arpRequestSourceIp;
+ }
+ public MacAddress getArpRequestMacAddress() {
+ return arpRequestSourceMacAddress;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ 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);
+ 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 (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;
+ 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.ovsdb.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.ovsdb.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.rev100924.Ipv4Address;
+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, egressNc);
+ }
+
+ private NodeConnectorId createNodeConnectorId(String connectorId, NodeId nodeId) {
+ StringBuilder stringId = new StringBuilder(nodeId.getValue()).append(":").append(connectorId);
+ return new NodeConnectorId(stringId.toString());
+ }
+
+ /**
+ * 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 egressNc the path to node connector from where the ARP packet will be sent
+ * @return future result about success of packet-out
+ */
+ public ListenableFuture<RpcResult<Void>> sendArp(ArpMessageAddress senderAddress, Ipv4Address tpa,
+ InstanceIdentifier<NodeConnector> egressNc) {
+ checkNotNull(senderAddress);
+ checkNotNull(tpa);
+ checkNotNull(egressNc);
+ final Ethernet arpFrame = createArpFrame(senderAddress, tpa);
+ 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) {
+ byte[] senderMac = ArpUtils.macToBytes(senderAddress.getHardwareAddress());
+ byte[] senderIp = ArpUtils.ipToBytes(senderAddress.getProtocolAddress());
+ byte[] 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.ovsdb.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.rev100924.Ipv4Address;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.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
+ */
+ 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
+ */
+ 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.ovsdb.openstack.netvirt.providers.openflow13.services.arp;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import java.math.BigInteger;
+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.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+
+import javax.annotation.Nullable;
+
+import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.ProviderContext;
+import org.opendaylight.openflowplugin.api.OFConstants;
+import org.opendaylight.ovsdb.openstack.netvirt.api.GatewayMacResolver;
+import org.opendaylight.ovsdb.openstack.netvirt.providers.ConfigInterface;
+import org.opendaylight.ovsdb.openstack.netvirt.providers.NetvirtProvidersProvider;
+import org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.AbstractServiceInstance;
+import org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.Service;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.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;
+
+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;
+
+/**
+ *
+ * @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 short TABEL_FOR_ARP_FLOW = 0;
+ 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 SalFlowService flowService;
+ private final AtomicLong flowCookie = new AtomicLong();
+ private final ConcurrentMap<Ipv4Address, ArpResolverMetadata> gatewayToArpMetadataMap =
+ new ConcurrentHashMap<Ipv4Address, ArpResolverMetadata>();
+ private final int ARP_WATCH_BROTHERS = 10;
+ private final int WAIT_CYCLES = 3;
+ private final int PER_CYCLE_WAIT_DURATION = 1000;
+ private final int REFRESH_INTERVAL = 10;
+ private final ListeningExecutorService arpWatcherWall = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(ARP_WATCH_BROTHERS));
+ private final ScheduledExecutorService gatewayMacRefresherPool = Executors.newScheduledThreadPool(1);
+ private final ScheduledExecutorService refreshRequester = Executors.newSingleThreadScheduledExecutor();
+ private AtomicBoolean initializationDone = new AtomicBoolean(false);
+
+ 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(){
+ super(Service.GATEWAY_RESOLVER);
+ }
+
+ public GatewayMacResolverService(Service service){
+ super(service);
+ }
+
+ private void init(){
+ if(!initializationDone.get()){
+ initializationDone.set(true);
+ ProviderContext providerContext = NetvirtProvidersProvider.getProviderContext();
+ checkNotNull(providerContext);
+ PacketProcessingService packetProcessingService = providerContext.getRpcService(PacketProcessingService.class);
+ 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;
+ }
+ flowService = providerContext.getRpcService(SalFlowService.class);
+ refreshRequester.scheduleWithFixedDelay(new Runnable(){
+
+ @Override
+ public void run() {
+ if (!gatewayToArpMetadataMap.isEmpty()){
+ for(final Entry<Ipv4Address, ArpResolverMetadata> gatewayToArpMetadataEntry : gatewayToArpMetadataMap.entrySet()){
+ final Ipv4Address gatewayIp = gatewayToArpMetadataEntry.getKey();
+ final ArpResolverMetadata gatewayMetaData = gatewayToArpMetadataEntry.getValue();
+ gatewayMacRefresherPool.schedule(new Runnable(){
+
+ @Override
+ public void run() {
+
+ 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() );
+ }
+
+ LOG.debug("Refresh Gateway Mac for gateway {} using source ip {} and mac {} for ARP request",
+ gatewayIp.getValue(),gatewayMetaData.getArpRequestSourceIp().getValue(),gatewayMetaData.getArpRequestMacAddress().getValue());
+
+ sendGatewayArpRequest(externalNetworkBridge,gatewayIp,gatewayMetaData.getArpRequestSourceIp(), gatewayMetaData.getArpRequestMacAddress());
+ }
+ }, 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
+ * NOTE:Periodic refresh is not supported yet.
+ * @param gatewayIp Resolve MAC address of this Gateway Ip
+ * @return Future object
+ */
+ @Override
+ public ListenableFuture<MacAddress> resolveMacAddress( final Long externalNetworkBridgeDpid, final Ipv4Address gatewayIp,
+ final Ipv4Address sourceIpAddress, final MacAddress sourceMacAddress, final Boolean periodicRefresh){
+ 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(new Callable<MacAddress>(){
+
+ @Override
+ public MacAddress call() throws Exception {
+ return gatewayToArpMetadataMap.get(gatewayIp).getGatewayMacAddress();
+ }
+ });
+ }
+ }else{
+ gatewayToArpMetadataMap.put(gatewayIp,new ArpResolverMetadata(
+ externalNetworkBridgeDpid, gatewayIp,sourceIpAddress,sourceMacAddress,periodicRefresh));
+ }
+
+
+ final Node externalNetworkBridge = getExternalBridge(externalNetworkBridgeDpid);
+ if(externalNetworkBridge == null){
+ LOG.error("MAC address for gateway {} can not be resolved, because external bridge {} "
+ + "is not connected to controller.",gatewayIp.getValue(),externalNetworkBridgeDpid );
+ return null;
+ }
+
+ sendGatewayArpRequest(externalNetworkBridge,gatewayIp,sourceIpAddress, sourceMacAddress);
+
+ //Wait for MacAddress population in cache
+ return waitForMacAddress(gatewayIp);
+ }
+
+ private Node getExternalBridge(final Long externalNetworkBridgeDpid){
+ final String nodeName = OPENFLOW + externalNetworkBridgeDpid;
+
+ return getOpenFlowNode(nodeName);
+ }
+
+ 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);
+
+ //cache metadata
+ gatewayToArpMetadataMap.get(gatewayIp).setFlowToRemove(
+ new RemoveFlowInputBuilder(arpReplyToControllerFlow).setNode(nodeRef).build());
+
+ //Broadcast 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, 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(new Callable<MacAddress>(){
+
+ @Override
+ public MacAddress call() throws Exception {
+ 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()){
+ return gatewayToArpMetadataMap.remove(gatewayIp).getGatewayMacAddress();
+ }
+ return arpResolverMetadata.getGatewayMacAddress();
+ }
+ }
+ return null;
+ }
+ });
+ }
+
+ private static @Nullable Ipv4Address getIPv4Addresses(IpAddress ipAddress) {
+ if (ipAddress.getIpv4Address() == null) {
+ return null;
+ }
+ return ipAddress.getIpv4Address();
+ }
+
+ private Flow createArpReplyToControllerFlow(final ArpMessageAddress senderAddress, final Ipv4Address ipForRequestedMac) {
+ checkNotNull(senderAddress);
+ checkNotNull(ipForRequestedMac);
+ FlowBuilder arpFlow = new FlowBuilder().setTableId(TABEL_FOR_ARP_FLOW)
+ .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(senderAddress, ipForRequestedMac));
+ return arpFlow.build();
+ }
+
+ private FlowId createFlowId(ArpMessageAddress senderAddress, 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);
+ flowService.removeFlow(candidateGatewayIp.getFlowToRemove());
+ }
+ }
+ }
+
+ @Override
+ public void setDependencies(BundleContext bundleContext,
+ ServiceReference serviceReference) {
+ super.setDependencies(bundleContext.getServiceReference(GatewayMacResolver.class.getName()), this);
+
+ }
+
+ @Override
+ public void setDependencies(Object impl) {}
+
+ @Override
+ public void stopPeriodicRefresh(Ipv4Address gatewayIp) {
+ init();
+ gatewayToArpMetadataMap.remove(gatewayIp);
+ }
+
+}
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyShort;
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 org.opendaylight.ovsdb.utils.servicehelper.ServiceHelper;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbTerminationPointAugmentation;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
-//import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
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;
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<NodeId, Node>();
+ 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(nodeId.getValue()).thenReturn(ID);
Node node = mock(Node.class);
when(node.getNodeId()).thenReturn(nodeId);
- Map<NodeId, Node> nodes = new HashMap<NodeId, Node>();
+ Map<NodeId, Node> nodes = new HashMap<>();
nodes.put(mock(NodeId.class), node);
when(nodeCacheManager.getOvsdbNodes()).thenReturn(nodes);
Southbound southbound = mock(Southbound.class);
when(southbound.getOptionsValue(any(List.class), anyString())).thenReturn(IP);
OvsdbTerminationPointAugmentation intf = mock(OvsdbTerminationPointAugmentation.class);
when(intf.getName()).thenReturn(INTF);
- List<String> intfs = new ArrayList<String>();
+ List<String> intfs = new ArrayList<>();
intfs.add(INTF);
BridgeConfigurationManager bridgeConfigurationManager = mock(BridgeConfigurationManager.class);
when(bridgeConfigurationManager.getAllPhysicalInterfaceNames(any(Node.class))).thenReturn(intfs);
BundleContext bundleContext = mock(BundleContext.class);
when(bundleContext.getServiceReference(NetworkingProvider.class.getName())).thenReturn(mock(ServiceReference.class));
- MemberModifier.field(OF13Provider.class, "bundleContext").set(of13Provider , bundleContext);
+ MemberModifier.field(OF13Provider.class, "bundleContext").set(of13Provider, bundleContext);
of13Provider.setDependencies(networkingProviderManager);
- assertEquals("Error, did not return the correct object", getField("networkingProviderManager"), networkingProviderManager);
-}
+ verify(networkingProviderManager).providerAdded(any(ServiceReference.class), same(of13Provider));
+ }
private Object getField(String fieldName) throws Exception {
Field field = OF13Provider.class.getDeclaredField(fieldName);
import org.opendaylight.ovsdb.openstack.netvirt.api.Action;
import org.opendaylight.ovsdb.openstack.netvirt.api.LoadBalancerConfiguration;
import org.opendaylight.ovsdb.openstack.netvirt.api.LoadBalancerConfiguration.LoadBalancerPoolMember;
+import org.opendaylight.ovsdb.openstack.netvirt.api.Southbound;
import org.opendaylight.ovsdb.openstack.netvirt.api.Status;
import org.opendaylight.ovsdb.openstack.netvirt.api.StatusCode;
import org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.PipelineOrchestrator;
import org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.Service;
-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.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import com.google.common.util.concurrent.CheckedFuture;
+import org.powermock.api.support.membermodification.MemberModifier;
/**
* Unit test fort {@link LoadBalancerService}
when(orchestrator.getNextServiceInPipeline(any(Service.class))).thenReturn(Service.ARP_RESPONDER);
- Map<String, LoadBalancerPoolMember> members = new HashMap<String, LoadBalancerPoolMember>();
+ Map<String, LoadBalancerPoolMember> members = new HashMap<>();
members.put("key", member);
when(lbConfig.isValid()).thenReturn(true);
when(member.getIndex()).thenReturn(1);
when(member.getMAC()).thenReturn(MAC_ADDRESS);
- NodeId nodeId = mock(NodeId.class);
- when(nodeId.getValue()).thenReturn("id");
-
- when(node.getNodeId()).thenReturn(nodeId);
+ Southbound southbound = mock(Southbound.class);
+ when(southbound.getDataPathId(any(Node.class))).thenReturn(Long.valueOf(123));
+ MemberModifier.field(LoadBalancerService.class, "southbound").set(loadBalancerService, southbound);
}
/**
* Test method {@link LoadBalancerService#programLoadBalancerPoolMemberRules(Node, LoadBalancerConfiguration, LoadBalancerPoolMember, Action)}
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
- <dependency>
- <groupId>org.apache.felix</groupId>
- <artifactId>org.apache.felix.dependencymanager</artifactId>
- </dependency>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.core</artifactId>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-common-api</artifactId>
</dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-common-util</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-core-api</artifactId>
- </dependency>
<dependency>
<groupId>org.opendaylight.neutron</groupId>
<artifactId>neutron-spi</artifactId>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-common</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>concepts</artifactId>
+ </dependency>
<dependency>
<groupId>org.opendaylight.yangtools.model</groupId>
<artifactId>ietf-inet-types</artifactId>
<groupId>org.opendaylight.yangtools.model</groupId>
<artifactId>ietf-topology</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools.model</groupId>
+ <artifactId>opendaylight-l2-types</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools.model</groupId>
+ <artifactId>ietf-yang-types-20130715</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools.model</groupId>
+ <artifactId>ietf-yang-types</artifactId>
+ </dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.powermock</groupId>
+ <artifactId>powermock-api-support</artifactId>
+ <version>${powermock.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.powermock</groupId>
+ <artifactId>powermock-reflect</artifactId>
+ <version>${powermock.version}</version>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${sonar-jacoco-listeners.version}</version>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-simple</artifactId>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<build>
<plugins>
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Dave Tucker, Flavio Fernandes
*/
package org.opendaylight.ovsdb.openstack.netvirt;
@Override
public boolean equals(Object obj) {
- if (this == obj)
+ if (this == obj) {
return true;
- if (obj == null)
+ }
+ if (obj == null) {
return false;
- if (getClass() != obj.getClass())
+ }
+ if (getClass() != obj.getClass()) {
return false;
+ }
AbstractEvent other = (AbstractEvent) obj;
if (handlerType == null) {
- if (other.handlerType != null)
+ if (other.handlerType != null) {
return false;
- } else if (!handlerType.equals(other.handlerType))
+ }
+ } else if (!handlerType.equals(other.handlerType)) {
return false;
+ }
if (action == null) {
- if (other.action != null)
+ if (other.action != null) {
return false;
- } else if (!action.equals(other.action))
+ }
+ } else if (!action.equals(other.action)) {
return false;
+ }
return true;
}
}
/*
- * Copyright (C) 2013 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal, Brent Salisbury
*/
+
package org.opendaylight.ovsdb.openstack.netvirt;
import org.opendaylight.ovsdb.openstack.netvirt.api.EventDispatcher;
* handlers.
*/
public abstract class AbstractHandler {
- static final Logger logger = LoggerFactory.getLogger(AbstractHandler.class);
-
- /*public AbstractHandler() {
- logger.info(">>>>> init {}", this.getClass());
- }*/
+ 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;
- /*void init() {
- logger.info(">>>>> init {}", this.getClass());
- }*/
-
/**
* 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 final int getException(Status status) {
- int result = HttpURLConnection.HTTP_INTERNAL_ERROR;
-
+ protected static int getException(Status status) {
assert !status.isSuccess();
StatusCode code = status.getCode();
- logger.debug(" Exception code - {}, description - {}",
+ LOG.debug(" Exception code - {}, description - {}",
code, status.getDescription());
- if (code == StatusCode.BADREQUEST) {
- result = HttpURLConnection.HTTP_BAD_REQUEST;
- } else if (code == StatusCode.CONFLICT) {
- result = HttpURLConnection.HTTP_CONFLICT;
- } else if (code == StatusCode.NOTACCEPTABLE) {
- result = HttpURLConnection.HTTP_NOT_ACCEPTABLE;
- } else if (code == StatusCode.NOTFOUND) {
- result = HttpURLConnection.HTTP_NOT_FOUND;
- } else {
- result = HttpURLConnection.HTTP_INTERNAL_ERROR;
+ 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;
}
-
- return result;
}
/**
* @see org.opendaylight.ovsdb.openstack.netvirt.api.EventDispatcher
*/
protected void enqueueEvent(AbstractEvent abstractEvent) {
- logger.info("enqueueEvent: evenDispatcher: {} - {}", eventDispatcher, abstractEvent);
+ LOG.info("enqueueEvent: evenDispatcher: {} - {}", eventDispatcher, abstractEvent);
Preconditions.checkNotNull(eventDispatcher);
eventDispatcher.enqueueEvent(abstractEvent);
}
+/*
+ * 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.ovsdb.openstack.netvirt;
import java.util.ArrayList;
public class ConfigActivator implements BundleActivator {
private static final Logger LOG = LoggerFactory.getLogger(ConfigActivator.class);
- private List<ServiceRegistration<?>> registrations = new ArrayList<ServiceRegistration<?>>();
+ private List<ServiceRegistration<?>> registrations = new ArrayList<>();
+ private List<Object> services = new ArrayList<>();
private ProviderContext providerContext;
- private ServiceTracker iNeutronNetworkCRUDTracker;
- private ServiceTracker iNeutronPortCRUDTracker;
- private ServiceTracker iNeutronLoadBalancerCRUDTracker;
- private ServiceTracker iNeutronLoadBalancerPoolCRUDTracker;
- private ServiceTracker iNeutronSubnetCRUDTracker;
- private ServiceTracker loadBalancerProviderTracker;
- private ServiceTracker arpProviderTracker;
- private ServiceTracker inboundNatProviderTracker;
- private ServiceTracker outboundNatProviderTracker;
- private ServiceTracker routingProviderTracker;
- private ServiceTracker l3ForwardingProviderTracker;
public ConfigActivator(ProviderContext providerContext) {
this.providerContext = providerContext;
registerService(context, new String[] {VlanConfigurationCache.class.getName()},
null, vlanConfigurationCache);
- Dictionary<String, Object> floatingIPHandlerProperties = new Hashtable<>();
- floatingIPHandlerProperties.put(Constants.EVENT_HANDLER_TYPE_PROPERTY,
- AbstractEvent.HandlerType.NEUTRON_FLOATING_IP);
FloatingIPHandler floatingIPHandler = new FloatingIPHandler();
- registerService(context,
- new String[] {INeutronFloatingIPAware.class.getName(), AbstractHandler.class.getName()},
- floatingIPHandlerProperties, floatingIPHandler);
+ registerAbstractHandlerService(context, new Class[] {INeutronFloatingIPAware.class},
+ AbstractEvent.HandlerType.NEUTRON_FLOATING_IP, floatingIPHandler);
- Dictionary<String, Object> networkHandlerProperties = new Hashtable<>();
- networkHandlerProperties.put(Constants.EVENT_HANDLER_TYPE_PROPERTY, AbstractEvent.HandlerType.NEUTRON_NETWORK);
final NetworkHandler networkHandler = new NetworkHandler();
- registerService(context,
- new String[]{INeutronNetworkAware.class.getName(), AbstractHandler.class.getName()},
- networkHandlerProperties, networkHandler);
+ registerAbstractHandlerService(context, new Class[] {INeutronNetworkAware.class},
+ AbstractEvent.HandlerType.NEUTRON_NETWORK, networkHandler);
- Dictionary<String, Object> subnetHandlerProperties = new Hashtable<>();
- subnetHandlerProperties.put(Constants.EVENT_HANDLER_TYPE_PROPERTY, AbstractEvent.HandlerType.NEUTRON_SUBNET);
SubnetHandler subnetHandler = new SubnetHandler();
- registerService(context,
- new String[] {INeutronSubnetAware.class.getName(), AbstractHandler.class.getName()},
- subnetHandlerProperties, subnetHandler);
+ registerAbstractHandlerService(context, new Class[] {INeutronSubnetAware.class},
+ AbstractEvent.HandlerType.NEUTRON_SUBNET, subnetHandler);
- Dictionary<String, Object> portHandlerProperties = new Hashtable<>();
- portHandlerProperties.put(Constants.EVENT_HANDLER_TYPE_PROPERTY, AbstractEvent.HandlerType.NEUTRON_PORT);
PortHandler portHandler = new PortHandler();
- registerService(context,
- new String[]{INeutronPortAware.class.getName(), AbstractHandler.class.getName()},
- portHandlerProperties, portHandler);
+ registerAbstractHandlerService(context, new Class[] {INeutronPortAware.class},
+ AbstractEvent.HandlerType.NEUTRON_PORT, portHandler);
- Dictionary<String, Object> routerHandlerProperties = new Hashtable<>();
- routerHandlerProperties.put(Constants.EVENT_HANDLER_TYPE_PROPERTY, AbstractEvent.HandlerType.NEUTRON_ROUTER);
RouterHandler routerHandler = new RouterHandler();
- registerService(context,
- new String[]{INeutronRouterAware.class.getName(), AbstractHandler.class.getName()},
- routerHandlerProperties, routerHandler);
+ registerAbstractHandlerService(context, new Class[] {INeutronRouterAware.class},
+ AbstractEvent.HandlerType.NEUTRON_ROUTER, routerHandler);
- Dictionary<String, Object> southboundHandlerProperties = new Hashtable<>();
- southboundHandlerProperties.put(Constants.EVENT_HANDLER_TYPE_PROPERTY, AbstractEvent.HandlerType.SOUTHBOUND);
SouthboundHandler southboundHandler = new SouthboundHandler();
- registerService(context,
- new String[]{OvsdbInventoryListener.class.getName(),
- NodeCacheListener.class.getName(),
- AbstractHandler.class.getName()},
- southboundHandlerProperties, southboundHandler);
-
- Dictionary<String, Object> lbaasHandlerProperties = new Hashtable<>();
- lbaasHandlerProperties.put(Constants.EVENT_HANDLER_TYPE_PROPERTY,
- AbstractEvent.HandlerType.NEUTRON_LOAD_BALANCER);
+ registerAbstractHandlerService(context, new Class[] {OvsdbInventoryListener.class, NodeCacheListener.class},
+ AbstractEvent.HandlerType.SOUTHBOUND, southboundHandler);
+
final LBaaSHandler lBaaSHandler = new LBaaSHandler();
- registerService(context,
- new String[]{INeutronLoadBalancerAware.class.getName(),
- NodeCacheListener.class.getName(), AbstractHandler.class.getName()},
- lbaasHandlerProperties, lBaaSHandler);
+ registerAbstractHandlerService(context, new Class[] {INeutronLoadBalancerAware.class, NodeCacheListener.class},
+ AbstractEvent.HandlerType.NEUTRON_LOAD_BALANCER, lBaaSHandler);
- Dictionary<String, Object> lbaasPoolHandlerProperties = new Hashtable<>();
- lbaasPoolHandlerProperties.put(Constants.EVENT_HANDLER_TYPE_PROPERTY,
- AbstractEvent.HandlerType.NEUTRON_LOAD_BALANCER_POOL);
final LBaaSPoolHandler lBaaSPoolHandler = new LBaaSPoolHandler();
- registerService(context,
- new String[]{INeutronLoadBalancerPoolAware.class.getName(),
- AbstractHandler.class.getName()}, lbaasPoolHandlerProperties, lBaaSPoolHandler);
+ registerAbstractHandlerService(context, new Class[] {INeutronLoadBalancerPoolAware.class},
+ AbstractEvent.HandlerType.NEUTRON_LOAD_BALANCER_POOL, lBaaSPoolHandler);
- Dictionary<String, Object> lbaasPoolMemberHandlerProperties = new Hashtable<>();
- lbaasPoolMemberHandlerProperties.put(Constants.EVENT_HANDLER_TYPE_PROPERTY,
- AbstractEvent.HandlerType.NEUTRON_LOAD_BALANCER_POOL_MEMBER);
final LBaaSPoolMemberHandler lBaaSPoolMemberHandler = new LBaaSPoolMemberHandler();
- registerService(context,
- new String[]{INeutronLoadBalancerPoolMemberAware.class.getName(),
- AbstractHandler.class.getName()}, lbaasPoolMemberHandlerProperties, lBaaSPoolMemberHandler);
+ registerAbstractHandlerService(context, new Class[] {INeutronLoadBalancerPoolMemberAware.class},
+ AbstractEvent.HandlerType.NEUTRON_LOAD_BALANCER_POOL_MEMBER, lBaaSPoolMemberHandler);
- Dictionary<String, Object> portSecurityHandlerProperties = new Hashtable<>();
- portSecurityHandlerProperties.put(Constants.EVENT_HANDLER_TYPE_PROPERTY,
- AbstractEvent.HandlerType.NEUTRON_PORT_SECURITY);
PortSecurityHandler portSecurityHandler = new PortSecurityHandler();
- registerService(context,
- new String[]{INeutronSecurityRuleAware.class.getName(),
- INeutronSecurityGroupAware.class.getName(), AbstractHandler.class.getName()},
- portSecurityHandlerProperties, portSecurityHandler);
+ registerAbstractHandlerService(context,
+ new Class[] {INeutronSecurityRuleAware.class, INeutronSecurityGroupAware.class},
+ AbstractEvent.HandlerType.NEUTRON_PORT_SECURITY, portSecurityHandler);
final SecurityServicesImpl securityServices = new SecurityServicesImpl();
registerService(context,
new String[]{SecurityServicesManager.class.getName()}, null, securityServices);
- Dictionary<String, Object> fWaasHandlerProperties = new Hashtable<>();
- fWaasHandlerProperties.put(Constants.EVENT_HANDLER_TYPE_PROPERTY, AbstractEvent.HandlerType.NEUTRON_FWAAS);
FWaasHandler fWaasHandler = new FWaasHandler();
- registerService(context,
- new String[]{INeutronFirewallAware.class.getName(),
- INeutronFirewallRuleAware.class.getName(), INeutronFirewallPolicyAware.class.getName(),
- AbstractHandler.class.getName()}, fWaasHandlerProperties, fWaasHandler);
+ registerAbstractHandlerService(context,
+ new Class[] {INeutronFirewallAware.class, INeutronFirewallRuleAware.class, INeutronFirewallPolicyAware.class},
+ AbstractEvent.HandlerType.NEUTRON_FWAAS, fWaasHandler);
ProviderNetworkManagerImpl providerNetworkManager = new ProviderNetworkManagerImpl();
registerService(context,
registerService(context,
new String[]{Southbound.class.getName()}, null, southbound);
- Dictionary<String, Object> nodeCacheManagerProperties = new Hashtable<>();
- nodeCacheManagerProperties.put(Constants.EVENT_HANDLER_TYPE_PROPERTY, AbstractEvent.HandlerType.NODE);
NodeCacheManagerImpl nodeCacheManager = new NodeCacheManagerImpl();
- registerService(context,
- new String[]{NodeCacheManager.class.getName(), AbstractHandler.class.getName()},
- nodeCacheManagerProperties, nodeCacheManager);
+ registerAbstractHandlerService(context, new Class[] {NodeCacheManager.class},
+ AbstractEvent.HandlerType.NODE, nodeCacheManager);
OvsdbInventoryServiceImpl ovsdbInventoryService = new OvsdbInventoryServiceImpl(providerContext);
registerService(context,
new String[] {OvsdbInventoryService.class.getName()}, null, ovsdbInventoryService);
- ovsdbInventoryService.setDependencies(context, null);
- nodeCacheManager.setDependencies(context, null);
- openstackRouter.setDependencies(context, null);
- neutronL3Adapter.setDependencies(context, null);
- eventDispatcher.setDependencies(context, null);
- providerNetworkManager.setDependencies(context, null);
- fWaasHandler.setDependencies(context, null);
- securityServices.setDependencies(context, null);
- portSecurityHandler.setDependencies(context, null);
- lBaaSPoolMemberHandler.setDependencies(context, null);
- lBaaSPoolHandler.setDependencies(context, null);
- lBaaSHandler.setDependencies(context, null);
- southboundHandler.setDependencies(context, null);
- routerHandler.setDependencies(context, null);
- portHandler.setDependencies(context, null);
- subnetHandler.setDependencies(context, null);
- networkHandler.setDependencies(context, null);
- floatingIPHandler.setDependencies(context, null);
- vlanConfigurationCache.setDependencies(context, null);
- tenantNetworkManager.setDependencies(context, null);
- bridgeConfigurationManager.setDependencies(context, null);
- configurationService.setDependencies(context, null);
+ // Call .setDependencies() starting with the last service registered
+ for (int i = services.size() - 1; i >= 0; i--) {
+ Object service = services.get(i);
+ if (service instanceof ConfigInterface) {
+ ((ConfigInterface) service).setDependencies(context, null);
+ }
+ }
// 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
- @SuppressWarnings("unchecked")
- ServiceTracker iNeutronNetworkCRUDTracker = 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) {
- tenantNetworkManager.setDependencies(service);
- networkHandler.setDependencies(service);
- lBaaSHandler.setDependencies(service);
- lBaaSPoolHandler.setDependencies(service);
- lBaaSPoolMemberHandler.setDependencies(service);
- neutronL3Adapter.setDependencies(service);
- }
- return service;
- }
- };
- iNeutronNetworkCRUDTracker.open();
- this.iNeutronNetworkCRUDTracker = iNeutronNetworkCRUDTracker;
-
- @SuppressWarnings("unchecked")
- ServiceTracker iNeutronSubnetCRUDTracker = new ServiceTracker(context, INeutronSubnetCRUD.class, null) {
- @Override
- public Object addingService(ServiceReference reference) {
- LOG.info("addingService INeutronSubnetCRUD");
- INeutronSubnetCRUD service = (INeutronSubnetCRUD) context.getService(reference);
- if (service != null) {
- lBaaSHandler.setDependencies(service);
- lBaaSPoolHandler.setDependencies(service);
- lBaaSPoolMemberHandler.setDependencies(service);
- neutronL3Adapter.setDependencies(service);
- }
- return service;
- }
- };
- iNeutronSubnetCRUDTracker.open();
- this.iNeutronSubnetCRUDTracker = iNeutronSubnetCRUDTracker;
-
- @SuppressWarnings("unchecked")
- ServiceTracker iNeutronPortCRUDTracker = new ServiceTracker(context, INeutronPortCRUD.class, null) {
- @Override
- public Object addingService(ServiceReference reference) {
- LOG.info("addingService INeutronPortCRUD");
- INeutronPortCRUD service = (INeutronPortCRUD) context.getService(reference);
- if (service != null) {
- tenantNetworkManager.setDependencies(service);
- lBaaSHandler.setDependencies(service);
- lBaaSPoolHandler.setDependencies(service);
- lBaaSPoolMemberHandler.setDependencies(service);
- securityServices.setDependencies(service);
- neutronL3Adapter.setDependencies(service);
- }
- return service;
- }
- };
- iNeutronPortCRUDTracker.open();
- this.iNeutronPortCRUDTracker = iNeutronPortCRUDTracker;
-
- @SuppressWarnings("unchecked")
- ServiceTracker iNeutronLoadBalancerCRUDTracker = new ServiceTracker(context,
- INeutronLoadBalancerCRUD.class, null) {
- @Override
- public Object addingService(ServiceReference reference) {
- LOG.info("addingService INeutronLoadBalancerCRUD");
- INeutronLoadBalancerCRUD service = (INeutronLoadBalancerCRUD) context.getService(reference);
- if (service != null) {
- lBaaSHandler.setDependencies(service);
- lBaaSPoolHandler.setDependencies(service);
- lBaaSPoolMemberHandler.setDependencies(service);
- }
- return service;
- }
- };
- iNeutronLoadBalancerCRUDTracker.open();
- this.iNeutronLoadBalancerCRUDTracker = iNeutronLoadBalancerCRUDTracker;
-
- @SuppressWarnings("unchecked")
- ServiceTracker iNeutronLoadBalancerPoolCRUDTracker = new ServiceTracker(context,
- INeutronLoadBalancerPoolCRUD.class, null) {
- @Override
- public Object addingService(ServiceReference reference) {
- LOG.info("addingService INeutronLoadBalancerPoolCRUD");
- INeutronLoadBalancerPoolCRUD service =
- (INeutronLoadBalancerPoolCRUD) context.getService(reference);
- if (service != null) {
- lBaaSHandler.setDependencies(service);
- lBaaSPoolMemberHandler.setDependencies(service);
- }
- return service;
- }
- };
- iNeutronLoadBalancerPoolCRUDTracker.open();
- this.iNeutronLoadBalancerPoolCRUDTracker = iNeutronLoadBalancerPoolCRUDTracker;
-
- @SuppressWarnings("unchecked")
- ServiceTracker ioadBalancerProviderTracker = new ServiceTracker(context,
- LoadBalancerProvider.class, null) {
- @Override
- public Object addingService(ServiceReference reference) {
- LOG.info("addingService LoadBalancerProvider");
- LoadBalancerProvider service =
- (LoadBalancerProvider) context.getService(reference);
- if (service != null) {
- lBaaSHandler.setDependencies(service);
- lBaaSPoolHandler.setDependencies(service);
- lBaaSPoolMemberHandler.setDependencies(service);
- }
- return service;
- }
- };
- ioadBalancerProviderTracker.open();
- this.loadBalancerProviderTracker = ioadBalancerProviderTracker;
-
- @SuppressWarnings("unchecked")
- ServiceTracker arpProviderTracker = new ServiceTracker(context,
- ArpProvider.class, null) {
- @Override
- public Object addingService(ServiceReference reference) {
- LOG.info("addingService ArpProvider");
- ArpProvider service =
- (ArpProvider) context.getService(reference);
- if (service != null) {
- neutronL3Adapter.setDependencies(service);
- }
- return service;
- }
- };
- arpProviderTracker.open();
- this.arpProviderTracker = arpProviderTracker;
-
- @SuppressWarnings("unchecked")
- ServiceTracker inboundNatProviderTracker = new ServiceTracker(context,
- InboundNatProvider.class, null) {
- @Override
- public Object addingService(ServiceReference reference) {
- LOG.info("addingService InboundNatProvider");
- InboundNatProvider service =
- (InboundNatProvider) context.getService(reference);
- if (service != null) {
- neutronL3Adapter.setDependencies(service);
- }
- return service;
- }
- };
- inboundNatProviderTracker.open();
- this.inboundNatProviderTracker = inboundNatProviderTracker;
-
- @SuppressWarnings("unchecked")
- ServiceTracker outboundNatProviderTracker = new ServiceTracker(context,
- OutboundNatProvider.class, null) {
- @Override
- public Object addingService(ServiceReference reference) {
- LOG.info("addingService OutboundNatProvider");
- OutboundNatProvider service =
- (OutboundNatProvider) context.getService(reference);
- if (service != null) {
- neutronL3Adapter.setDependencies(service);
- }
- return service;
- }
- };
- outboundNatProviderTracker.open();
- this.outboundNatProviderTracker = outboundNatProviderTracker;
+ trackService(context, INeutronNetworkCRUD.class, tenantNetworkManager, networkHandler, lBaaSHandler,
+ lBaaSPoolHandler, lBaaSPoolMemberHandler, neutronL3Adapter);
+ trackService(context, INeutronSubnetCRUD.class, lBaaSHandler, lBaaSPoolHandler, lBaaSPoolMemberHandler,
+ securityServices, neutronL3Adapter);
+ trackService(context, INeutronPortCRUD.class, tenantNetworkManager, lBaaSHandler, lBaaSPoolHandler,
+ lBaaSPoolMemberHandler, securityServices, neutronL3Adapter);
+ trackService(context, INeutronLoadBalancerCRUD.class, lBaaSHandler, lBaaSPoolHandler, lBaaSPoolMemberHandler);
+ trackService(context, INeutronLoadBalancerPoolCRUD.class, lBaaSHandler, lBaaSPoolMemberHandler);
+ trackService(context, LoadBalancerProvider.class, lBaaSHandler, lBaaSPoolHandler, lBaaSPoolMemberHandler);
+ trackService(context, ArpProvider.class, neutronL3Adapter);
+ trackService(context, InboundNatProvider.class, neutronL3Adapter);
+ trackService(context, OutboundNatProvider.class, neutronL3Adapter);
+ trackService(context, RoutingProvider.class, neutronL3Adapter);
+ trackService(context, L3ForwardingProvider.class, neutronL3Adapter);
+ trackService(context, GatewayMacResolver.class, neutronL3Adapter);
+
+ // We no longer need to track the services, avoid keeping references around
+ services.clear();
+ }
+ private void trackService(BundleContext context, final Class<?> clazz, final ConfigInterface... dependents) {
@SuppressWarnings("unchecked")
- ServiceTracker routingProviderTracker = new ServiceTracker(context,
- RoutingProvider.class, null) {
+ ServiceTracker tracker = new ServiceTracker(context, clazz, null) {
@Override
public Object addingService(ServiceReference reference) {
- LOG.info("addingService RoutingProvider");
- RoutingProvider service =
- (RoutingProvider) context.getService(reference);
+ LOG.info("addingService " + clazz.getName());
+ Object service = context.getService(reference);
if (service != null) {
- neutronL3Adapter.setDependencies(service);
+ for (ConfigInterface dependent : dependents) {
+ dependent.setDependencies(service);
+ }
}
return service;
}
};
- routingProviderTracker.open();
- this.routingProviderTracker = routingProviderTracker;
+ tracker.open();
+ }
- @SuppressWarnings("unchecked")
- ServiceTracker l3ForwardingProviderTracker = new ServiceTracker(context,
- L3ForwardingProvider.class, null) {
- @Override
- public Object addingService(ServiceReference reference) {
- LOG.info("addingService L3ForwardingProvider");
- L3ForwardingProvider service =
- (L3ForwardingProvider) context.getService(reference);
- if (service != null) {
- neutronL3Adapter.setDependencies(service);
- }
- return service;
- }
- };
- l3ForwardingProviderTracker.open();
- this.l3ForwardingProviderTracker = l3ForwardingProviderTracker;
+ 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
- iNeutronNetworkCRUDTracker.close();
- iNeutronPortCRUDTracker.close();
- iNeutronSubnetCRUDTracker.close();
- iNeutronLoadBalancerCRUDTracker.close();
- iNeutronLoadBalancerPoolCRUDTracker.close();
- loadBalancerProviderTracker.close();
-
- for (ServiceRegistration registration : registrations) {
- if (registration != null) {
- registration.unregister();
- }
- }*/
+ // 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) {
+ services.add(impl);
ServiceRegistration<?> serviceRegistration = bundleContext.registerService(interfaces, impl, properties);
if (serviceRegistration != null) {
registrations.add(serviceRegistration);
+/*
+ * 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.ovsdb.openstack.netvirt;
import org.osgi.framework.BundleContext;
/*
- * Copyright (C) 2013 Red Hat, Inc.
+ * 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.ovsdb.openstack.netvirt;
implements INeutronFirewallAware, INeutronFirewallRuleAware,
INeutronFirewallPolicyAware, ConfigInterface {
- static final Logger logger = LoggerFactory.getLogger(FWaasHandler.class);
+ private static final Logger LOG = LoggerFactory.getLogger(FWaasHandler.class);
/**
* Invoked when a Firewall Rules creation is requested
@Override
public void neutronFirewallCreated(NeutronFirewall neutronFirewall) {
- logger.debug("Neutron Firewall created by Neutron: {}", neutronFirewall);
- int result = HttpURLConnection.HTTP_BAD_REQUEST;
+ LOG.debug("Neutron Firewall created by Neutron: {}", neutronFirewall);
- result = canCreateNeutronFirewall(neutronFirewall);
+ int result = canCreateNeutronFirewall(neutronFirewall);
if (result != HttpURLConnection.HTTP_CREATED) {
- logger.error("Neutron Firewall creation failed: {} ", result);
- return;
+ LOG.error("Neutron Firewall creation failed: {} ", result);
}
}
@Override
public void neutronFirewallUpdated(NeutronFirewall neutronFirewall) {
- logger.debug("NeutronFirewall updated from Neutron: {}", neutronFirewall);
- return;
+ LOG.debug("NeutronFirewall updated from Neutron: {}", neutronFirewall);
}
@Override
//TODO: Trigger flowmod removals
int result = canDeleteNeutronFirewall(neutronFirewall);
if (result != HttpURLConnection.HTTP_OK) {
- logger.error(" delete Neutron Firewall validation failed for result - {} ", result);
- return;
+ LOG.error(" delete Neutron Firewall validation failed for result - {} ", result);
}
}
@Override
public void neutronFirewallRuleCreated(NeutronFirewallRule neutronFirewallRule) {
- logger.debug("NeutronFirewallRule created by Neutron: {}", neutronFirewallRule);
+ LOG.debug("NeutronFirewallRule created by Neutron: {}", neutronFirewallRule);
- int result = HttpURLConnection.HTTP_BAD_REQUEST;
-
- result = canCreateNeutronFirewallRule(neutronFirewallRule);
+ int result = canCreateNeutronFirewallRule(neutronFirewallRule);
if (result != HttpURLConnection.HTTP_CREATED) {
- logger.error("Neutron Firewall Rule creation failed {} ", result);
- return;
+ LOG.error("Neutron Firewall Rule creation failed {} ", result);
}
}
@Override
public void neutronFirewallRuleUpdated(NeutronFirewallRule neutronFirewallRule) {
- logger.debug("Neutron Firewall Rule updated from Neutron: {}", neutronFirewallRule);
- return;
+ LOG.debug("Neutron Firewall Rule updated from Neutron: {}", neutronFirewallRule);
}
@Override
public void neutronFirewallRuleDeleted(NeutronFirewallRule neutronFirewallRule) {
int result = canDeleteNeutronFirewallRule(neutronFirewallRule);
if (result != HttpURLConnection.HTTP_OK) {
- logger.error(" delete Neutron Firewall Rule validation failed for result - {} ", result);
- return;
+ LOG.error(" delete Neutron Firewall Rule validation failed for result - {} ", result);
}
}
@Override
public void neutronFirewallPolicyCreated(NeutronFirewallPolicy neutronFirewallPolicy) {
- logger.debug("Neutron Firewall Policy created by Neutron: {}", neutronFirewallPolicy);
-
- int result = HttpURLConnection.HTTP_BAD_REQUEST;
+ LOG.debug("Neutron Firewall Policy created by Neutron: {}", neutronFirewallPolicy);
- result = canCreateNeutronFirewallPolicy(neutronFirewallPolicy);
+ int result = canCreateNeutronFirewallPolicy(neutronFirewallPolicy);
if (result != HttpURLConnection.HTTP_CREATED) {
- logger.debug("Neutron Firewall Policy creation failed: {} ", result);
- return;
+ LOG.debug("Neutron Firewall Policy creation failed: {} ", result);
}
}
@Override
public void neutronFirewallPolicyUpdated(NeutronFirewallPolicy neutronFirewallPolicy) {
- logger.debug("Neutron Firewall Policy updated from Neutron: {}", neutronFirewallPolicy);
- return;
+ LOG.debug("Neutron Firewall Policy updated from Neutron: {}", neutronFirewallPolicy);
}
@Override
public void neutronFirewallPolicyDeleted(NeutronFirewallPolicy neutronFirewallPolicy) {
int result = canDeleteNeutronFirewallPolicy(neutronFirewallPolicy);
if (result != HttpURLConnection.HTTP_OK) {
- logger.error(" delete Neutron Firewall Policy validation failed for result - {} ", result);
- return;
+ LOG.error(" delete Neutron Firewall Policy validation failed for result - {} ", result);
}
}
@Override
public void processEvent(AbstractEvent abstractEvent) {
if (!(abstractEvent instanceof NorthboundEvent)) {
- logger.error("Unable to process abstract event " + abstractEvent);
+ LOG.error("Unable to process abstract event {}", abstractEvent);
return;
}
NorthboundEvent ev = (NorthboundEvent) abstractEvent;
// TODO: add handling of events here, once callbacks do something
// other than logging.
default:
- logger.warn("Unable to process event action " + ev.getAction());
+ LOG.warn("Unable to process event action {}", ev.getAction());
break;
}
}
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Dave Tucker, Flavio Fernandes
*/
+
package org.opendaylight.ovsdb.openstack.netvirt;
import java.net.HttpURLConnection;
public class FloatingIPHandler extends AbstractHandler
implements INeutronFloatingIPAware, ConfigInterface {
- static final Logger logger = LoggerFactory.getLogger(FloatingIPHandler.class);
+ 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;
@Override
public void processEvent(AbstractEvent abstractEvent) {
if (!(abstractEvent instanceof NorthboundEvent)) {
- logger.error("Unable to process abstract event " + abstractEvent);
+ LOG.error("Unable to process abstract event {}", abstractEvent);
return;
}
NorthboundEvent ev = (NorthboundEvent) abstractEvent;
neutronL3Adapter.handleNeutronFloatingIPEvent(ev.getNeutronFloatingIP(), ev.getAction());
break;
default:
- logger.warn("Unable to process event action " + ev.getAction());
+ LOG.warn("Unable to process event action {}", ev.getAction());
break;
}
}
/*
- * Copyright (C) 2014 SDN Hub, LLC.
+ * 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
- *
- * Authors : Srini Seetharaman
*/
package org.opendaylight.ovsdb.openstack.netvirt;
public class LBaaSHandler extends AbstractHandler
implements INeutronLoadBalancerAware, ConfigInterface, NodeCacheListener {
- private static final Logger logger = LoggerFactory.getLogger(LBaaSHandler.class);
+ 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;
@Override
public void neutronLoadBalancerCreated(NeutronLoadBalancer neutronLB) {
- logger.debug("Neutron LB Creation : {}", neutronLB.toString());
+ LOG.debug("Neutron LB Creation : {}", neutronLB.toString());
enqueueEvent(new NorthboundEvent(neutronLB, Action.ADD));
}
final List<Node> nodes = nodeCacheManager.getBridgeNodes();
if (!lbConfig.isValid()) {
- logger.debug("Neutron LB pool configuration invalid for {} ", lbConfig.getName());
+ LOG.debug("Neutron LB pool configuration invalid for {} ", lbConfig.getName());
} else if (nodes.isEmpty()) {
- logger.debug("Noop with LB {} creation because no nodes available.", lbConfig.getName());
+ 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 void neutronLoadBalancerUpdated(NeutronLoadBalancer neutronLB) {
- logger.debug("Neutron LB Update : {}", neutronLB.toString());
+ LOG.debug("Neutron LB Update : {}", neutronLB.toString());
enqueueEvent(new NorthboundEvent(neutronLB, Action.UPDATE));
}
@Override
public void neutronLoadBalancerDeleted(NeutronLoadBalancer neutronLB) {
- logger.debug("Neutron LB Deletion : {}", neutronLB.toString());
+ LOG.debug("Neutron LB Deletion : {}", neutronLB.toString());
enqueueEvent(new NorthboundEvent(neutronLB, Action.DELETE));
}
final List<Node> nodes = nodeCacheManager.getBridgeNodes();
if (!lbConfig.isValid()) {
- logger.debug("Neutron LB pool configuration invalid for {} ", lbConfig.getName());
+ LOG.debug("Neutron LB pool configuration invalid for {} ", lbConfig.getName());
} else if (nodes.isEmpty()) {
- logger.debug("Noop with LB {} deletion because no nodes available.", lbConfig.getName());
+ LOG.debug("Noop with LB {} deletion because no nodes available.", lbConfig.getName());
} else {
for (Node node : nodes) {
loadBalancerProvider.programLoadBalancerRules(node, lbConfig, Action.DELETE);
*/
@Override
public void processEvent(AbstractEvent abstractEvent) {
- logger.debug("Processing Loadbalancer event " + abstractEvent);
+ LOG.debug("Processing Loadbalancer event {}", abstractEvent);
if (!(abstractEvent instanceof NorthboundEvent)) {
- logger.error("Unable to process abstract event " + abstractEvent);
+ LOG.error("Unable to process abstract event {}", abstractEvent);
return;
}
NorthboundEvent ev = (NorthboundEvent) abstractEvent;
doNeutronLoadBalancerCreate(ev.getLoadBalancer());
break;
default:
- logger.warn("Unable to process event action " + ev.getAction());
+ LOG.warn("Unable to process event action {}", ev.getAction());
break;
}
}
}
lbConfig.setVmac(NeutronCacheUtils.getMacAddress(neutronPortCache, loadBalancerSubnetID, loadBalancerVip));
- String memberID, memberIP, memberMAC, memberProtocol, memberSubnetID;
- Integer memberPort;
- Boolean memberAdminStateIsUp;
-
for (NeutronLoadBalancerPool neutronLBPool: neutronLBPoolCache.getAllNeutronLoadBalancerPools()) {
List<NeutronLoadBalancerPoolMember> members = neutronLBPool.getLoadBalancerPoolMembers();
- memberProtocol = neutronLBPool.getLoadBalancerPoolProtocol();
+ String memberProtocol = neutronLBPool.getLoadBalancerPoolProtocol();
if (memberProtocol == null) {
continue;
}
continue;
}
for (NeutronLoadBalancerPoolMember neutronLBPoolMember: members) {
- memberAdminStateIsUp = neutronLBPoolMember.getPoolMemberAdminStateIsUp();
- memberSubnetID = neutronLBPoolMember.getPoolMemberSubnetID();
- if (memberSubnetID == null || memberAdminStateIsUp == null) {
- continue;
- }
- else if (memberSubnetID.equals(loadBalancerSubnetID) && memberAdminStateIsUp.booleanValue()) {
- memberID = neutronLBPoolMember.getPoolMemberID();
- memberIP = neutronLBPoolMember.getPoolMemberAddress();
- memberPort = neutronLBPoolMember.getPoolMemberProtoPort();
- if (memberSubnetID == null || memberID == null || memberIP == null || memberPort == null) {
- logger.debug("Neutron LB pool member details incomplete: {}", neutronLBPoolMember);
+ 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;
}
- memberMAC = NeutronCacheUtils.getMacAddress(neutronPortCache, memberSubnetID, memberIP);
+ String memberMAC = NeutronCacheUtils.getMacAddress(neutronPortCache, memberSubnetID, memberIP);
if (memberMAC == null) {
continue;
}
*/
@Override
public void notifyNode(Node node, Action type) {
- logger.debug("notifyNode: Node {} update {} from Controller's inventory Service", node, type);
+ LOG.debug("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()) {
- logger.debug("Neutron LB configuration invalid for {} ", lbConfig.getName());
+ LOG.debug("Neutron LB configuration invalid for {} ", lbConfig.getName());
} else {
if (type.equals(Action.ADD)) {
loadBalancerProvider.programLoadBalancerRules(node, lbConfig, Action.ADD);
*/
//(type.equals(UpdateType.REMOVED) || type.equals(UpdateType.CHANGED))
- } else {
- continue;
}
}
}
/*
- * Copyright (C) 2014 SDN Hub, LLC.
+ * 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
- *
- * Authors : Srini Seetharaman
*/
package org.opendaylight.ovsdb.openstack.netvirt;
public class LBaaSPoolHandler extends AbstractHandler
implements INeutronLoadBalancerPoolAware, ConfigInterface {
- private static final Logger logger = LoggerFactory.getLogger(LBaaSPoolHandler.class);
+ 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;
@Override
public void neutronLoadBalancerPoolCreated(NeutronLoadBalancerPool neutronLBPool) {
- logger.debug("Neutron LB Pool Creation : {}", neutronLBPool.toString());
+ LOG.debug("Neutron LB Pool Creation : {}", neutronLBPool.toString());
enqueueEvent(new NorthboundEvent(neutronLBPool, Action.ADD));
}
List<LoadBalancerConfiguration> lbConfigList = extractLBConfiguration(neutronLBPool);
final List<Node> nodes = nodeCacheManager.getBridgeNodes();
if (lbConfigList == null) {
- logger.debug("Neutron LB configuration invalid for pool {} ", neutronLBPool.getLoadBalancerPoolID());
+ LOG.debug("Neutron LB configuration invalid for pool {} ", neutronLBPool.getID());
} else if (lbConfigList.size() == 0) {
- logger.debug("No Neutron LB VIP not created yet for pool {} ", neutronLBPool.getLoadBalancerPoolID());
+ LOG.debug("No Neutron LB VIP not created yet for pool {} ", neutronLBPool.getID());
} else if (nodes.isEmpty()) {
- logger.debug("Noop with LB pool {} creation because no nodes available.", neutronLBPool.getLoadBalancerPoolID());
+ LOG.debug("Noop with LB pool {} creation because no nodes available.", neutronLBPool.getID());
} else {
for (LoadBalancerConfiguration lbConfig: lbConfigList) {
if (!lbConfig.isValid()) {
- logger.debug("Neutron LB pool configuration invalid for {} ", lbConfig.getName());
- continue;
+ LOG.debug("Neutron LB pool configuration invalid for {} ", lbConfig.getName());
} else {
for (Node node : nodes) {
loadBalancerProvider.programLoadBalancerRules(node, lbConfig, Action.ADD);
@Override
public void neutronLoadBalancerPoolUpdated(NeutronLoadBalancerPool neutronLBPool) {
- logger.debug("Neutron LB Pool Update : {}", neutronLBPool.toString());
+ LOG.debug("Neutron LB Pool Update : {}", neutronLBPool.toString());
enqueueEvent(new NorthboundEvent(neutronLBPool, Action.UPDATE));
}
@Override
public void neutronLoadBalancerPoolDeleted(NeutronLoadBalancerPool neutronLBPool) {
- logger.debug("Neutron LB Pool Deletion : {}", neutronLBPool.toString());
+ LOG.debug("Neutron LB Pool Deletion : {}", neutronLBPool.toString());
enqueueEvent(new NorthboundEvent(neutronLBPool, Action.DELETE));
}
List<LoadBalancerConfiguration> lbConfigList = extractLBConfiguration(neutronLBPool);
final List<Node> nodes = nodeCacheManager.getBridgeNodes();
if (lbConfigList == null) {
- logger.debug("Neutron LB configuration invalid for pool {} ", neutronLBPool.getLoadBalancerPoolID());
+ LOG.debug("Neutron LB configuration invalid for pool {} ", neutronLBPool.getID());
} else if (lbConfigList.size() == 0) {
- logger.debug("No Neutron LB VIP not created yet for pool {} ", neutronLBPool.getLoadBalancerPoolID());
+ LOG.debug("No Neutron LB VIP not created yet for pool {} ", neutronLBPool.getID());
} else if (nodes.isEmpty()) {
- logger.debug("Noop with LB pool {} deletion because no nodes available.", neutronLBPool.getLoadBalancerPoolID());
+ LOG.debug("Noop with LB pool {} deletion because no nodes available.", neutronLBPool.getID());
} else {
for (LoadBalancerConfiguration lbConfig: lbConfigList) {
if (!lbConfig.isValid()) {
- logger.debug("Neutron LB pool configuration invalid for {} ", lbConfig.getName());
- continue;
+ LOG.debug("Neutron LB pool configuration invalid for {} ", lbConfig.getName());
} else {
for (Node node : nodes) {
loadBalancerProvider.programLoadBalancerRules(node, lbConfig, Action.DELETE);
*/
@Override
public void processEvent(AbstractEvent abstractEvent) {
- logger.debug("Processing Loadbalancer Pool event " + abstractEvent);
+ LOG.debug("Processing Loadbalancer Pool event {}", abstractEvent);
if (!(abstractEvent instanceof NorthboundEvent)) {
- logger.error("Unable to process abstract event " + abstractEvent);
+ LOG.error("Unable to process abstract event {}", abstractEvent);
return;
}
NorthboundEvent ev = (NorthboundEvent) abstractEvent;
* Typical upgrade involves changing algorithm. Right now
* we do not support this flexibility. TODO
*/
- logger.warn("Load balancer pool update is not supported");
+ LOG.warn("Load balancer pool update is not supported");
break;
default:
- logger.warn("Unable to process event action " + ev.getAction());
+ LOG.warn("Unable to process event action {}", ev.getAction());
break;
}
}
List<NeutronLoadBalancerPoolMember> poolMembers = neutronLBPool.getLoadBalancerPoolMembers();
if (poolMembers.size() == 0) {
- logger.debug("Neutron LB pool is empty: {}", neutronLBPool);
+ LOG.debug("Neutron LB pool is empty: {}", neutronLBPool);
return null;
}
/* Iterate over all the Loadbalancers created so far and identify VIP
*/
- String loadBalancerSubnetID, loadBalancerVip=null, loadBalancerName=null;
for (NeutronLoadBalancer neutronLB: neutronLBCache.getAllNeutronLoadBalancers()) {
- loadBalancerSubnetID = neutronLB.getLoadBalancerVipSubnetID();
- loadBalancerName = neutronLB.getLoadBalancerName();
- loadBalancerVip = neutronLB.getLoadBalancerVipAddress();
+ 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);
for (NeutronLoadBalancerPoolMember neutronLBPoolMember: neutronLBPool.getLoadBalancerPoolMembers()) {
memberAdminStateIsUp = neutronLBPoolMember.getPoolMemberAdminStateIsUp();
memberSubnetID = neutronLBPoolMember.getPoolMemberSubnetID();
- if (memberSubnetID == null || memberAdminStateIsUp == null) {
- continue;
- } else if (memberSubnetID.equals(loadBalancerSubnetID) && memberAdminStateIsUp.booleanValue()) {
- memberID = neutronLBPoolMember.getPoolMemberID();
+ if (memberSubnetID != null && memberAdminStateIsUp != null &&
+ memberSubnetID.equals(loadBalancerSubnetID) && memberAdminStateIsUp) {
+ memberID = neutronLBPoolMember.getID();
memberIP = neutronLBPoolMember.getPoolMemberAddress();
memberPort = neutronLBPoolMember.getPoolMemberProtoPort();
- if (memberSubnetID == null || memberID == null || memberIP == null || memberPort == null) {
- logger.debug("Neutron LB pool member details incomplete: {}", neutronLBPoolMember);
+ if (memberID == null || memberIP == null || memberPort == null) {
+ LOG.debug("Neutron LB pool member details incomplete: {}", neutronLBPoolMember);
continue;
}
memberMAC = NeutronCacheUtils.getMacAddress(neutronPortCache, memberSubnetID, memberIP);
}
}
- if (lbConfig.getMembers().size() > 0)
+ if (lbConfig.getMembers().size() > 0) {
lbConfigList.add(lbConfig);
+ }
}
return lbConfigList;
/*
- * Copyright (C) 2014 SDN Hub, LLC.
+ * 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
- *
- * Authors : Srini Seetharaman
*/
+
package org.opendaylight.ovsdb.openstack.netvirt;
import java.net.HttpURLConnection;
public class LBaaSPoolMemberHandler extends AbstractHandler
implements INeutronLoadBalancerPoolMemberAware, ConfigInterface {
- private static final Logger logger = LoggerFactory.getLogger(LBaaSPoolMemberHandler.class);
+ 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;
@Override
public void neutronLoadBalancerPoolMemberCreated(NeutronLoadBalancerPoolMember neutronLBPoolMember) {
- logger.debug("Neutron LB Pool Member Creation : {}", neutronLBPoolMember.toString());
+ LOG.debug("Neutron LB Pool Member Creation : {}", neutronLBPoolMember.toString());
enqueueEvent(new NorthboundEvent(neutronLBPoolMember, Action.ADD));
}
final List<Node> nodes =
nodeCacheManager.getBridgeNodes();
if (lbConfig == null) {
- logger.debug("Neutron LB configuration invalid for member {} ", neutronLBPoolMember.getPoolMemberAddress());
+ LOG.debug("Neutron LB configuration invalid for member {} ", neutronLBPoolMember.getPoolMemberAddress());
} else if (lbConfig.getVip() == null) {
- logger.debug("Neutron LB VIP not created yet for member {} ", neutronLBPoolMember.getPoolMemberID());
+ LOG.debug("Neutron LB VIP not created yet for member {} ", neutronLBPoolMember.getID());
} else if (!lbConfig.isValid()) {
- logger.debug("Neutron LB pool configuration invalid for {} ", lbConfig.getName());
+ LOG.debug("Neutron LB pool configuration invalid for {} ", lbConfig.getName());
} else if (nodes.isEmpty()) {
- logger.debug("Noop with LB pool member {} creation because no nodes available.", neutronLBPoolMember.getPoolMemberID());
+ 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.getPoolMemberID()), Action.ADD);
+ lbConfig.getMembers().get(neutronLBPoolMember.getID()), Action.ADD);
}
}
}
@Override
public void neutronLoadBalancerPoolMemberUpdated(NeutronLoadBalancerPoolMember neutronLBPoolMember) {
- logger.debug("Neutron LB Pool Member Update : {}", neutronLBPoolMember.toString());
+ LOG.debug("Neutron LB Pool Member Update : {}", neutronLBPoolMember.toString());
enqueueEvent(new NorthboundEvent(neutronLBPoolMember, Action.UPDATE));
}
@Override
public void neutronLoadBalancerPoolMemberDeleted(NeutronLoadBalancerPoolMember neutronLBPoolMember) {
- logger.debug("Neutron LB Pool Member Deletion : {}", neutronLBPoolMember.toString());
+ LOG.debug("Neutron LB Pool Member Deletion : {}", neutronLBPoolMember.toString());
enqueueEvent(new NorthboundEvent(neutronLBPoolMember, Action.DELETE));
}
LoadBalancerConfiguration lbConfig = extractLBConfiguration(neutronLBPoolMember);
final List<Node> nodes = nodeCacheManager.getBridgeNodes();
if (lbConfig == null) {
- logger.debug("Neutron LB configuration invalid for member {} ", neutronLBPoolMember.getPoolMemberAddress());
+ LOG.debug("Neutron LB configuration invalid for member {} ", neutronLBPoolMember.getPoolMemberAddress());
} else if (lbConfig.getVip() == null) {
- logger.debug("Neutron LB VIP not created yet for member {} ", neutronLBPoolMember.getPoolMemberID());
+ LOG.debug("Neutron LB VIP not created yet for member {} ", neutronLBPoolMember.getID());
} else if (!lbConfig.isValid()) {
- logger.debug("Neutron LB pool configuration invalid for {} ", lbConfig.getName());
+ LOG.debug("Neutron LB pool configuration invalid for {} ", lbConfig.getName());
} else if (nodes.isEmpty()) {
- logger.debug("Noop with LB pool member {} deletion because no nodes available.", neutronLBPoolMember.getPoolMemberID());
+ 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.getPoolMemberID());
+ newLBConfig.removeMember(neutronLBPoolMember.getID());
for (Node node : nodes) {
loadBalancerProvider.programLoadBalancerRules(node, lbConfig, Action.DELETE);
*/
@Override
public void processEvent(AbstractEvent abstractEvent) {
- logger.debug("Processing Loadbalancer member event " + abstractEvent);
+ LOG.debug("Processing Loadbalancer member event {}", abstractEvent);
if (!(abstractEvent instanceof NorthboundEvent)) {
- logger.error("Unable to process abstract event " + abstractEvent);
+ LOG.error("Unable to process abstract event {}", abstractEvent);
return;
}
NorthboundEvent ev = (NorthboundEvent) abstractEvent;
* Typical upgrade involves changing weights. Since weights are not
* supported yet, updates are not supported either. TODO
*/
- logger.warn("Load balancer pool member update is not supported");
+ LOG.warn("Load balancer pool member update is not supported");
break;
default:
- logger.warn("Unable to process event action " + ev.getAction());
+ LOG.warn("Unable to process event action {}", ev.getAction());
break;
}
}
* configuration from the neutron LB cache based on member info
*/
public LoadBalancerConfiguration extractLBConfiguration(NeutronLoadBalancerPoolMember neutronLBPoolMember) {
- String memberID = neutronLBPoolMember.getPoolMemberID();
+ String memberID = neutronLBPoolMember.getID();
String memberIP = neutronLBPoolMember.getPoolMemberAddress();
String memberSubnetID = neutronLBPoolMember.getPoolMemberSubnetID();
Integer memberPort = neutronLBPoolMember.getPoolMemberProtoPort();
String memberPoolID = neutronLBPoolMember.getPoolID();
- String memberProtocol = null;
if (memberSubnetID == null || memberID == null || memberPoolID == null) {
- logger.debug("Neutron LB pool member details incomplete [id={}, pool_id={},subnet_id={}",
+ 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) {
- logger.debug("Neutron LB pool member {} MAC address unavailable", memberID);
+ LOG.debug("Neutron LB pool member {} MAC address unavailable", memberID);
return null;
}
NeutronLoadBalancerPool neutronLBPool = neutronLBPoolCache.getNeutronLoadBalancerPool(memberPoolID);
- memberProtocol = neutronLBPool.getLoadBalancerPoolProtocol();
+ String memberProtocol = neutronLBPool.getLoadBalancerPoolProtocol();
if (!(memberProtocol.equalsIgnoreCase(LoadBalancerConfiguration.PROTOCOL_TCP) ||
memberProtocol.equalsIgnoreCase(LoadBalancerConfiguration.PROTOCOL_HTTP) ||
memberProtocol.equalsIgnoreCase(LoadBalancerConfiguration.PROTOCOL_HTTPS))) {
Integer otherMemberPort;
for (NeutronLoadBalancerPoolMember otherMember: neutronLBPool.getLoadBalancerPoolMembers()) {
- otherMemberID = otherMember.getPoolMemberID();
+ otherMemberID = otherMember.getID();
if (otherMemberID.equals(memberID)) {
continue; //skip
}
otherMemberPort = otherMember.getPoolMemberProtoPort();
otherMemberProtocol = memberProtocol;
- if (otherMemberIP == null || otherMemberSubnetID == null || otherMemberAdminStateIsUp == null) {
- continue;
- } else if (otherMemberAdminStateIsUp.booleanValue()) {
+ if (otherMemberIP != null && otherMemberSubnetID != null && otherMemberAdminStateIsUp != null &&
+ otherMemberAdminStateIsUp) {
otherMemberMAC = NeutronCacheUtils.getMacAddress(neutronPortCache, otherMemberSubnetID, otherMemberIP);
if (otherMemberMAC == null) {
continue;
+/*
+ * 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.ovsdb.openstack.netvirt;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
/*
- * Copyright (C) 2013 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal, Brent Salisbury, Hsin-Yi Shen
*/
+
package org.opendaylight.ovsdb.openstack.netvirt;
import java.net.HttpURLConnection;
* Handle requests for Neutron Network.
*/
public class NetworkHandler extends AbstractHandler implements INeutronNetworkAware, ConfigInterface {
- private static final Logger logger = LoggerFactory.getLogger(NetworkHandler.class);
+ 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";
@Override
public int canCreateNetwork(NeutronNetwork network) {
if (network.isShared()) {
- logger.error(" Network shared attribute not supported ");
+ LOG.error(" Network shared attribute not supported ");
return HttpURLConnection.HTTP_NOT_ACCEPTABLE;
}
public int canUpdateNetwork(NeutronNetwork delta,
NeutronNetwork original) {
if (delta.isShared()) {
- logger.error(" Network shared attribute not supported ");
+ LOG.error(" Network shared attribute not supported ");
return HttpURLConnection.HTTP_NOT_ACCEPTABLE;
}
if (neutronNetworkCache != null) {
networks = neutronNetworkCache.getAllNetworks();
if (networks.isEmpty()) {
- logger.trace("neutronNetworkDeleted: last tenant network, delete tunnel ports...");
+ LOG.trace("neutronNetworkDeleted: last tenant network, delete tunnel ports...");
List<Node> nodes = nodeCacheManager.getNodes();
for (Node node : nodes) {
List<OvsdbTerminationPointAugmentation> ports = southbound.getTerminationPointsOfBridge(node);
for (OvsdbTerminationPointAugmentation port : ports) {
if (southbound.isTunnel(port)) {
- logger.trace("Delete tunnel interface {}", port.getName());
+ LOG.trace("Delete tunnel interface {}", port.getName());
southbound.deleteTerminationPoint(node, port.getName());
} else if (!phyIfName.isEmpty() && phyIfName.contains(port.getName())) {
- logger.trace("Delete physical interface {}", port.getName());
+ LOG.trace("Delete physical interface {}", port.getName());
southbound.deleteTerminationPoint(node, port.getName());
}
}
} catch (Exception e) {
- logger.error("Exception during handlingNeutron network delete", e);
+ LOG.error("Exception during handlingNeutron network delete", e);
}
}
}
@Override
public void processEvent(AbstractEvent abstractEvent) {
if (!(abstractEvent instanceof NorthboundEvent)) {
- logger.error("Unable to process abstract event " + abstractEvent);
+ LOG.error("Unable to process abstract event {}", abstractEvent);
return;
}
NorthboundEvent ev = (NorthboundEvent) abstractEvent;
doNeutronNetworkDeleted(ev.getNeutronNetwork());
break;
default:
- logger.warn("Unable to process event action " + ev.getAction());
+ LOG.warn("Unable to process event action {}", ev.getAction());
break;
}
}
/*
- * Copyright (C) 2014 SDN Hub, LLC.
+ * 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
- *
- * Authors : Srini Seetharaman
*/
package org.opendaylight.ovsdb.openstack.netvirt;
* @return MAC address registered with that IP address
*/
public static String getMacAddress(INeutronPortCRUD neutronPortsCache, String subnetID, String ipAddr) {
- if (ipAddr == null || subnetID == null)
+ if (ipAddr == null || subnetID == null) {
return null;
+ }
List<Neutron_IPs> fixedIPs;
Iterator<Neutron_IPs> fixedIPIterator;
fixedIPIterator = fixedIPs.iterator();
while (fixedIPIterator.hasNext()) {
ip = fixedIPIterator.next();
- if (ip.getIpAddress().equals(ipAddr) && ip.getSubnetUUID().equals(subnetID))
+ if (ip.getIpAddress().equals(ipAddr) && ip.getSubnetUUID().equals(subnetID)) {
return port.getMacAddress();
+ }
}
}
}
break;
}
}
- if (networkID == null)
+ if (networkID == null) {
return null;
+ }
List<NeutronNetwork> allNetworks = neutronNetworkCache.getAllNetworks();
for (NeutronNetwork network: allNetworks) {
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Dave Tucker
*/
+
package org.opendaylight.ovsdb.openstack.netvirt;
import org.opendaylight.ovsdb.openstack.netvirt.api.Constants;
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Dave Tucker, Flavio Fernandes
*/
package org.opendaylight.ovsdb.openstack.netvirt;
/*
- * Copyright (C) 2013 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal, Brent Salisbury
*/
+
package org.opendaylight.ovsdb.openstack.netvirt;
import java.net.HttpURLConnection;
* Handle requests for Neutron Port.
*/
public class PortHandler extends AbstractHandler implements INeutronPortAware, ConfigInterface {
- static final Logger logger = LoggerFactory.getLogger(PortHandler.class);
+ 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;
enqueueEvent(new NorthboundEvent(neutronPort, Action.ADD));
}
private void doNeutronPortCreated(NeutronPort neutronPort) {
- logger.debug(" Port-ADD successful for tenant-id - {}," +
- " network-id - {}, port-id - {}",
+ LOG.debug(" Port-ADD successful for tenant-id - {}, network-id - {}, port-id - {}",
neutronPort.getTenantID(), neutronPort.getNetworkUUID(),
neutronPort.getID());
neutronL3Adapter.handleNeutronPortEvent(neutronPort, Action.ADD);
enqueueEvent(new NorthboundEvent(neutronPort, Action.UPDATE));
}
private void doNeutronPortUpdated(NeutronPort neutronPort) {
- logger.debug("Handling neutron update port " + neutronPort);
+ LOG.debug("Handling neutron update port {}", neutronPort);
neutronL3Adapter.handleNeutronPortEvent(neutronPort, Action.UPDATE);
}
enqueueEvent(new NorthboundEvent(neutronPort, Action.DELETE));
}
private void doNeutronPortDeleted(NeutronPort neutronPort) {
- logger.debug("Handling neutron delete port " + neutronPort);
+ LOG.debug("Handling neutron delete port {}", neutronPort);
neutronL3Adapter.handleNeutronPortEvent(neutronPort, Action.DELETE);
//TODO: Need to implement getNodes
List<Node> nodes = nodeCacheManager.getNodes();
String neutronPortId =
southbound.getInterfaceExternalIdsValue(port, Constants.EXTERNAL_ID_INTERFACE_ID);
if (neutronPortId != null && neutronPortId.equalsIgnoreCase(neutronPort.getPortUUID())) {
- logger.trace("neutronPortDeleted: Delete interface {}", port.getName());
+ LOG.trace("neutronPortDeleted: Delete interface {}", port.getName());
southbound.deleteTerminationPoint(node, port.getName());
break;
}
}
} catch (Exception e) {
- logger.error("Exception during handlingNeutron port delete", e);
+ LOG.error("Exception during handlingNeutron port delete", e);
}
}
- logger.debug(" PORT delete successful for tenant-id - {}, " +
- " network-id - {}, port-id - {}",
+ LOG.debug(" PORT delete successful for tenant-id - {}, network-id - {}, port-id - {}",
neutronPort.getTenantID(), neutronPort.getNetworkUUID(),
neutronPort.getID());
}
@Override
public void processEvent(AbstractEvent abstractEvent) {
if (!(abstractEvent instanceof NorthboundEvent)) {
- logger.error("Unable to process abstract event " + abstractEvent);
+ LOG.error("Unable to process abstract event {}", abstractEvent);
return;
}
NorthboundEvent ev = (NorthboundEvent) abstractEvent;
doNeutronPortUpdated(ev.getPort());
break;
default:
- logger.warn("Unable to process event action " + ev.getAction());
+ LOG.warn("Unable to process event action {}", ev.getAction());
break;
}
}
/*
- * Copyright (C) 2013 Red Hat, Inc.
+ * 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
- *
- * Authors : Brent Salisbury, Madhu Venugopal
*/
package org.opendaylight.ovsdb.openstack.netvirt;
public class PortSecurityHandler extends AbstractHandler
implements INeutronSecurityGroupAware, INeutronSecurityRuleAware, ConfigInterface {
- static final Logger logger = LoggerFactory.getLogger(PortSecurityHandler.class);
+ private static final Logger LOG = LoggerFactory.getLogger(PortSecurityHandler.class);
@Override
public int canCreateNeutronSecurityGroup(NeutronSecurityGroup neutronSecurityGroup) {
@Override
public void neutronSecurityGroupCreated(NeutronSecurityGroup neutronSecurityGroup) {
- int result = HttpURLConnection.HTTP_BAD_REQUEST;
-
- result = canCreateNeutronSecurityGroup(neutronSecurityGroup);
+ int result = canCreateNeutronSecurityGroup(neutronSecurityGroup);
if (result != HttpURLConnection.HTTP_CREATED) {
- logger.debug("Neutron Security Group creation failed {} ", result);
- return;
+ LOG.debug("Neutron Security Group creation failed {} ", result);
}
}
@Override
public void neutronSecurityGroupUpdated(NeutronSecurityGroup neutronSecurityGroup) {
- return;
+ // Nothing to do
}
@Override
//TODO: Trigger flowmod removals
int result = canDeleteNeutronSecurityGroup(neutronSecurityGroup);
if (result != HttpURLConnection.HTTP_OK) {
- logger.error(" delete Neutron Security Rule validation failed for result - {} ", result);
- return;
+ LOG.error(" delete Neutron Security Rule validation failed for result - {} ", result);
}
}
@Override
public void neutronSecurityRuleCreated(NeutronSecurityRule neutronSecurityRule) {
- int result = HttpURLConnection.HTTP_BAD_REQUEST;
-
- result = canCreateNeutronSecurityRule(neutronSecurityRule);
+ int result = canCreateNeutronSecurityRule(neutronSecurityRule);
if (result != HttpURLConnection.HTTP_CREATED) {
- logger.debug("Neutron Security Group creation failed {} ", result);
- return;
+ LOG.debug("Neutron Security Group creation failed {} ", result);
}
}
@Override
public void neutronSecurityRuleUpdated(NeutronSecurityRule neutronSecurityRule) {
- return;
+ // Nothing to do
}
@Override
public void neutronSecurityRuleDeleted(NeutronSecurityRule neutronSecurityRule) {
int result = canDeleteNeutronSecurityRule(neutronSecurityRule);
if (result != HttpURLConnection.HTTP_OK) {
- logger.error(" delete Neutron Security Rule validation failed for result - {} ", result);
- return;
+ LOG.error(" delete Neutron Security Rule validation failed for result - {} ", result);
}
}
@Override
public void processEvent(AbstractEvent abstractEvent) {
if (!(abstractEvent instanceof NorthboundEvent)) {
- logger.error("Unable to process abstract event " + abstractEvent);
+ LOG.error("Unable to process abstract event {}", abstractEvent);
return;
}
NorthboundEvent ev = (NorthboundEvent) abstractEvent;
// TODO: add handling of events here, once callbacks do something
// other than logging.
default:
- logger.warn("Unable to process event action " + ev.getAction());
+ LOG.warn("Unable to process event action {}", ev.getAction());
break;
}
}
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Dave Tucker, Flavio Fernandes
*/
+
package org.opendaylight.ovsdb.openstack.netvirt;
import java.net.HttpURLConnection;
* Handle requests for Neutron Router.
*/
public class RouterHandler extends AbstractHandler implements INeutronRouterAware, ConfigInterface {
- static final Logger logger = LoggerFactory.getLogger(RouterHandler.class);
+ 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;
*/
@Override
public int canAttachInterface(NeutronRouter router, NeutronRouter_Interface routerInterface) {
- logger.debug(" Router {} asked if it can attach interface {}. Subnet {}",
+ LOG.debug(" Router {} asked if it can attach interface {}. Subnet {}",
router.getName(),
routerInterface.getPortUUID(),
routerInterface.getSubnetUUID());
*/
@Override
public int canDetachInterface(NeutronRouter router, NeutronRouter_Interface routerInterface) {
- logger.debug(" Router {} asked if it can detach interface {}. Subnet {}",
+ LOG.debug(" Router {} asked if it can detach interface {}. Subnet {}",
router.getName(),
routerInterface.getPortUUID(),
routerInterface.getSubnetUUID());
@Override
public void processEvent(AbstractEvent abstractEvent) {
if (!(abstractEvent instanceof NorthboundEvent)) {
- logger.error("Unable to process abstract event " + abstractEvent);
+ LOG.error("Unable to process abstract event {}", abstractEvent);
return;
}
NorthboundEvent ev = (NorthboundEvent) abstractEvent;
}
break;
default:
- logger.warn("Unable to process event action " + ev.getAction());
+ LOG.warn("Unable to process event action {}", ev.getAction());
break;
}
}
/*
- * Copyright (C) 2013 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal, Brent Salisbury
*/
+
package org.opendaylight.ovsdb.openstack.netvirt;
import org.opendaylight.ovsdb.openstack.netvirt.api.Action;
/*
- * Copyright (C) 2013 Red Hat, Inc.
+ * 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.ovsdb.openstack.netvirt;
import java.util.List;
*/
public class SouthboundHandler extends AbstractHandler
implements ConfigInterface, NodeCacheListener, OvsdbInventoryListener {
- private static final Logger LOGGER = LoggerFactory.getLogger(SouthboundHandler.class);
+ 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;
type = SouthboundEvent.Type.OPENVSWITCH;
break;
default:
- LOGGER.warn("Invalid OvsdbType: {}", ovsdbType);
+ LOG.warn("Invalid OvsdbType: {}", ovsdbType);
break;
}
return type;
@Override
public void ovsdbUpdate(Node node, DataObject resourceAugmentationData, OvsdbType ovsdbType, Action action) {
- LOGGER.info("ovsdbUpdate: {} - {} - <<{}>> <<{}>>", ovsdbType, action, node, resourceAugmentationData);
+ LOG.info("ovsdbUpdate: {} - {} - <<{}>> <<{}>>", ovsdbType, action, node, resourceAugmentationData);
enqueueEvent(new SouthboundEvent(node, resourceAugmentationData,
ovsdbTypeToSouthboundEventType(ovsdbType), action));
}
private void handleInterfaceUpdate (Node node, OvsdbTerminationPointAugmentation tp) {
- LOGGER.debug("handleInterfaceUpdate <{}> <{}>", node, tp);
+ LOG.debug("handleInterfaceUpdate <{}> <{}>", node, tp);
NeutronNetwork network = tenantNetworkManager.getTenantNetwork(tp);
if (network != null && !network.getRouterExternal()) {
- LOGGER.trace("handleInterfaceUpdate <{}> <{}> network: {}", node, tp, network.getNetworkUUID());
+ LOG.trace("handleInterfaceUpdate <{}> <{}> network: {}", node, tp, network.getNetworkUUID());
if (bridgeConfigurationManager.createLocalNetwork(node, network)) {
networkingProviderManager.getProvider(node).handleInterfaceUpdate(network, node, tp);
}
} else {
- LOGGER.debug("No tenant network found on node: <{}> for interface: <{}>", node, tp);
+ LOG.debug("No tenant network found on node: <{}> for interface: <{}>", node, tp);
}
neutronL3Adapter.handleInterfaceEvent(node, tp, network, Action.UPDATE);
}
private void handleInterfaceDelete (Node node, OvsdbTerminationPointAugmentation intf,
boolean isLastInstanceOnNode, NeutronNetwork network) {
- LOGGER.debug("handleInterfaceDelete: node: <{}>, isLastInstanceOnNode: {}, interface: <{}>",
+ LOG.debug("handleInterfaceDelete: node: <{}>, isLastInstanceOnNode: {}, interface: <{}>",
node, isLastInstanceOnNode, intf);
neutronL3Adapter.handleInterfaceEvent(node, intf, network, Action.DELETE);
// vlan doesn't need a tunnel endpoint
if (!network.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VLAN) &&
configurationService.getTunnelEndPoint(node) == null) {
- LOGGER.error("Tunnel end-point configuration missing. Please configure it in OpenVSwitch Table");
+ LOG.error("Tunnel end-point configuration missing. Please configure it in OpenVSwitch Table");
return;
}
networkingProviderManager.getProvider(node).handleInterfaceDelete(network.getProviderNetworkType(),
@Override
public void triggerUpdates() {
- LOGGER.info("triggerUpdates");
+ LOG.info("triggerUpdates");
List<Node> ovsdbNodes = southbound.readOvsdbTopologyNodes();
for (Node node : ovsdbNodes) {
ovsdbUpdate(node, node.getAugmentation(OvsdbNodeAugmentation.class),
private void processPortDelete(Node node, OvsdbTerminationPointAugmentation ovsdbTerminationPointAugmentation,
Object context) {
- LOGGER.debug("processPortDelete <{}> <{}>", node, ovsdbTerminationPointAugmentation);
- NeutronNetwork network = null;
+ LOG.debug("processPortDelete <{}> <{}>", node, ovsdbTerminationPointAugmentation);
+ NeutronNetwork network;
if (context == null) {
network = tenantNetworkManager.getTenantNetwork(ovsdbTerminationPointAugmentation);
} else {
if (network != null) {
this.handleInterfaceDelete(node, ovsdbTerminationPointAugmentation, false, network);
} else {
- LOGGER.warn("processPortDelete: network was null, ignoring update");
+ LOG.warn("processPortDelete: network was null, ignoring update");
}
} else if (network != null && !network.getRouterExternal()) {
- LOGGER.debug("Network {}: Delete interface {} attached to bridge {}", network.getNetworkUUID(),
+ LOG.debug("Network {}: Delete interface {} attached to bridge {}", network.getNetworkUUID(),
ovsdbTerminationPointAugmentation.getInterfaceUuid(), node.getNodeId());
try {
OvsdbBridgeAugmentation ovsdbBridgeAugmentation = southbound.getBridge(node);
}
}
} catch (Exception e) {
- LOGGER.error("Error fetching Interface Rows for node " + node, e);
+ LOG.error("Error fetching Interface Rows for node {}", node, e);
}
}
}
private boolean isInterfaceOfInterest(OvsdbTerminationPointAugmentation terminationPoint, List<String> phyIfName) {
- LOGGER.trace("SouthboundHandler#isInterfaceOfInterest: Interface : {}", terminationPoint);
+ LOG.trace("SouthboundHandler#isInterfaceOfInterest: Interface : {}", terminationPoint);
if(terminationPoint.getInterfaceType() == null){
// This is OK since eth ports don't have an interface type
- LOGGER.info("No type found for the interface : {}", terminationPoint);
+ LOG.info("No type found for the interface : {}", terminationPoint);
return false;
}
return MdsalHelper.createOvsdbInterfaceType(
*/
@Override
public void notifyNode (Node node, Action action) {
- LOGGER.info("notifyNode: action: {}, Node <{}>", action, node);
+ LOG.info("notifyNode: action: {}, Node <{}>", action, node);
if ((action.equals(Action.ADD)) && (southbound.getBridge(node) != null)) {
networkingProviderManager.getProvider(node).initializeOFFlowRules(node);
@Override
public void processEvent(AbstractEvent abstractEvent) {
if (!(abstractEvent instanceof SouthboundEvent)) {
- LOGGER.error("processEvent: Unable to process abstract event {}", abstractEvent);
+ LOG.error("processEvent: Unable to process abstract event {}", abstractEvent);
return;
}
SouthboundEvent ev = (SouthboundEvent) abstractEvent;
- LOGGER.trace("processEvent: {}", ev);
+ LOG.trace("processEvent: {}", ev);
switch (ev.getType()) {
case NODE:
processOvsdbNodeEvent(ev);
break;
default:
- LOGGER.warn("Unable to process type " + ev.getType() +
- " action " + ev.getAction() + " for node " + ev.getNode());
+ LOG.warn("Unable to process type {} action {} for node {}", ev.getType(), ev.getAction(), ev.getNode());
break;
}
}
}
private void processOvsdbNodeCreate(Node node, OvsdbNodeAugmentation ovsdbNode) {
- LOGGER.info("processOvsdbNodeCreate <{}> <{}>", node, ovsdbNode);
+ LOG.info("processOvsdbNodeCreate <{}> <{}>", node, ovsdbNode);
nodeCacheManager.nodeAdded(node);
bridgeConfigurationManager.prepareNode(node);
}
private void processOvsdbNodeUpdate(Node node, OvsdbNodeAugmentation ovsdbNode) {
- LOGGER.info("processOvsdbNodeUpdate <{}> <{}>", node, ovsdbNode);
+ LOG.info("processOvsdbNodeUpdate <{}> <{}>", node, ovsdbNode);
nodeCacheManager.nodeAdded(node);
}
private void processOvsdbNodeDelete(Node node, OvsdbNodeAugmentation ovsdbNode) {
- LOGGER.info("processOvsdbNodeDelete <{}> <{}>", node, ovsdbNode);
+ LOG.info("processOvsdbNodeDelete <{}> <{}>", node, ovsdbNode);
nodeCacheManager.nodeRemoved(node);
/* TODO SB_MIGRATION
* I don't think we want to do this yet
}
private void processPortUpdate(Node node, OvsdbTerminationPointAugmentation port) {
- LOGGER.debug("processPortUpdate <{}> <{}>", node, port);
+ LOG.debug("processPortUpdate <{}> <{}>", node, port);
NeutronNetwork network = tenantNetworkManager.getTenantNetwork(port);
- if (network != null && !network.getRouterExternal()) {
- this.handleInterfaceUpdate(node, port);
+ if (network != null ){
+ if(!network.getRouterExternal()){
+ this.handleInterfaceUpdate(node, port);
+ }
}
}
}
private void processOpenVSwitchUpdate(Node node) {
- LOGGER.debug("processOpenVSwitchUpdate {}", 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);
}
}
- private boolean isMainBridge(Node node, OvsdbBridgeAugmentation bridge) {
- boolean rv = false;
- String nodeIdStr = node.getNodeId().getValue();
- String bridgeName = nodeIdStr.substring(nodeIdStr.lastIndexOf('/') + 1);
- List<TerminationPoint> terminationPoints = southbound.extractTerminationPoints(node);
- if (terminationPoints != null && terminationPoints.size() == 1) {
- // TODO: Either do something or remove this if statement.
- // If there's only one termination point, is it a 1-port bridge?
- }
- OvsdbTerminationPointAugmentation port = southbound.extractTerminationPointAugmentation(node, bridgeName);
- if (port != null) {
- String datapathId = southbound.getDatapathId(bridge);
- // Having a datapathId means the ovsdb node has connected to ODL
- if (datapathId != null) {
- rv = true;
- } else {
- LOGGER.info("datapathId not found");
- }
- }
- return rv;
- }
-
private void processBridgeCreate(Node node, OvsdbBridgeAugmentation bridge) {
- LOGGER.debug("processBridgeCreate <{}> <{}>", node, bridge);
+ LOG.debug("processBridgeCreate <{}> <{}>", node, bridge);
String datapathId = southbound.getDatapathId(bridge);
// Having a datapathId means the ovsdb node has connected to ODL
if (datapathId != null) {
nodeCacheManager.nodeAdded(node);
} else {
- LOGGER.info("processBridgeCreate datapathId not found");
+ LOG.info("processBridgeCreate datapathId not found");
}
}
private void processBridgeUpdate(Node node, OvsdbBridgeAugmentation bridge) {
- LOGGER.debug("processBridgeUpdate <{}> <{}>", node, bridge);
+ LOG.debug("processBridgeUpdate <{}> <{}>", node, bridge);
String datapathId = southbound.getDatapathId(bridge);
// Having a datapathId means the ovsdb node has connected to ODL
if (datapathId != null) {
nodeCacheManager.nodeAdded(node);
} else {
- LOGGER.info("processBridgeUpdate datapathId not found");
+ LOG.info("processBridgeUpdate datapathId not found");
}
}
private void processBridgeDelete(Node node, OvsdbBridgeAugmentation bridge) {
- LOGGER.debug("processBridgeDelete: Delete bridge from config data store: <{}> <{}>",
+ LOG.debug("processBridgeDelete: Delete bridge from config data store: <{}> <{}>",
node, bridge);
nodeCacheManager.nodeRemoved(node);
// TODO SB_MIGRATION
/*
- * Copyright (C) 2013 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal, Brent Salisbury
*/
package org.opendaylight.ovsdb.openstack.netvirt;
public class SubnetHandler extends AbstractHandler implements INeutronSubnetAware, ConfigInterface {
- static final Logger logger = LoggerFactory.getLogger(SubnetHandler.class);
+ 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 void processEvent(AbstractEvent abstractEvent) {
if (!(abstractEvent instanceof NorthboundEvent)) {
- logger.error("Unable to process abstract event " + abstractEvent);
+ LOG.error("Unable to process abstract event {}", abstractEvent);
return;
}
NorthboundEvent ev = (NorthboundEvent) abstractEvent;
neutronL3Adapter.handleNeutronSubnetEvent(ev.getSubnet(), ev.getAction());
break;
default:
- logger.warn("Unable to process event action " + ev.getAction());
+ LOG.warn("Unable to process event action {}", ev.getAction());
break;
}
}
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Dave Tucker, Flavio Fernandes
*/
package org.opendaylight.ovsdb.openstack.netvirt.api;
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Dave Tucker, Flavio Fernandes
*/
package org.opendaylight.ovsdb.openstack.netvirt.api;
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Dave Tucker
*/
package org.opendaylight.ovsdb.openstack.netvirt.api;
* @param bridgeName the name of the bridge
* @return the UUID of the bridge
*/
- public String getBridgeUuid(Node node, String bridgeName);
+ 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
*/
- public boolean isNodeNeutronReady(Node node);
+ 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
*/
- public boolean isNodeOverlayReady(Node node);
+ boolean isNodeOverlayReady(Node node);
/**
* Checks for the existence of the Network Bridge on a given Node
* @param ovsdbNode the {@link Node} where the bridge is configured
* @return True or False
*/
- public boolean isNodeTunnelReady(Node bridgeNode, Node ovsdbNode);
+ 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
* @param network the {@link org.opendaylight.neutron.spi.NeutronNetwork}
* @return True or False
*/
- public boolean isNodeVlanReady(Node bridgeNode, Node ovsdbNode, NeutronNetwork network);
+ boolean isNodeVlanReady(Node bridgeNode, Node ovsdbNode, NeutronNetwork network);
/**
* A helper function to determine if a port exists on a given bridge
* @param portName the name of the port to search for
* @return True if the port exists, otherwise False
*/
- public boolean isPortOnBridge (Node node, String portName);
+ boolean isPortOnBridge(Node node, String portName);
/**
* @param network the {@link org.opendaylight.neutron.spi.NeutronNetwork}
* @return True or False
*/
- public boolean createLocalNetwork(Node node, NeutronNetwork network);
+ 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
*/
- public void prepareNode(Node node);
+ void prepareNode(Node node);
/**
* Returns the physical interface mapped to the given neutron physical network.
* @param physicalNetwork
* @return
*/
- public String getPhysicalInterfaceName (Node node, String physicalNetwork);
+ 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
*/
- public List<String> getAllPhysicalInterfaceNames(Node node);
+ List<String> getAllPhysicalInterfaceNames(Node node);
}
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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.ovsdb.openstack.netvirt.api;
* This interface allows Classifier flows to be written to devices
*/
public interface ClassifierProvider {
- public void programLocalInPort(Long dpidLong, String segmentationId, Long inPort, String attachedMac, boolean write);
- public void programLocalInPortSetVlan(Long dpidLong, String segmentationId, Long inPort, String attachedMac, boolean write);
- public void programDropSrcIface(Long dpidLong, Long inPort, boolean write);
- public void programTunnelIn(Long dpidLong, String segmentationId, Long ofPort, boolean write);
- public void programVlanIn(Long dpidLong, String segmentationId, Long ethPort, boolean write);
- public void programLLDPPuntRule(Long dpidLong);
+ 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);
}
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Dave Tucker
*/
package org.opendaylight.ovsdb.openstack.netvirt.api;
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Dave Tucker
*/
+
package org.opendaylight.ovsdb.openstack.netvirt.api;
/**
/*
* 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 PREFIX_PORT_MATCH_PRIORITY_DROP = 36002;
public static final Integer PROTO_PORT_PREFIX_MATCH_PRIORITY_DROP = 36001;
+ public static final Integer PROTO_DHCP_CLIENT_TRAFFIC_MATCH_PRIORITY = 61012;
public static final Integer PROTO_MATCH_PRIORITY = 61010;
public static final Integer PREFIX_MATCH_PRIORITY = 61009;
public static final Integer PROTO_PREFIX_MATCH_PRIORITY = 61008;
public static final Integer PROTO_PORT_MATCH_PRIORITY = 61007;
public static final Integer PROTO_PORT_PREFIX_MATCH_PRIORITY = 61007;
+ public static final Integer PROTO_DHCP_SERVER_MATCH_PRIORITY = 61006;
+ public static final Integer PROTO_VM_IP_MAC_MATCH_PRIORITY = 36001;
public static final int TCP_SYN = 0x002;
public static final short INGRESS_ACL = 40; // Flows Destined to the VM Port go here
+/*
+ * 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.ovsdb.openstack.netvirt.api;
+import java.util.List;
+
import org.opendaylight.neutron.spi.NeutronSecurityGroup;
+import org.opendaylight.neutron.spi.Neutron_IPs;
/**
* This interface allows egress Port Security flows to be written to devices
* @param localPort the local port
* @param securityGroup the security group
*/
- public void programPortSecurityACL(Long dpid, String segmentationId, String attachedMac,
- long localPort, NeutronSecurityGroup securityGroup);
+ void programPortSecurityACL(Long dpid, String segmentationId, String attachedMac,
+ long localPort, NeutronSecurityGroup securityGroup);
+ /**
+ * Program fixed egress 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 attached mac
+ * @param localPort the local port
+ * @param srcAddressList the list of source ip address assigned to vm
+ * @param isLastPortinBridge is this the last port in the bridge
+ * @param isComputePort indicates whether this port is a compute port or not
+ * @param write is this flow writing or deleting
+ */
+ void programFixedSecurityACL(Long dpid, String segmentationId, String attachedMac,
+ long localPort, List<Neutron_IPs> srcAddressList, boolean isLastPortinBridge, boolean isComputePort, boolean write);
}
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Dave Tucker, Flavio Fernandes
*/
package org.opendaylight.ovsdb.openstack.netvirt.api;
* Enqueue the event.
* @param event the {@link org.opendaylight.ovsdb.openstack.netvirt.AbstractEvent} event to be handled.
*/
- public void enqueueEvent(AbstractEvent event);
- public void eventHandlerAdded(final ServiceReference ref, AbstractHandler handler);
- public void eventHandlerRemoved(final ServiceReference ref);
+ 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.ovsdb.openstack.netvirt.api;
+
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress;
+
+import 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 externalNetworkBridgeDpid This bridge will be used for sending ARP request
+ * @param gatewayIp ARP request will be send for this ip address
+ * @param periodicRefresh Do you want to periodically refresh the gateway mac?
+ * @return
+ */
+ public ListenableFuture<MacAddress> resolveMacAddress( final Long externalNetworkBridgeDpid, 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
+ */
+ public void stopPeriodicRefresh(final Ipv4Address gatewayIp);
+}
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Dave Tucker, Flavio Fernandes
*/
package org.opendaylight.ovsdb.openstack.netvirt.api;
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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.ovsdb.openstack.netvirt.api;
* @param localPort the local port
* @param securityGroup the security group
*/
- public void programPortSecurityACL(Long dpid, String segmentationId, String attachedMac,
- long localPort, NeutronSecurityGroup securityGroup);
+ void programPortSecurityACL(Long dpid, String segmentationId, String attachedMac,
+ long localPort, NeutronSecurityGroup securityGroup);
+ /**
+ * 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 attached mac
+ * @param localPort the local port
+ * @param isLastPortinSubnet is this the last port in the subnet
+ * @param isComputePort indicates whether this port is a compute port or not
+ * @param write is this flow writing or deleting
+ */
+ void programFixedSecurityACL(Long dpid, String segmentationId,
+ String attachedMac, long localPort, boolean isLastPortinSubnet, boolean isComputePort, boolean write);
}
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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.ovsdb.openstack.netvirt.api;
* This interface allows L2Forwarding flows to be written to devices
*/
public interface L2ForwardingProvider {
- public void programLocalUcastOut(Long dpidLong, String segmentationId, Long localPort, String attachedMac, boolean write);
- public void programLocalVlanUcastOut(Long dpidLong, String segmentationId, Long localPort, String attachedMac, boolean write);
- public void programLocalBcastOut(Long dpidLong, String segmentationId, Long localPort, boolean write);
- public void programLocalVlanBcastOut(Long dpidLong, String segmentationId, Long localPort, Long ethPort, boolean write);
- public void programLocalTableMiss(Long dpidLong, String segmentationId, boolean write);
- public void programLocalVlanTableMiss(Long dpidLong, String segmentationId, boolean write);
- public void programTunnelOut(Long dpidLong, String segmentationId, Long OFPortOut, String attachedMac, boolean write);
- public void programVlanOut(Long dpidLong, String segmentationId, Long ethPort, String attachedMac, boolean write);
- public void programTunnelFloodOut(Long dpidLong, String segmentationId, Long OFPortOut, boolean write);
- public void programVlanFloodOut(Long dpidLong, String segmentationId, Long ethPort, boolean write);
- public void programTunnelMiss(Long dpidLong, String segmentationId, boolean write);
- public void programVlanMiss(Long dpidLong, String segmentationId, Long ethPort, boolean write);
+ 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 programLocalTableMiss(Long dpidLong, String segmentationId, 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 programVlanFloodOut(Long dpidLong, String segmentationId, Long ethPort, boolean write);
+ void programTunnelMiss(Long dpidLong, String segmentationId, boolean write);
+ void programVlanMiss(Long dpidLong, String segmentationId, Long ethPort, boolean write);
}
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Dave Tucker, Flavio Fernandes
*/
package org.opendaylight.ovsdb.openstack.netvirt.api;
/*
- * Copyright (C) 2014 SDN Hub, LLC.
+ * 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
- *
- * Authors : Srini Seetharaman
*/
package org.opendaylight.ovsdb.openstack.netvirt.api;
*/
@Override
public boolean equals(Object obj) {
- if (this == obj)
+ if (this == obj) {
return true;
- if (obj == null)
+ }
+ if (obj == null) {
return false;
- if (getClass() != obj.getClass())
+ }
+ if (getClass() != obj.getClass()) {
return false;
+ }
LoadBalancerPoolMember other = (LoadBalancerPoolMember) obj;
if (ipAddr == null) {
- if (other.ipAddr != null)
+ if (other.ipAddr != null) {
return false;
- } else if (!ipAddr.equals(other.ipAddr))
+ }
+ } else if (!ipAddr.equals(other.ipAddr)) {
return false;
+ }
if (macAddr == null) {
- if (other.macAddr != null)
+ if (other.macAddr != null) {
return false;
- } else if (!macAddr.equals(other.macAddr))
+ }
+ } else if (!macAddr.equals(other.macAddr)) {
return false;
+ }
if (port == null) {
- if (other.port != null)
+ if (other.port != null) {
return false;
- } else if (!port.equals(other.port))
+ }
+ } else if (!port.equals(other.port)) {
return false;
+ }
if (protocol == null) {
- if (other.protocol != null)
+ if (other.protocol != null) {
return false;
- } else if (!protocol.equals(other.protocol))
+ }
+ } else if (!protocol.equals(other.protocol)) {
return false;
+ }
return true;
}
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)
+ if (member.getIndex() == -1) {
member.setIndex(members.size());
+ }
this.members.put(uuid, member);
return this.members;
}
/* Update indices of all other members
*/
int index = 0;
- for(Map.Entry<String, LoadBalancerPoolMember> entry : this.getMembers().entrySet())
+ for(Map.Entry<String, LoadBalancerPoolMember> entry : this.getMembers().entrySet()) {
((LoadBalancerPoolMember) entry.getValue()).setIndex(index++);
+ }
return this.members;
}
public boolean isValid() {
- if (members.size() == 0)
+ if (members.size() == 0) {
return false;
- else if (providerNetworkType == null)
+ } else if (providerNetworkType == null) {
return false;
+ }
return true;
}
/*
- * Copyright (C) 2014 SDN Hub, LLC.
+ * 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
- *
- * Authors : Srini Seetharaman
*/
package org.opendaylight.ovsdb.openstack.netvirt.api;
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Dave Tucker, Flavio Fernandes
*/
package org.opendaylight.ovsdb.openstack.netvirt.api;
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Dave Tucker
*/
package org.opendaylight.ovsdb.openstack.netvirt.api;
/**
* Returns the name of the NetworkingProvider
*/
- public String getName();
+ String getName();
/**
* Return true if the provider supports Network Service Instances
*/
- public boolean supportsServices();
+ boolean supportsServices();
/**
* Return true if the provider supports per-tenant or "static" tunneling
*/
- public boolean hasPerTenantTunneling();
+ boolean hasPerTenantTunneling();
/**
* Handle Interface Update Callback Method
*/
- public boolean handleInterfaceUpdate(NeutronNetwork network, Node source, OvsdbTerminationPointAugmentation intf);
+ boolean handleInterfaceUpdate(NeutronNetwork network, Node source, OvsdbTerminationPointAugmentation intf);
/**
* Handle Interface Delete Callback Method
*/
- public boolean handleInterfaceDelete(String tunnelType, NeutronNetwork network, Node source,
- OvsdbTerminationPointAugmentation intf, boolean isLastInstanceOnNode);
+ boolean handleInterfaceDelete(String tunnelType, NeutronNetwork network, Node source,
+ OvsdbTerminationPointAugmentation intf, boolean isLastInstanceOnNode);
/**
* Initialize the Flow rules given the OVSDB node.
* that are Openflow Version specific. Hence we have this method in addition to the following
* Openflow Node specific initialization method.
*/
- public void initializeFlowRules(Node node);
+ void initializeFlowRules(Node node);
/**
* Initialize the Flow rules for a given OpenFlow node
*/
- public void initializeOFFlowRules(Node openflowNode);
+ void initializeOFFlowRules(Node openflowNode);
}
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Dave Tucker
*/
package org.opendaylight.ovsdb.openstack.netvirt.api;
* @see NetworkingProvider
*/
NetworkingProvider getProvider(Node ovsdbNode);
- public void providerAdded(final ServiceReference ref, final NetworkingProvider provider);
- public void providerRemoved(final ServiceReference ref);
+ void providerAdded(final ServiceReference ref, final NetworkingProvider provider);
+ void providerRemoved(final ServiceReference ref);
}
* @author Sam Hague (shague@redhat.com)
*/
public interface NodeCacheListener {
- public void notifyNode(Node node, Action action);
+ void notifyNode(Node node, Action action);
}
* @author Sam Hague (shague@redhat.com)
*/
public interface NodeCacheManager {
- public void nodeAdded(Node node);
- public void nodeRemoved(Node node);
- public List<Node> getNodes();
- public Map<NodeId, Node> getOvsdbNodes();
- public List<Node> getBridgeNodes();
- public void cacheListenerAdded(final ServiceReference ref, NodeCacheListener handler);
- public void cacheListenerRemoved(final ServiceReference ref);
+ void nodeAdded(Node node);
+ void nodeRemoved(Node node);
+ List<Node> getNodes();
+ Map<NodeId, Node> getOvsdbNodes();
+ List<Node> getBridgeNodes();
+ void cacheListenerAdded(final ServiceReference ref, NodeCacheListener handler);
+ void cacheListenerRemoved(final ServiceReference ref);
}
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Dave Tucker, Flavio Fernandes
*/
package org.opendaylight.ovsdb.openstack.netvirt.api;
+/*
+ * 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.ovsdb.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 {
- public enum OvsdbType {
+ enum OvsdbType {
NODE,
ROW,
OPENVSWITCH,
CONTROLLER,
PORT
}
- public void ovsdbUpdate(Node node, DataObject augmentationDataChanges, OvsdbType type, Action action);
- public void triggerUpdates();
+ void ovsdbUpdate(Node node, DataObject augmentationDataChanges, OvsdbType type, Action action);
+ void triggerUpdates();
}
* @author Sam Hague (shague@redhat.com)
*/
public interface OvsdbInventoryService {
- public void listenerAdded(OvsdbInventoryListener listener);
- public void listenerRemoved(OvsdbInventoryListener listener);
- public void providersReady();
+ void listenerAdded(OvsdbInventoryListener listener);
+ void listenerRemoved(OvsdbInventoryListener listener);
+ void providersReady();
}
+/*
+ * 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.ovsdb.openstack.netvirt.api;
public class OvsdbPluginException extends RuntimeException {
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Dave Tucker, Flavio Fernandes
*/
package org.opendaylight.ovsdb.openstack.netvirt.api;
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Dave Tucker, Flavio Fernandes
*/
package org.opendaylight.ovsdb.openstack.netvirt.api;
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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.ovsdb.openstack.netvirt.api;
+import java.util.List;
+
+import org.opendaylight.neutron.spi.NeutronPort;
import org.opendaylight.neutron.spi.NeutronSecurityGroup;
+import org.opendaylight.neutron.spi.Neutron_IPs;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.*;
+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
* @param intf the intf
* @return the boolean
*/
- public boolean isPortSecurityReady(OvsdbTerminationPointAugmentation intf);
+ boolean isPortSecurityReady(OvsdbTerminationPointAugmentation intf);
/**
* Gets security group in port.
*
* @param intf the intf
* @return the security group in port
*/
- public NeutronSecurityGroup getSecurityGroupInPort(OvsdbTerminationPointAugmentation intf);
+ NeutronSecurityGroup getSecurityGroupInPort(OvsdbTerminationPointAugmentation intf);
+ /**
+ * Gets the DHCP server port corresponding to a network.
+ *
+ * @param intf the intf
+ * @return the security group in port
+ */
+ NeutronPort getDHCPServerPort(OvsdbTerminationPointAugmentation intf);
+
+ /**
+ * Is the port a compute port.
+ *
+ * @param intf the intf
+ * @return the security group in port
+ */
+ boolean isComputePort(OvsdbTerminationPointAugmentation intf);
+
+ /**
+ * Is this the last port in the subnet to which interface belongs to.
+ *
+ * @param intf the intf
+ * @return the security group in port
+ */
+ boolean isLastPortinSubnet(Node node, OvsdbTerminationPointAugmentation intf);
+ /**
+ * Is this the last port in the bridge to which interface belongs to.
+ *
+ * @param intf the intf
+ * @return the security group in port
+ */
+ boolean isLastPortinBridge(Node node, OvsdbTerminationPointAugmentation intf);
+ /**
+ * Returns the list of ip adddress assigned to the interface.
+ *
+ * @param intf the intf
+ * @return the security group in port
+ */
+ List<Neutron_IPs> getIpAddress(Node node, OvsdbTerminationPointAugmentation intf);
}
\ No newline at end of file
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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,
* @param networkId the Neutron Network ID
* @return the assigned VLAN ID or 0 in case of an error
*/
- public int getInternalVlan(Node node, String networkId);
+ 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
*/
- public void reclaimInternalVlan(Node node, NeutronNetwork network);
+ void reclaimInternalVlan(Node node, NeutronNetwork network);
/**
* Configures the VLAN for a Tenant Network
* @param tp the termination point
* @param network the Neutron Network ID
*/
- public void programInternalVlan(Node node, OvsdbTerminationPointAugmentation tp, NeutronNetwork network);
+ void programInternalVlan(Node node, OvsdbTerminationPointAugmentation tp, NeutronNetwork network);
/**
* Check is the given network is present on a Node
* @param segmentationId the Neutron Segementation ID
* @return True or False
*/
- public boolean isTenantNetworkPresentInNode(Node node, String segmentationId);
+ boolean isTenantNetworkPresentInNode(Node node, String segmentationId);
/**
* Get the Neutron Network ID for a given Segmentation ID
*/
- public String getNetworkId (String segmentationId);
+ String getNetworkId(String segmentationId);
/**
* Network Created Callback
*/
- public int networkCreated (Node node, String networkId);
+ int networkCreated(Node node, String networkId);
/**
* Network Deleted Callback
*/
- public void networkDeleted(String id);
+ void networkDeleted(String id);
NeutronNetwork getTenantNetwork(OvsdbTerminationPointAugmentation terminationPointAugmentation);
- public NeutronPort getTenantPort(OvsdbTerminationPointAugmentation terminationPointAugmentation);
+ NeutronPort getTenantPort(OvsdbTerminationPointAugmentation terminationPointAugmentation);
}
/*
- * Copyright (C) 2013 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal, Brent Salisbury
*/
package org.opendaylight.ovsdb.openstack.netvirt.api;
private static final int UUID_TIME_LEN = (UUID_TIME_LOW +
UUID_TIME_MID + UUID_TIME_HIGH_VERSION);
- static final Logger logger = LoggerFactory.getLogger(UuidUtils.class);
+ private static final Logger LOG = LoggerFactory.getLogger(UuidUtils.class);
+
+ /**
+ * Private constructor (utility class).
+ */
+ private UuidUtils() {
+ // Nothing to do
+ }
/**
* Convert neutron object id to key syntax.
return null;
}
- logger.trace(" neutronID - {}, length - {} ",
+ LOG.trace(" neutronID - {}, length - {} ",
neutronID, neutronID.length());
if (!isValidNeutronID(neutronID)) {
return null;
return false;
}
boolean isValid;
- logger.trace("id - {}, length - {} ", id, id.length());
+ LOG.trace("id - {}, length - {} ", id, id.length());
/**
* check the string length
* if length is 36 its a uuid do uuid validation
String toUUID = fromUUID.toString();
isValid = toUUID.equalsIgnoreCase(id);
} catch(IllegalArgumentException e) {
- logger.error(" IllegalArgumentExecption for id - {} ", id);
+ LOG.error(" IllegalArgumentExecption for id - {} ", id, e);
isValid = false;
}
} else {
if (id == null) {
return null;
}
- logger.trace("id - {}, length - {} ", id, id.length());
+ LOG.trace("id - {}, length - {} ", id, id.length());
/**
* ID must be less than 32 bytes,
* Shorten UUID string length from 36 to 31 as follows:
tKey.deleteCharAt(UUID_VERSION_POS);
key = tKey.toString();
} catch(IllegalArgumentException ile) {
- logger.error(" Invalid UUID - {} ", id);
+ LOG.error(" Invalid UUID - {} ", id, ile);
key = null;
}
return key;
* and reconvert it to key
*/
- logger.trace(" id - {}, length - {} ", id, id.length());
+ LOG.trace(" id - {}, length - {} ", id, id.length());
try {
StringBuilder tKey = new StringBuilder();
String tmpStr = id.substring(0, UUID_TIME_LOW);
key = convertUUIDToKey(tmpStr);
}
} catch(IndexOutOfBoundsException ibe) {
- logger.error(" Exception! Invalid UUID - {} ", id);
+ LOG.error(" Exception! Invalid UUID - {} ", id, ibe);
key = null;
} catch (IllegalArgumentException iae) {
- logger.error(" Exception! Invalid object ID - {} ", id);
+ LOG.error(" Exception! Invalid object ID - {} ", id, iae);
key = null;
}
return key;
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Dave Tucker
*/
package org.opendaylight.ovsdb.openstack.netvirt.api;
* @param networkId the Neutron Network ID
* @return a VLAN ID or 0 in case of an error
*/
- public Integer assignInternalVlan (Node node, String networkId);
+ Integer assignInternalVlan(Node node, String networkId);
/**
* Recovers an assigned VLAN ID when it is no longer required
* @param networkId the Neutron Network ID
* @return the reclaimed VLAN ID or 0 in case of an error
*/
- public Integer reclaimInternalVlan (Node node, String networkId);
+ Integer reclaimInternalVlan(Node node, String networkId);
/**
* Returns a VLAN ID assigned to a given tenant network
* @param networkId the Neutron Network ID
* @return the VLAN ID or 0 in case of an error
*/
- public Integer getInternalVlan (Node node, String networkId);
+ Integer getInternalVlan(Node node, String networkId);
}
/*
- * Copyright (C) 2013 Red Hat, Inc.
+ * 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.ovsdb.openstack.netvirt.impl;
import org.opendaylight.neutron.spi.NeutronNetwork;
* @author Sam Hague (shague@redhat.com)
*/
public class BridgeConfigurationManagerImpl implements BridgeConfigurationManager, ConfigInterface {
- private static final Logger LOGGER = LoggerFactory.getLogger(BridgeConfigurationManagerImpl.class);
+ 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;
public boolean isNodeTunnelReady(Node bridgeNode, Node ovsdbNode) {
Preconditions.checkNotNull(configurationService);
if (!southbound.isBridgeOnOvsdbNode(ovsdbNode, configurationService.getIntegrationBridgeName())) {
- LOGGER.trace("isNodeTunnelReady: node: {}, {} missing",
+ LOG.trace("isNodeTunnelReady: node: {}, {} missing",
bridgeNode, configurationService.getIntegrationBridgeName());
return false;
}
final String brInt = configurationService.getIntegrationBridgeName();
if (!southbound.isBridgeOnOvsdbNode(ovsdbNode, brInt)) {
- LOGGER.trace("isNodeVlanReady: node: {}, {} missing", bridgeNode, 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)) {
- LOGGER.trace("isNodeVlanReady: node: {}, eth missing", bridgeNode);
+ LOG.trace("isNodeVlanReady: node: {}, eth missing", bridgeNode);
return false;
}
if (isPortOnBridge(extBridgeNode, portNameExt)) {
ready = true;
} else {
- LOGGER.trace("isNodeL3Ready: node: {}, {} missing",
+ LOG.trace("isNodeL3Ready: node: {}, {} missing",
bridgeNode, portNameExt);
}
} else {
- LOGGER.trace("isNodeL3Ready: node: {}, {} missing",
+ LOG.trace("isNodeL3Ready: node: {}, {} missing",
bridgeNode, portNameInt);
}
} else {
- LOGGER.trace("isNodeL3Ready: node: {}, {} missing",
+ LOG.trace("isNodeL3Ready: node: {}, {} missing",
bridgeNode, brExt);
}
} else {
try {
createIntegrationBridge(ovsdbNode);
} catch (Exception e) {
- LOGGER.error("Error creating Integration Bridge on {}", ovsdbNode, e);
+ LOG.error("Error creating Integration Bridge on {}", ovsdbNode, e);
return;
}
createExternalBridge(ovsdbNode);
}
} catch (Exception e) {
- LOGGER.error("Error creating External Bridge on {}", ovsdbNode, e);
+ LOG.error("Error creating External Bridge on {}", ovsdbNode, e);
return;
}
// this node is an ovsdb node so it doesn't have a bridge
Node ovsdbNode = southbound.readOvsdbNode(bridgeNode);
if (ovsdbNode == null) {
//this should never happen
- LOGGER.error("createLocalNetwork could not find ovsdbNode from bridge node " + bridgeNode);
+ LOG.error("createLocalNetwork could not find ovsdbNode from bridge node " + bridgeNode);
return false;
}
if (network.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VLAN)) {
try {
isCreated = createBridges(bridgeNode, ovsdbNode, network);
} catch (Exception e) {
- LOGGER.error("Error creating internal vlan net network " + bridgeNode, e);
+ LOG.error("Error creating internal vlan net network " + bridgeNode, e);
}
} else {
isCreated = true;
try {
isCreated = createBridges(bridgeNode, ovsdbNode, network);
} catch (Exception e) {
- LOGGER.error("Error creating internal vxlan/gre net network " + bridgeNode, e);
+ LOG.error("Error creating internal vxlan/gre net network " + bridgeNode, e);
}
} else {
isCreated = true;
}
if (phyIf == null) {
- LOGGER.error("Physical interface not found for Node: {}, Network {}",
- node, physicalNetwork);
+ LOG.error("Physical interface not found for Node: {}, Network {}",
+ node, physicalNetwork);
}
return phyIf;
@Override
public List<String> getAllPhysicalInterfaceNames(Node node) {
List<String> phyIfName = Lists.newArrayList();
- String phyIf = null;
String providerMaps = southbound.getOtherConfig(node, OvsdbTables.OPENVSWITCH,
configurationService.getProviderMappingsKey());
if (providerMaps == null) {
Preconditions.checkNotNull(configurationService);
if (!addBridge(ovsdbNode, configurationService.getIntegrationBridgeName())) {
- LOGGER.debug("Integration Bridge Creation failed");
+ LOG.debug("Integration Bridge Creation failed");
return false;
}
return true;
Preconditions.checkNotNull(configurationService);
if (!addBridge(ovsdbNode, configurationService.getExternalBridgeName())) {
- LOGGER.debug("External Bridge Creation failed");
+ LOG.debug("External Bridge Creation failed");
return false;
}
return true;
Preconditions.checkNotNull(configurationService);
Preconditions.checkNotNull(networkingProviderManager);
- LOGGER.debug("createBridges: node: {}, network type: {}", bridgeNode, network.getProviderNetworkType());
+ LOG.debug("createBridges: node: {}, network type: {}", bridgeNode, network.getProviderNetworkType());
final String brInt = configurationService.getIntegrationBridgeName();
if (! createIntegrationBridge(ovsdbNode)) {
- LOGGER.debug("{} Bridge creation failed", brInt);
+ LOG.debug("{} Bridge creation failed", brInt);
return false;
}
if (configurationService.isL3ForwardingEnabled()) {
final String brExt = configurationService.getExternalBridgeName();
if (! createExternalBridge(ovsdbNode)) {
- LOGGER.error("{} Bridge creation failed", brExt);
+ LOG.error("{} Bridge creation failed", brExt);
return false;
}
Preconditions.checkNotNull(portNameExt);
if (!addPatchPort(bridgeNode, brInt, portNameInt, portNameExt)) {
- LOGGER.error("Add Port {} to Bridge {} failed", portNameInt, brInt);
+ LOG.error("Add Port {} to Bridge {} failed", portNameInt, brInt);
return false;
}
Node extBridgeNode = southbound.readBridgeNode(ovsdbNode, brExt);
Preconditions.checkNotNull(extBridgeNode);
if (!addPatchPort(extBridgeNode, brExt, portNameExt, portNameInt)) {
- LOGGER.error("Add Port {} to Bridge {} failed", portNameExt, brExt);
+ LOG.error("Add Port {} to Bridge {} failed", portNameExt, brExt);
return false;
}
}
if (network.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VLAN)) {
String phyNetName = this.getPhysicalInterfaceName(bridgeNode, network.getProviderPhysicalNetwork());
if (!addPortToBridge(bridgeNode, brInt, phyNetName)) {
- LOGGER.debug("Add Port {} to Bridge {} failed", phyNetName, brInt);
+ LOG.debug("Add Port {} to Bridge {} failed", phyNetName, brInt);
return false;
}
}
- LOGGER.debug("createBridges: node: {}, status: success", bridgeNode);
+ LOG.debug("createBridges: node: {}, status: success", bridgeNode);
return true;
}
rv = southbound.addTerminationPoint(node, bridgeName, portName, null);
if (rv) {
- LOGGER.info("addPortToBridge: node: {}, bridge: {}, portname: {} status: success",
+ LOG.info("addPortToBridge: node: {}, bridge: {}, portname: {} status: success",
node.getNodeId().getValue(), bridgeName, portName);
} else {
- LOGGER.error("addPortToBridge: node: {}, bridge: {}, portname: {} status: FAILED",
+ LOG.error("addPortToBridge: node: {}, bridge: {}, portname: {} status: FAILED",
node.getNodeId().getValue(), bridgeName, portName);
}
} else {
- LOGGER.trace("addPortToBridge: node: {}, bridge: {}, portname: {} status: not_needed",
+ LOG.trace("addPortToBridge: node: {}, bridge: {}, portname: {} status: not_needed",
node.getNodeId().getValue(), bridgeName, portName);
}
rv = southbound.addPatchTerminationPoint(node, bridgeName, portName, peerPortName);
if (rv) {
- LOGGER.info("addPatchPort: node: {}, bridge: {}, portname: {} peer: {} status: success",
+ LOG.info("addPatchPort: node: {}, bridge: {}, portname: {} peer: {} status: success",
node.getNodeId().getValue(), bridgeName, portName, peerPortName);
} else {
- LOGGER.error("addPatchPort: node: {}, bridge: {}, portname: {} peer: {} status: FAILED",
+ LOG.error("addPatchPort: node: {}, bridge: {}, portname: {} peer: {} status: FAILED",
node.getNodeId().getValue(), bridgeName, portName, peerPortName);
}
} else {
- LOGGER.trace("addPatchPort: node: {}, bridge: {}, portname: {} peer: {} status: not_needed",
+ LOG.trace("addPatchPort: node: {}, bridge: {}, portname: {} peer: {} status: not_needed",
node.getNodeId().getValue(), bridgeName, portName, peerPortName);
}
return addressString;
}
} catch (UnknownHostException e) {
- LOGGER.error("Host {} is invalid", addressString);
+ LOG.error("Host {} is invalid", addressString);
}
}
return addressString;
}
} catch (UnknownHostException e) {
- LOGGER.error("Host {} is invalid", addressString);
+ LOG.error("Host {} is invalid", addressString);
}
}
}
private short getControllerOFPort() {
- Short defaultOpenFlowPort = Constants.OPENFLOW_PORT;
- Short openFlowPort = defaultOpenFlowPort;
+ short openFlowPort = Constants.OPENFLOW_PORT;
String portString = ConfigProperties.getProperty(this.getClass(), "of.listenPort");
if (portString != null) {
try {
- openFlowPort = Short.decode(portString).shortValue();
+ openFlowPort = Short.parseShort(portString);
} catch (NumberFormatException e) {
- LOGGER.warn("Invalid port:{}, use default({})", portString,
+ LOG.warn("Invalid port:{}, use default({})", portString,
openFlowPort);
}
}
private String getControllerTarget(Node node) {
String setControllerStr = null;
- String controllerIpStr = null;
short openflowPort = Constants.OPENFLOW_PORT;
//Look at user configuration.
//TODO: In case we move to config subsystem to expose these user facing parameter,
// we will have to modify this code.
- controllerIpStr = getControllerIPAddress();
+ String controllerIpStr = getControllerIPAddress();
if(controllerIpStr == null){
// Check if ovsdb node has connection info
if(connectionInfo != null && connectionInfo.getLocalIp() != null) {
controllerIpStr = new String(connectionInfo.getLocalIp().getValue());
}else{
- LOGGER.warn("Ovsdb Node does not contains connection info : {}",node);
+ LOG.warn("Ovsdb Node does not contains connection info : {}", node);
}
}
}else {
if(controllerIpStr == null) {
// Neither user provided ip nor ovsdb node has controller ip, Lets use local machine ip address
- LOGGER.debug("Use local machine ip address as a OpenFlow Controller ip address");
+ LOG.debug("Use local machine ip address as a OpenFlow Controller ip address");
controllerIpStr = getLocalControllerHostIpAddress();
}
if(controllerIpStr != null){
- LOGGER.debug("Targe OpenFlow Controller found : {}",controllerIpStr);
+ LOG.debug("Targe OpenFlow Controller found : {}", controllerIpStr);
setControllerStr = Constants.OPENFLOW_CONNECTION_PROTOCOL + ":" + controllerIpStr + ":" + openflowPort;
}else {
- LOGGER.warn("Failed to determine OpenFlow controller ip address");
+ LOG.warn("Failed to determine OpenFlow controller ip address");
}
return setControllerStr;
}
String ipaddress = null;
try{
for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();ifaces.hasMoreElements();){
- NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
+ NetworkInterface iface = ifaces.nextElement();
for (Enumeration<InetAddress> inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
- InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
+ InetAddress inetAddr = inetAddrs.nextElement();
if (!inetAddr.isLoopbackAddress() && inetAddr.isSiteLocalAddress()) {
ipaddress = inetAddr.getHostAddress();
break;
}
}
}catch (Exception e){
- LOGGER.warn("Exception while fetching local host ip address ",e);
+ LOG.warn("Exception while fetching local host ip address ", e);
}
return ipaddress;
}
/*
- * Copyright (C) 2013 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal, Brent Salisbury, Sam Hague, Dave Tucker
*/
+
package org.opendaylight.ovsdb.openstack.netvirt.impl;
import com.google.common.collect.Maps;
import org.slf4j.LoggerFactory;
public class ConfigurationServiceImpl implements ConfigurationService, ConfigInterface {
- static final Logger logger = LoggerFactory.getLogger(ConfigurationServiceImpl.class);
+ private static final Logger LOG = LoggerFactory.getLogger(ConfigurationServiceImpl.class);
private String integrationBridgeName;
private String networkBridgeName;
if (tunnelEndpoint != null) {
try {
address = InetAddress.getByName(tunnelEndpoint);
+ LOG.debug("Tunnel Endpoint for Node {} {}", node, address.getHostAddress());
} catch (UnknownHostException e) {
- logger.error("Error populating Tunnel Endpoint for Node {} ", node, e);
+ LOG.error("Error populating Tunnel Endpoint for Node {} ", node, e);
}
- logger.debug("Tunnel Endpoint for Node {} {}", node, address.getHostAddress());
}
return address;
}
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Dave Tucker, Flavio Fernandes
*/
package org.opendaylight.ovsdb.openstack.netvirt.impl;
import java.util.concurrent.TimeUnit;
public class EventDispatcherImpl implements EventDispatcher, ConfigInterface {
- static final Logger logger = LoggerFactory.getLogger(EventDispatcher.class);
+ private static final Logger LOG = LoggerFactory.getLogger(EventDispatcher.class);
private ExecutorService eventHandler;
private volatile BlockingQueue<AbstractEvent> events;
private AbstractHandler[] handlers;
public void run() {
Thread t = Thread.currentThread();
t.setName("EventDispatcherImpl");
- logger.info("EventDispatcherImpl: started {}", t.getName());
+ LOG.info("EventDispatcherImpl: started {}", t.getName());
while (true) {
AbstractEvent ev;
try {
ev = events.take();
} catch (InterruptedException e) {
- logger.info("The event handler thread was interrupted, shutting down", e);
+ LOG.info("The event handler thread was interrupted, shutting down", e);
return;
}
try {
dispatchEvent(ev);
} catch (Exception e) {
- logger.error("Exception in dispatching event "+ev.toString(), e);
+ LOG.error("Exception in dispatching event {}", ev.toString(), e);
}
}
}
});
- logger.debug("event dispatcher is started");
+ LOG.debug("event dispatcher is started");
}
void stop() {
if (!eventHandler.awaitTermination(10, TimeUnit.SECONDS)) {
eventHandler.shutdownNow();
// Wait a while for tasks to respond to being cancelled
- if (!eventHandler.awaitTermination(10, TimeUnit.SECONDS))
- logger.error("Dispatcher's event handler did not terminate");
+ 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
// Preserve interrupt status
Thread.currentThread().interrupt();
}
- logger.debug("event dispatcher is stopped");
+ LOG.debug("event dispatcher is stopped");
}
private void dispatchEvent(AbstractEvent ev) {
AbstractHandler handler = handlers[ev.getHandlerType().ordinal()];
if (handler == null) {
- logger.warn("event dispatcher found no handler for {}", ev);
+ LOG.warn("event dispatcher found no handler for {}", ev);
return;
}
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)){
- logger.error("Abstract handler reg failed to provide a valid handler type: {} ref: {} handler: {}",
+ LOG.error("Abstract handler reg failed to provide a valid handler type: {} ref: {} handler: {}",
handlerTypeObject, ref.getClass().getName(), handler.getClass().getName());
return;
}
AbstractEvent.HandlerType handlerType = (AbstractEvent.HandlerType) handlerTypeObject;
handlers[handlerType.ordinal()] = handler;
- logger.info("eventHandlerAdded: handler: {}, pid: {}, type: {}",
+ LOG.info("eventHandlerAdded: handler: {}, pid: {}, type: {}",
handler.getClass().getName(), pid, handlerType);
}
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)){
- logger.error("Abstract handler unreg failed to provide a valid handler type " + handlerTypeObject);
+ LOG.error("Abstract handler unreg failed to provide a valid handler type {}", handlerTypeObject);
return;
}
AbstractEvent.HandlerType handlerType = (AbstractEvent.HandlerType) handlerTypeObject;
handlers[handlerType.ordinal()] = null;
- logger.debug("Event handler for type {} unregistered pid {}", handlerType, pid);
+ LOG.debug("Event handler for type {} unregistered pid {}", handlerType, pid);
}
/**
@Override
public void enqueueEvent(AbstractEvent event) {
if (event == null) {
- logger.warn("enqueueEvent: event is null");
+ LOG.warn("enqueueEvent: event is null");
return;
}
try {
events.put(event);
} catch (InterruptedException e) {
- logger.error("Thread was interrupted while trying to enqueue event ", e);
+ LOG.error("Thread was interrupted while trying to enqueue event ", e);
}
}
+/*
+ * 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.ovsdb.openstack.netvirt.impl;
import com.google.common.base.Optional;
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Dave Tucker, Flavio Fernandes
*/
+
package org.opendaylight.ovsdb.openstack.netvirt.impl;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.opendaylight.ovsdb.openstack.netvirt.ConfigInterface;
import org.opendaylight.ovsdb.openstack.netvirt.api.*;
import org.opendaylight.ovsdb.utils.servicehelper.ServiceHelper;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
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 com.google.common.base.Preconditions;
+import com.google.common.util.concurrent.FutureCallback;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
+
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
/**
* Neutron L3 Adapter implements a hub-like adapter for the various Neutron events. Based on
* as well as the multi-tenant router forwarding provider.
*/
public class NeutronL3Adapter implements ConfigInterface {
- private static final Logger LOGGER = LoggerFactory.getLogger(NeutronL3Adapter.class);
+ 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 OutboundNatProvider outboundNatProvider;
private volatile ArpProvider arpProvider;
private volatile RoutingProvider routingProvider;
+ private volatile GatewayMacResolver gatewayMacResolver;
private class FloatIpData {
private final Long dpid; // br-int of node where floating ip is associated with tenant port
private Boolean enabled = false;
private Boolean flgDistributedARPEnabled = true;
private Southbound southbound;
+ private final ExecutorService gatewayMacResolverPool = Executors.newFixedThreadPool(5);
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 DEFAULT_EXT_RTR_MAC = "00:00:5E:00:01:01";
public NeutronL3Adapter() {
- LOGGER.info(">>>>>> NeutronL3Adapter constructor {}", this.getClass());
+ LOG.info(">>>>>> NeutronL3Adapter constructor {}", this.getClass());
}
private void initL3AdapterMembers() {
}
this.enabled = true;
- LOGGER.info("OVSDB L3 forwarding is enabled");
+ LOG.info("OVSDB L3 forwarding is enabled");
if (configurationService.isDistributedArpDisabled()) {
this.flgDistributedARPEnabled = false;
- LOGGER.info("Distributed ARP responder is disabled");
+ LOG.info("Distributed ARP responder is disabled");
} else {
- LOGGER.debug("Distributed ARP responder is enabled");
+ LOG.debug("Distributed ARP responder is enabled");
}
} else {
- LOGGER.debug("OVSDB L3 forwarding is disabled");
+ LOG.debug("OVSDB L3 forwarding is disabled");
}
}
* @param subnet An instance of NeutronSubnet object.
*/
public void handleNeutronSubnetEvent(final NeutronSubnet subnet, Action action) {
- LOGGER.debug("Neutron subnet {} event : {}", action, subnet.toString());
- if (!this.enabled) {
- return;
- }
+ LOG.debug("Neutron subnet {} event : {}", action, subnet.toString());
}
/**
* @param neutronPort An instance of NeutronPort object.
*/
public void handleNeutronPortEvent(final NeutronPort neutronPort, Action action) {
- LOGGER.debug("Neutron port {} event : {}", action, neutronPort.toString());
+ LOG.debug("Neutron port {} event : {}", action, neutronPort.toString());
if (!this.enabled) {
return;
}
final boolean isDelete = action == Action.DELETE;
+ if (neutronPort.getDeviceOwner().equalsIgnoreCase(OWNER_ROUTER_GATEWAY)){
+ if(!isDelete){
+ Node externalBridgeNode = getExternalBridgeNode();
+ if(externalBridgeNode != null){
+ LOG.info("Port {} is network router gateway interface, "
+ + "triggering gateway resolution for the attached external network on node {}", neutronPort, externalBridgeNode);
+ this.triggerGatewayMacResolver(externalBridgeNode, neutronPort);
+ }else{
+ LOG.error("Did not find Node that has external bridge (br-ex), Gateway resolution failed");
+ }
+ }else{
+ NeutronNetwork externalNetwork = neutronNetworkCache.getNetwork(neutronPort.getNetworkUUID());
+
+ if(externalNetwork != null){
+ if(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)) {
+
for (Neutron_IPs neutronIP : neutronPort.getFixedIPs()) {
NeutronRouter_Interface neutronRouterInterface =
new NeutronRouter_Interface(neutronIP.getSubnetUUID(), neutronPort.getPortUUID());
// there.
//
if (!isDelete) {
- for (Neutron_IPs neutronIP : neutronPort.getFixedIPs()) {
- NeutronRouter_Interface neutronRouterInterface =
+ if (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);
+ if (neutronRouterInterface != null) {
+ this.handleNeutronRouterInterfaceEvent(null /*neutronRouter*/, neutronRouterInterface, action);
+ }
}
}
}
* @param neutronRouter An instance of NeutronRouter object.
*/
public void handleNeutronRouterEvent(final NeutronRouter neutronRouter, Action action) {
- LOGGER.debug("Neutron router {} event : {}", action, neutronRouter.toString());
- if (!this.enabled) {
- return;
- }
+ LOG.debug("Neutron router {} event : {}", action, neutronRouter.toString());
}
/**
public void handleNeutronRouterInterfaceEvent(final NeutronRouter neutronRouter,
final NeutronRouter_Interface neutronRouterInterface,
Action action) {
- LOGGER.debug("Router interface {} got event {}. Subnet {}",
+ LOG.debug("Router interface {} got event {}. Subnet {}",
neutronRouterInterface.getPortUUID(),
action,
neutronRouterInterface.getSubnetUUID());
Action actionIn) {
Preconditions.checkNotNull(neutronFloatingIP);
- LOGGER.debug(" Floating IP {} {}<->{}, network uuid {}", actionIn,
+ LOG.debug(" Floating IP {} {}<->{}, network uuid {}", actionIn,
neutronFloatingIP.getFixedIPAddress(),
neutronFloatingIP.getFloatingIPAddress(),
neutronFloatingIP.getFloatingNetworkUUID());
final FloatIpData fid = floatIpDataMapCache.get(neutronFloatingIP.getID());
if (fid == null) {
- LOGGER.trace("programFlowsForFloatingIPInboundAdd {} for {} uuid {} not in local cache",
+ LOG.trace("programFlowsForFloatingIPInboundAdd {} for {} uuid {} not in local cache",
action, neutronFloatingIP.getFloatingIPAddress(), neutronFloatingIP.getID());
return;
}
final FloatIpData fid = floatIpDataMapCache.get(neutronFloatingIP.getID());
if (fid == null) {
- LOGGER.trace("programFlowsForFloatingIPOutbound {} for {} uuid {} not in local cache",
+ LOG.trace("programFlowsForFloatingIPOutbound {} for {} uuid {} not in local cache",
action, neutronFloatingIP.getFloatingIPAddress(), neutronFloatingIP.getID());
return;
}
Preconditions.checkNotNull(neutronFloatingIP.getFloatingIPAddress());
if (floatIpDataMapCache.get(neutronFloatingIP.getID()) != null) {
- LOGGER.trace("programFlowsForFloatingIPArpAdd for neutronFloatingIP {} uuid {} is already done",
+ LOG.trace("programFlowsForFloatingIPArpAdd for neutronFloatingIP {} uuid {} is already done",
neutronFloatingIP.getFloatingIPAddress(), neutronFloatingIP.getID());
return;
}
providerSegmentationId == null || providerSegmentationId.isEmpty() ||
floatingIpMac == null || floatingIpMac.isEmpty() ||
neutronRouterMac == null || neutronRouterMac.isEmpty()) {
- LOGGER.trace("Floating IP {}<->{}, incomplete floatPort {} tenantPortUuid {} seg {} mac {} rtrMac {}",
+ LOG.trace("Floating IP {}<->{}, incomplete floatPort {} tenantPortUuid {} seg {} mac {} rtrMac {}",
fixedIpAddress,
floatingIpAddress,
neutronPortForFloatIp,
final Long dpId = nodeIfPair.getLeft();
final Long ofPort = findOFPortForExtPatch(dpId);
if (ofPort == null) {
- LOGGER.warn("Unable to locate OF port of patch port to connect floating ip to external bridge. dpid {}",
+ LOG.warn("Unable to locate OF port of patch port to connect floating ip to external bridge. dpid {}",
dpId);
return;
}
final FloatIpData floatIpData = new FloatIpData(dpId, ofPort, providerSegmentationId, floatingIpMac,
floatingIpAddress, fixedIpAddress, neutronRouterMac);
floatIpDataMapCache.put(neutronFloatingIP.getID(), floatIpData);
- LOGGER.info("Floating IP {}<->{} programmed ARP mac {} on OFport {} seg {} dpid {}",
+ 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 = floatIpDataMapCache.get(neutronFloatingIPUuid);
if (floatIpData == null) {
- LOGGER.trace("programFlowsForFloatingIPArpDelete for uuid {} is not needed", neutronFloatingIPUuid);
+ LOG.trace("programFlowsForFloatingIPArpDelete for uuid {} is not needed", neutronFloatingIPUuid);
return;
}
if (programStaticArpStage1(floatIpData.dpid, encodeExcplicitOFPort(floatIpData.ofPort), floatIpData.macAddress,
floatIpData.floatingIpAddress, Action.DELETE)) {
floatIpDataMapCache.remove(neutronFloatingIPUuid);
- LOGGER.info("Floating IP {} un-programmed ARP mac {} on {} dpid {}",
+ LOG.info("Floating IP {} un-programmed ARP mac {} on {} dpid {}",
floatIpData.floatingIpAddress, floatIpData.macAddress, floatIpData.ofPort, floatIpData.dpid);
}
}
- private final NeutronPort findNeutronPortForFloatingIp(final String floatingIpUuid) {
+ private NeutronPort findNeutronPortForFloatingIp(final String floatingIpUuid) {
for (NeutronPort neutronPort : neutronPortCache.getAllPorts()) {
if (neutronPort.getDeviceOwner().equals(OWNER_FLOATING_IP) &&
neutronPort.getDeviceID().equals(floatingIpUuid)) {
return null;
}
- private final Long findOFPortForExtPatch(Long dpId) {
+ 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.longValue();
+ final long dpidPrimitive = dpId;
for (Node node : nodeCacheManager.getBridgeNodes()) {
if (dpidPrimitive == southbound.getDataPathId(node)) {
final OvsdbTerminationPointAugmentation terminationPointOfBridge =
* @param neutronNetwork An {@link org.opendaylight.neutron.spi.NeutronNetwork} instance of NeutronFloatingIP object.
*/
public void handleNeutronNetworkEvent(final NeutronNetwork neutronNetwork, Action action) {
- LOGGER.debug("neutronNetwork {}: network: {}", action, neutronNetwork);
- if (!this.enabled) {
- return;
- }
+ LOG.debug("neutronNetwork {}: network: {}", action, neutronNetwork);
}
//
*/
public void handleInterfaceEvent(final Node bridgeNode, final OvsdbTerminationPointAugmentation intf,
final NeutronNetwork neutronNetwork, Action action) {
- LOGGER.debug("southbound interface {} node:{} interface:{}, neutronNetwork:{}",
+ LOG.debug("southbound interface {} node:{} interface:{}, neutronNetwork:{}",
action, bridgeNode.getNodeId().getValue(), intf.getName(), neutronNetwork);
if (!this.enabled) {
return;
final Long dpId = getDpidForIntegrationBridge(bridgeNode);
final Uuid interfaceUuid = intf.getInterfaceUuid();
- LOGGER.trace("southbound interface {} node:{} interface:{}, neutronNetwork:{} port:{} dpid:{} intfUuid:{}",
+ LOG.trace("southbound interface {} node:{} interface:{}, neutronNetwork:{} port:{} dpid:{} intfUuid:{}",
action, bridgeNode.getNodeId().getValue(), intf.getName(), neutronNetwork, neutronPort, dpId, interfaceUuid);
if (neutronPort != null) {
private void handleInterfaceEventAdd(final String neutronPortUuid, Long dpId, final Uuid interfaceUuid) {
neutronPortToDpIdCache.put(neutronPortUuid, new ImmutablePair<>(dpId, interfaceUuid));
- LOGGER.debug("handleInterfaceEvent add cache entry NeutronPortUuid {} : dpid {}, ifUuid {}",
+ LOG.debug("handleInterfaceEvent add cache entry NeutronPortUuid {} : dpid {}, ifUuid {}",
neutronPortUuid, dpId, interfaceUuid.getValue());
}
for (Map.Entry<String, Pair<Long, Uuid>> entry : neutronPortToDpIdCache.entrySet()) {
final String currPortUuid = entry.getKey();
if (intf.getInterfaceUuid().equals(entry.getValue().getRight())) {
- LOGGER.debug("handleInterfaceEventDelete remove cache entry NeutronPortUuid {} : dpid {}, ifUuid {}",
+ LOG.debug("handleInterfaceEventDelete remove cache entry NeutronPortUuid {} : dpid {}, ifUuid {}",
currPortUuid, dpId, intf.getInterfaceUuid().getValue());
neutronPortToDpIdCache.remove(currPortUuid);
break;
final Action action = isDelete ? Action.DELETE : Action.ADD;
List<Node> nodes = nodeCacheManager.getBridgeNodes();
if (nodes.isEmpty()) {
- LOGGER.trace("updateL3ForNeutronPort has no nodes to work with");
+ LOG.trace("updateL3ForNeutronPort has no nodes to work with");
}
for (Node node : nodes) {
final Long dpid = getDpidForIntegrationBridge(node);
programL3ForwardingStage1(node, dpid, providerSegmentationId, tenantMac, tenantIpStr, action);
// Configure distributed ARP responder
- if (true == flgDistributedARPEnabled) {
+ if (flgDistributedARPEnabled) {
programStaticArpStage1(dpid, providerSegmentationId, tenantMac, tenantIpStr, action);
}
}
Action actionForNode) {
// Based on the local cache, figure out whether programming needs to occur. To do this, we
// will look at desired action for node.
- //
+
final String cacheKey = node.getNodeId().getValue() + ":" + providerSegmentationId + ":" + ipStr;
final Boolean isProgrammed = l3ForwardingCache.contains(cacheKey);
if (actionForNode == Action.DELETE && isProgrammed == Boolean.FALSE) {
- LOGGER.trace("programL3ForwardingStage1 for node {} providerId {} mac {} ip {} action {} is already done",
+ LOG.trace("programL3ForwardingStage1 for node {} providerId {} mac {} ip {} action {} is already done",
node.getNodeId().getValue(), providerSegmentationId, macAddress, ipStr, actionForNode);
return;
}
if (actionForNode == Action.ADD && isProgrammed == Boolean.TRUE) {
- LOGGER.trace("programL3ForwardingStage1 for node {} providerId {} mac {} ip {} action {} is already done",
+ LOG.trace("programL3ForwardingStage1 for node {} providerId {} mac {} ip {} action {} is already done",
node.getNodeId().getValue(), providerSegmentationId, macAddress, ipStr, actionForNode);
return;
}
}
if (status.isSuccess()) {
- LOGGER.debug("ProgramL3Forwarding {} for mac:{} addr:{} node:{} action:{}",
+ LOG.debug("ProgramL3Forwarding {} for mac:{} addr:{} node:{} action:{}",
l3ForwardingProvider == null ? "skipped" : "programmed",
macAddress, address, node.getNodeId().getValue(), actionForNode);
} else {
- LOGGER.error("ProgramL3Forwarding failed for mac:{} addr:{} node:{} action:{} status:{}",
+ LOG.error("ProgramL3Forwarding failed for mac:{} addr:{} node:{} action:{} status:{}",
macAddress, address, node.getNodeId().getValue(), actionForNode, status);
}
return status;
neutronNetworkCache.getNetwork(subnet.getNetworkUUID()) : null;
final String destinationSegmentationId = neutronNetwork != null ?
neutronNetwork.getProviderSegmentationID() : null;
- final String gatewayIp = subnet != null ? subnet.getGatewayIP() : null;
final Boolean isExternal = neutronNetwork != null ? neutronNetwork.getRouterExternal() : Boolean.TRUE;
final String cidr = subnet != null ? subnet.getCidr() : null;
final int mask = getMaskLenFromCidr(cidr);
- LOGGER.trace("programFlowsForNeutronRouterInterface called for interface {} isDelete {}",
+ LOG.trace("programFlowsForNeutronRouterInterface called for interface {} isDelete {}",
destNeutronRouterInterface, isDelete);
// in delete path, mac address as well as ip address are not provided. Being so, let's find them from
cidr == null || cidr.isEmpty() ||
macAddress == null || macAddress.isEmpty() ||
ipList == null || ipList.isEmpty()) {
- LOGGER.debug("programFlowsForNeutronRouterInterface is bailing seg:{} cidr:{} mac:{} ip:{}",
+ LOG.debug("programFlowsForNeutronRouterInterface is bailing seg:{} cidr:{} mac:{} ip:{}",
destinationSegmentationId, cidr, macAddress, ipList);
// done: go no further w/out all the info needed...
return;
List<Node> nodes = nodeCacheManager.getBridgeNodes();
if (nodes.isEmpty()) {
- LOGGER.trace("programFlowsForNeutronRouterInterface has no nodes to work with");
+ LOG.trace("programFlowsForNeutronRouterInterface has no nodes to work with");
}
for (Node node : nodes) {
final Long dpid = getDpidForIntegrationBridge(node);
for (Neutron_IPs neutronIP : ipList) {
final String ipStr = neutronIP.getIpAddress();
if (ipStr.isEmpty()) {
- LOGGER.debug("programFlowsForNeutronRouterInterface is skipping node {} ip {}",
+ LOG.debug("programFlowsForNeutronRouterInterface is skipping node {} ip {}",
node.getNodeId().getValue(), ipStr);
continue;
}
final String sourceSubnetId = srcNeutronRouterInterface.getSubnetUUID();
if (sourceSubnetId == null) {
- LOGGER.error("Could not get provider Subnet ID from router interface {}",
+ 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) {
- LOGGER.error("Could not get provider Network ID from subnet {}", sourceSubnetId);
+ LOG.error("Could not get provider Network ID from subnet {}", sourceSubnetId);
return;
}
final NeutronNetwork sourceNetwork = neutronNetworkCache.getNetwork(sourceNetworkId);
if (sourceNetwork == null) {
- LOGGER.error("Could not get provider Network for Network ID {}", sourceNetworkId);
+ LOG.error("Could not get provider Network for Network ID {}", sourceNetworkId);
return;
}
}
final String sourceSegmentationId = sourceNetwork.getProviderSegmentationID();
if (sourceSegmentationId == null) {
- LOGGER.error("Could not get provider Segmentation ID for Subnet {}", sourceSubnetId);
+ LOG.error("Could not get provider Segmentation ID for Subnet {}", sourceSubnetId);
return;
}
if (sourceSegmentationId.equals(destinationSegmentationId)) {
if (cidr2 == null || cidr2.isEmpty() ||
macAddress2 == null || macAddress2.isEmpty() ||
ipList2 == null || ipList2.isEmpty()) {
- LOGGER.trace("programFlowsForNeutronRouterInterfacePair reflexive is bailing seg:{} cidr:{} mac:{} ip:{}",
+ 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;
final Boolean isProgrammed = routerInterfacesCache.contains(cacheKey);
if (actionForNode == Action.DELETE && isProgrammed == Boolean.FALSE) {
- LOGGER.trace("programRouterInterfaceStage1 for node {} sourceSegId {} destSegId {} mac {} ip {} mask {}" +
+ LOG.trace("programRouterInterfaceStage1 for node {} sourceSegId {} destSegId {} mac {} ip {} mask {}" +
" action {} is already done",
node.getNodeId().getValue(), sourceSegmentationId, destinationSegmentationId,
macAddress, ipStr, mask, actionForNode);
return;
}
if (actionForNode == Action.ADD && isProgrammed == Boolean.TRUE) {
- LOGGER.trace("programRouterInterfaceStage1 for node {} sourceSegId {} destSegId {} mac {} ip {} mask {}" +
+ LOG.trace("programRouterInterfaceStage1 for node {} sourceSegId {} destSegId {} mac {} ip {} mask {}" +
" action {} is already done",
node.getNodeId().getValue(), sourceSegmentationId, destinationSegmentationId,
macAddress, ipStr, mask, actionForNode);
}
if (status.isSuccess()) {
- LOGGER.debug("ProgramRouterInterface {} for mac:{} addr:{}/{} node:{} srcTunId:{} destTunId:{} action:{}",
+ LOG.debug("ProgramRouterInterface {} for mac:{} addr:{}/{} node:{} srcTunId:{} destTunId:{} action:{}",
routingProvider == null ? "skipped" : "programmed",
macAddress, address, mask, node.getNodeId().getValue(), sourceSegmentationId, destinationSegmentationId,
actionForNode);
} else {
- LOGGER.error("ProgramRouterInterface failed for mac:{} addr:{}/{} node:{} srcTunId:{} destTunId:{} action:{} status:{}",
+ LOG.error("ProgramRouterInterface failed for mac:{} addr:{}/{} node:{} srcTunId:{} destTunId:{} action:{} status:{}",
macAddress, address, mask, node.getNodeId().getValue(), sourceSegmentationId, destinationSegmentationId,
actionForNode, status);
}
final Boolean isProgrammed = staticArpEntryCache.contains(cacheKey);
if (action == Action.DELETE && isProgrammed == Boolean.FALSE) {
- LOGGER.trace("programStaticArpStage1 dpid {} segOrOfPort {} mac {} ip {} action {} is already done",
+ LOG.trace("programStaticArpStage1 dpid {} segOrOfPort {} mac {} ip {} action {} is already done",
dpid, segOrOfPort, macAddress, ipStr, action);
return true;
}
if (action == Action.ADD && isProgrammed == Boolean.TRUE) {
- LOGGER.trace("programStaticArpStage1 dpid {} segOrOfPort {} mac {} ip {} action {} is already done",
+ LOG.trace("programStaticArpStage1 dpid {} segOrOfPort {} mac {} ip {} action {} is already done",
dpid, segOrOfPort, macAddress, ipStr, action);
return true;
}
}
if (status.isSuccess()) {
- LOGGER.debug("ProgramStaticArp {} for mac:{} addr:{} dpid:{} segOrOfPort:{} action:{}",
+ LOG.debug("ProgramStaticArp {} for mac:{} addr:{} dpid:{} segOrOfPort:{} action:{}",
arpProvider == null ? "skipped" : "programmed",
macAddress, address, dpid, segOrOfPort, action);
} else {
- LOGGER.error("ProgramStaticArp failed for mac:{} addr:{} dpid:{} segOrOfPort:{} action:{} status:{}",
+ LOG.error("ProgramStaticArp failed for mac:{} addr:{} dpid:{} segOrOfPort:{} action:{} status:{}",
macAddress, address, dpid, segOrOfPort, action, status);
}
return status;
final Boolean isProgrammed = inboundIpRewriteCache.contains(cacheKey);
if (action == Action.DELETE && isProgrammed == Boolean.FALSE) {
- LOGGER.trace("programInboundIpRewriteStage1 dpid {} OFPort {} seg {} matchAddress {} rewriteAddress {}" +
+ LOG.trace("programInboundIpRewriteStage1 dpid {} OFPort {} seg {} matchAddress {} rewriteAddress {}" +
" action {} is already done",
dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action);
return true;
}
if (action == Action.ADD && isProgrammed == Boolean.TRUE) {
- LOGGER.trace("programInboundIpRewriteStage1 dpid {} OFPort {} seg {} matchAddress {} rewriteAddress {}" +
+ LOG.trace("programInboundIpRewriteStage1 dpid {} OFPort {} seg {} matchAddress {} rewriteAddress {}" +
" action is already done",
dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action);
return true;
if (status.isSuccess()) {
final boolean isSkipped = inboundNatProvider == null;
- LOGGER.debug("programInboundIpRewriteStage2 {} for dpid:{} ofPort:{} seg:{} match:{} rewrite:{} action:{}",
+ LOG.debug("programInboundIpRewriteStage2 {} for dpid:{} ofPort:{} seg:{} match:{} rewrite:{} action:{}",
isSkipped ? "skipped" : "programmed",
dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action);
} else {
- LOGGER.error("programInboundIpRewriteStage2 failed for dpid:{} ofPort:{} seg:{} match:{} rewrite:{} action:{}" +
+ LOG.error("programInboundIpRewriteStage2 failed for dpid:{} ofPort:{} seg:{} match:{} rewrite:{} action:{}" +
" status:{}",
dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action,
status);
final Boolean isProgrammed = outboundIpRewriteExclusionCache.contains(cacheKey);
if (actionForRewriteExclusion == Action.DELETE && isProgrammed == Boolean.FALSE) {
- LOGGER.trace("programIpRewriteExclusionStage1 node {} providerId {} cidr {} action {} is already done",
+ LOG.trace("programIpRewriteExclusionStage1 node {} providerId {} cidr {} action {} is already done",
node.getNodeId().getValue(), providerSegmentationId, cidr, actionForRewriteExclusion);
return;
}
if (actionForRewriteExclusion == Action.ADD && isProgrammed == Boolean.TRUE) {
- LOGGER.trace("programIpRewriteExclusionStage1 node {} providerId {} cidr {} action {} is already done",
+ LOG.trace("programIpRewriteExclusionStage1 node {} providerId {} cidr {} action {} is already done",
node.getNodeId().getValue(), providerSegmentationId, cidr, actionForRewriteExclusion);
return;
}
if (status.isSuccess()) {
final boolean isSkipped = outboundNatProvider == null;
- LOGGER.debug("IpRewriteExclusion {} for cidr:{} node:{} action:{}",
+ LOG.debug("IpRewriteExclusion {} for cidr:{} node:{} action:{}",
isSkipped ? "skipped" : "programmed",
cidr, node.getNodeId().getValue(), actionForNode);
} else {
- LOGGER.error("IpRewriteExclusion failed for cidr:{} node:{} action:{} status:{}",
+ LOG.error("IpRewriteExclusion failed for cidr:{} node:{} action:{} status:{}",
cidr, node.getNodeId().getValue(), actionForNode, status);
}
return status;
final Boolean isProgrammed = outboundIpRewriteCache.contains(cacheKey);
if (action == Action.DELETE && isProgrammed == Boolean.FALSE) {
- LOGGER.trace("programOutboundIpRewriteStage1 dpid {} seg {} fixedIpAddress {} floatIp {} action {} " +
+ LOG.trace("programOutboundIpRewriteStage1 dpid {} seg {} fixedIpAddress {} floatIp {} action {} " +
"is already done",
fid.dpid, fid.segId, fid.fixedIpAddress, fid.floatingIpAddress, action);
return;
}
if (action == Action.ADD && isProgrammed == Boolean.TRUE) {
- LOGGER.trace("programOutboundIpRewriteStage1 dpid {} seg {} fixedIpAddress {} floatIp {} action {} " +
+ LOG.trace("programOutboundIpRewriteStage1 dpid {} seg {} fixedIpAddress {} floatIp {} action {} " +
"is already done",
fid.dpid, fid.segId, fid.fixedIpAddress, fid.floatingIpAddress, action);
return;
if (status.isSuccess()) {
final boolean isSkipped = outboundNatProvider == null;
- LOGGER.debug("programOutboundIpRewriteStage2 {} for dpid {} seg {} fixedIpAddress {} floatIp {}" +
+ LOG.debug("programOutboundIpRewriteStage2 {} for dpid {} seg {} fixedIpAddress {} floatIp {}" +
" action {}",
isSkipped ? "skipped" : "programmed",
fid.dpid, fid.segId, fid.fixedIpAddress, fid.floatingIpAddress, action);
} else {
- LOGGER.error("programOutboundIpRewriteStage2 failed for dpid {} seg {} fixedIpAddress {} floatIp {}" +
+ LOG.error("programOutboundIpRewriteStage2 failed for dpid {} seg {} fixedIpAddress {} floatIp {}" +
" action {} status:{}",
fid.dpid, fid.segId, fid.fixedIpAddress, fid.floatingIpAddress, action, status);
}
return null;
}
+ private Long getDpidForExternalBridge(Node node) {
+ // Check if node is integration 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){
+ for (Neutron_IPs neutronIPs : gatewayPort.getFixedIPs()) {
+ String subnetUUID = neutronIPs.getSubnetUUID();
+ NeutronSubnet extSubnet = neutronSubnetCache.getSubnet(subnetUUID);
+ if (extSubnet.getGatewayIP() == null) {
+ continue;
+ }
+ return extSubnet;
+ }
+ return null;
+ }
+
+ public void triggerGatewayMacResolver(final Node node, final NeutronPort gatewayPort ){
+
+ Preconditions.checkNotNull(node);
+ 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) {
+ LOG.info("Trigger MAC resolution for gateway ip {} on Node {}",externalSubnet.getGatewayIP(),node.getNodeId());
+ ListenableFuture<MacAddress> gatewayMacAddress =
+ gatewayMacResolver.resolveMacAddress(getDpidForExternalBridge(node),
+ new Ipv4Address(externalSubnet.getGatewayIP()),
+ new Ipv4Address(gatewayPort.getFixedIPs().get(0).getIpAddress()),
+ new MacAddress(gatewayPort.getMacAddress()),
+ true);
+ if(gatewayMacAddress != null){
+ Futures.addCallback(gatewayMacAddress, new FutureCallback<MacAddress>(){
+ @Override
+ public void onSuccess(MacAddress result) {
+ if(result != null){
+ if(!result.getValue().equals(externalRouterMac)){
+ updateExternalRouterMac(result.getValue());
+ LOG.info("Resolved MAC address for gateway IP {} is {}", externalSubnet.getGatewayIP(),result.getValue());
+ }
+ }else{
+ LOG.warn("MAC address resolution failed for gateway IP {}", externalSubnet.getGatewayIP());
+ }
+ }
+
+ @Override
+ public void onFailure(Throwable t) {
+ LOG.warn("MAC address resolution failed for gateway IP {}", externalSubnet.getGatewayIP());
+ }
+ }, gatewayMacResolverPool);
+ }
+ } else {
+ LOG.warn("No gateway IP address found for external network {}", externalNetwork);
+ }
+ }
+ }else{
+ LOG.warn("Neutron network not found for router interface {}", gatewayPort);
+ }
+ }
+
/**
* Return String that represents OF port with marker explicitly provided (reverse of MatchUtils:parseExplicitOFPort)
*
(NodeCacheManager) ServiceHelper.getGlobalInstance(NodeCacheManager.class, this);
southbound =
(Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this);
-
+ gatewayMacResolver =
+ (GatewayMacResolver) ServiceHelper.getGlobalInstance(GatewayMacResolver.class, this);
initL3AdapterMembers();
}
routingProvider = (RoutingProvider)impl;
} else if (impl instanceof L3ForwardingProvider) {
l3ForwardingProvider = (L3ForwardingProvider)impl;
+ }else if (impl instanceof GatewayMacResolver) {
+ gatewayMacResolver = (GatewayMacResolver)impl;
}
}
}
* @author Sam Hague (shague@redhat.com)
*/
public class NodeCacheManagerImpl extends AbstractHandler implements NodeCacheManager, ConfigInterface {
- private static final Logger logger = LoggerFactory.getLogger(NodeCacheManagerImpl.class);
- private final Object nodeCacheLock = new Object();
+ private static final Logger LOG = LoggerFactory.getLogger(NodeCacheManagerImpl.class);
private Map<NodeId, Node> nodeCache = new ConcurrentHashMap<>();
private Map<Long, NodeCacheListener> handlers = Maps.newHashMap();
private volatile Southbound southbound;
@Override
public void nodeAdded(Node node) {
- logger.debug("nodeAdded: {}", node);
+ LOG.debug("nodeAdded: {}", node);
enqueueEvent(new NodeCacheManagerEvent(node, Action.UPDATE));
}
@Override
public void nodeRemoved(Node node) {
- logger.debug("nodeRemoved: {}", node);
+ LOG.debug("nodeRemoved: {}", node);
enqueueEvent(new NodeCacheManagerEvent(node, Action.DELETE));
}
}
nodeCache.put(nodeId, node);
- logger.debug("processNodeUpdate: {} Node type {} {}: {}",
+ LOG.debug("processNodeUpdate: {} Node type {} {}: {}",
nodeCache.size(),
southbound.getBridge(node) != null ? "BridgeNode" : "OvsdbNode",
action == Action.ADD ? "ADD" : "UPDATE",
try {
handler.notifyNode(node, action);
} catch (Exception e) {
- logger.error("Failed notifying node add event", e);
+ LOG.error("Failed notifying node add event", e);
}
}
- logger.debug("processNodeUpdate returns");
+ LOG.debug("processNodeUpdate returns");
}
private void processNodeRemoved(Node node) {
try {
handler.notifyNode(node, Action.DELETE);
} catch (Exception e) {
- logger.error("Failed notifying node remove event", e);
+ LOG.error("Failed notifying node remove event", e);
}
}
- logger.warn("processNodeRemoved returns");
+ LOG.warn("processNodeRemoved returns");
}
/**
@Override
public void processEvent(AbstractEvent abstractEvent) {
if (!(abstractEvent instanceof NodeCacheManagerEvent)) {
- logger.error("Unable to process abstract event " + abstractEvent);
+ LOG.error("Unable to process abstract event {}", abstractEvent);
return;
}
NodeCacheManagerEvent ev = (NodeCacheManagerEvent) abstractEvent;
- logger.debug("NodeCacheManagerImpl: dequeue: {}", ev);
+ LOG.debug("NodeCacheManagerImpl: dequeue: {}", ev);
switch (ev.getAction()) {
case DELETE:
processNodeRemoved(ev.getNode());
processNodeUpdate(ev.getNode());
break;
default:
- logger.warn("Unable to process event action " + ev.getAction());
+ 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);
- logger.info("Node cache listener registered, pid {} {}", pid, handler.getClass().getName());
+ LOG.info("Node cache listener registered, pid {} {}", pid, handler.getClass().getName());
}
public void cacheListenerRemoved(final ServiceReference ref){
Long pid = (Long) ref.getProperty(org.osgi.framework.Constants.SERVICE_ID);
handlers.remove(pid);
- logger.debug("Node cache listener unregistered, pid {}", pid);
+ LOG.debug("Node cache listener unregistered, pid {}", pid);
}
@Override
public Map<NodeId,Node> getOvsdbNodes() {
- Map<NodeId,Node> ovsdbNodesMap = new ConcurrentHashMap<NodeId,Node>();
+ 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());
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Dave Tucker, Flavio Fernandes
*/
package org.opendaylight.ovsdb.openstack.netvirt.impl;
/*
- * Copyright (C) 2013 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal, Brent Salisbury, Dave Tucker
*/
+
package org.opendaylight.ovsdb.openstack.netvirt.impl;
import java.util.HashMap;
import com.google.common.collect.Maps;
public class ProviderNetworkManagerImpl implements ConfigInterface, NetworkingProviderManager {
- static final Logger logger = LoggerFactory.getLogger(ProviderNetworkManagerImpl.class);
- private HashMap<Long, ProviderEntry> providers = Maps.newHashMap();
- private HashMap<Node, NetworkingProvider> nodeToProviderMapping = Maps.newHashMap();
+ private static final Logger LOG = LoggerFactory.getLogger(ProviderNetworkManagerImpl.class);
+ private Map<Long, ProviderEntry> providers = Maps.newHashMap();
+ private Map<Node, NetworkingProvider> nodeToProviderMapping = Maps.newHashMap();
private volatile OvsdbInventoryService ovsdbInventoryService;
@Override
Iterable<ProviderEntry> matchingProviders = Iterables.filter(providers.values(), providerEntryPredicate);
if (!matchingProviders.iterator().hasNext()) {
- logger.error("No providers matching {} found", targetVersion);
+ LOG.error("No providers matching {} found", targetVersion);
}
// Return the first match as only have one matching provider today
(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));
- logger.info("Neutron Networking Provider Registered: {}, with {} and pid={}",
+ LOG.info("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);
- logger.info("Neutron Networking Provider Removed: {}", pid);
+ LOG.info("Neutron Networking Provider Removed: {}", pid);
}
@Override
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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.ovsdb.openstack.netvirt.impl;
import java.util.List;
+
import org.opendaylight.neutron.spi.INeutronPortCRUD;
+import org.opendaylight.neutron.spi.INeutronSubnetCRUD;
import org.opendaylight.neutron.spi.NeutronPort;
import org.opendaylight.neutron.spi.NeutronSecurityGroup;
+import org.opendaylight.neutron.spi.NeutronSubnet;
+import org.opendaylight.neutron.spi.Neutron_IPs;
import org.opendaylight.ovsdb.openstack.netvirt.ConfigInterface;
import org.opendaylight.ovsdb.openstack.netvirt.api.Constants;
import org.opendaylight.ovsdb.openstack.netvirt.api.SecurityServicesManager;
import org.opendaylight.ovsdb.openstack.netvirt.api.Southbound;
import org.opendaylight.ovsdb.utils.servicehelper.ServiceHelper;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.*;
+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.BundleContext;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SecurityServicesImpl implements ConfigInterface, SecurityServicesManager {
- static final Logger logger = LoggerFactory.getLogger(TenantNetworkManagerImpl.class);
+ private static final Logger LOG = LoggerFactory.getLogger(TenantNetworkManagerImpl.class);
private volatile INeutronPortCRUD neutronPortCache;
+ private volatile INeutronSubnetCRUD neutronSubnetCache;
private volatile Southbound southbound;
/**
*/
public boolean isPortSecurityReady(OvsdbTerminationPointAugmentation terminationPointAugmentation) {
if (neutronPortCache == null) {
- logger.error("neutron port is null");
+ LOG.error("neutron port is null");
return false;
}
- logger.trace("isPortSecurityReady for {}", terminationPointAugmentation.getName());
+ LOG.trace("isPortSecurityReady for {}", terminationPointAugmentation.getName());
String neutronPortId = southbound.getInterfaceExternalIdsValue(terminationPointAugmentation,
Constants.EXTERNAL_ID_INTERFACE_ID);
if (neutronPortId == null) {
}
String deviceOwner = neutronPort.getDeviceOwner();
if (!deviceOwner.contains("compute")) {
- logger.debug("Port {} is not a compute host, it is a: {}", neutronPortId, deviceOwner);
+ LOG.debug("Port {} is not a compute host, it is a: {}", neutronPortId, deviceOwner);
}
- logger.debug("isPortSecurityReady() is a {} ", deviceOwner);
+ LOG.debug("isPortSecurityReady() is a {} ", deviceOwner);
List<NeutronSecurityGroup> securityGroups = neutronPort.getSecurityGroups();
if (securityGroups.isEmpty()) {
- logger.debug("Check for device: {} does not contain a Security Group for port: {}", deviceOwner,
+ LOG.debug("Check for device: {} does not contain a Security Group for port: {}", deviceOwner,
neutronPortId);
return false;
}
- String vmPort = southbound.getInterfaceExternalIdsValue(terminationPointAugmentation,
- Constants.EXTERNAL_ID_VM_MAC);
- logger.debug("Security Group Check {} DOES contain a Neutron Security Group", neutronPortId);
+ LOG.debug("Security Group Check {} DOES contain a Neutron Security Group", neutronPortId);
return true;
}
*/
public NeutronSecurityGroup getSecurityGroupInPort(OvsdbTerminationPointAugmentation terminationPointAugmentation) {
if (neutronPortCache == null) {
- logger.error("neutron port is null");
+ LOG.error("neutron port is null");
return null;
}
- logger.trace("isPortSecurityReady for {}", terminationPointAugmentation.getName());
+ LOG.trace("isPortSecurityReady for {}", terminationPointAugmentation.getName());
String neutronPortId = southbound.getInterfaceExternalIdsValue(terminationPointAugmentation,
Constants.EXTERNAL_ID_INTERFACE_ID);
if (neutronPortId == null) {
List<NeutronSecurityGroup> neutronSecurityGroups = neutronPort.getSecurityGroups();
if (neutronSecurityGroups != null) {
- NeutronSecurityGroup neutronSecurityGroup = (NeutronSecurityGroup) neutronSecurityGroups.toArray()[0];
- return neutronSecurityGroup;
+ return (NeutronSecurityGroup) neutronSecurityGroups.toArray()[0];
} else {
return null;
}
}
+ @Override
+ public NeutronPort getDHCPServerPort(
+ OvsdbTerminationPointAugmentation terminationPointAugmentation) {
+ if (neutronPortCache == null) {
+ LOG.error("getDHCPServerPort: neutron port is null");
+ return null;
+ }
+ LOG.trace("getDHCPServerPort for {}",
+ terminationPointAugmentation.getName());
+ String neutronPortId = southbound.getInterfaceExternalIdsValue(
+ terminationPointAugmentation,
+ Constants.EXTERNAL_ID_INTERFACE_ID);
+ if (neutronPortId == null) {
+ return null;
+ }
+ NeutronPort neutronPort = neutronPortCache.getPort(neutronPortId);
+ if (neutronPort == null) {
+ LOG.error("getDHCPServerPort: neutron port of {} is not found", neutronPortId);
+ return null;
+ }
+ //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;
+ }
+
+ String networkUUID = neutronPort.getNetworkUUID();
+ for (NeutronPort port : neutronPortCache.getAllPorts()) {
+ if (port.getNetworkUUID() == networkUUID && port.getDeviceOwner().contains("dhcp")) {
+ return port;
+ }
+ }
+
+ return null;
+
+ }
+
+ @Override
+ public boolean isComputePort(OvsdbTerminationPointAugmentation terminationPointAugmentation) {
+ if (neutronPortCache == null) {
+ LOG.error("neutron port is null");
+ return false;
+ }
+ LOG.trace("isComputePort for {}", terminationPointAugmentation.getName());
+ String neutronPortId = southbound.getInterfaceExternalIdsValue(terminationPointAugmentation,
+ Constants.EXTERNAL_ID_INTERFACE_ID);
+ if (neutronPortId == null) {
+ return false;
+ }
+ NeutronPort neutronPort = neutronPortCache.getPort(neutronPortId);
+ if (neutronPort == null) {
+ return false;
+ }
+ String deviceOwner = neutronPort.getDeviceOwner();
+ if (!deviceOwner.contains("compute")) {
+ LOG.debug("isComputePort : Port {} is not a DHCP server port", neutronPortId, deviceOwner);
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public boolean isLastPortinSubnet(Node node, OvsdbTerminationPointAugmentation terminationPointAugmentation) {
+ if (neutronPortCache == null) {
+ LOG.error("isLastPortinSubnet: neutron port is null");
+ return false;
+ }
+ LOG.trace("isLastPortinSubnet: for {}", terminationPointAugmentation.getName());
+ String neutronPortId = southbound.getInterfaceExternalIdsValue(terminationPointAugmentation,
+ Constants.EXTERNAL_ID_INTERFACE_ID);
+ if (neutronPortId == null) {
+ return false;
+ }
+ NeutronPort neutronPort = neutronPortCache.getPort(neutronPortId);
+ 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;
+ }
+ 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) {
+ if(!(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())) {
+ return false;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ return true;
+ }
+
+ @Override
+ public boolean isLastPortinBridge(Node node, OvsdbTerminationPointAugmentation terminationPointAugmentation) {
+ LOG.trace("isLastPortinBridge: for {}", terminationPointAugmentation.getName());
+ List<TerminationPoint> terminationPoints = node.getTerminationPoint();
+ if(terminationPoints != null && !terminationPoints.isEmpty()){
+ for(TerminationPoint tp : terminationPoints){
+ OvsdbTerminationPointAugmentation ovsdbTerminationPointAugmentation =
+ tp.getAugmentation(OvsdbTerminationPointAugmentation.class);
+ if(null!=ovsdbTerminationPointAugmentation)
+ {
+ if(!(ovsdbTerminationPointAugmentation.getName().equals(Constants.INTEGRATION_BRIDGE))
+ && !(terminationPointAugmentation.getInterfaceUuid().equals
+ (ovsdbTerminationPointAugmentation.getInterfaceUuid()))) {
+ return false;
+ }
+ }
+ }
+ }
+ return true;
+ }
+
+ @Override
+ public List<Neutron_IPs> getIpAddress(Node node,
+ OvsdbTerminationPointAugmentation terminationPointAugmentation) {
+ if (neutronPortCache == null) {
+ LOG.error("getIpAddress: neutron port is null");
+ return null;
+ }
+ LOG.trace("getIpAddress: for {}", terminationPointAugmentation.getName());
+ String neutronPortId = southbound.getInterfaceExternalIdsValue(terminationPointAugmentation,
+ Constants.EXTERNAL_ID_INTERFACE_ID);
+ if (neutronPortId == null) {
+ return null;
+ }
+ NeutronPort neutronPort = neutronPortCache.getPort(neutronPortId);
+ if (neutronPort == null) {
+ LOG.error("getIpAddress: neutron port of {} is not found", neutronPortId);
+ return null;
+ }
+ return neutronPort.getFixedIPs();
+ }
+
@Override
public void setDependencies(BundleContext bundleContext, ServiceReference serviceReference) {
southbound =
if (impl instanceof INeutronPortCRUD) {
neutronPortCache = (INeutronPortCRUD)impl;
}
+ else if (impl instanceof INeutronSubnetCRUD) {
+ neutronSubnetCache = (INeutronSubnetCRUD) impl;
+ }
}
}
import org.opendaylight.ovsdb.openstack.netvirt.api.OvsdbTables;
import org.opendaylight.ovsdb.openstack.netvirt.api.Southbound;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Uri;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.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.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;
ovsdbBridgeAugmentationBuilder.setFailMode(
MdsalHelper.OVSDB_FAIL_MODE_MAP.inverse().get("secure"));
setManagedByForBridge(ovsdbBridgeAugmentationBuilder, ovsdbNode.getKey());
+ if (isOvsdbNodeDpdk(ovsdbNode)) {
+ ovsdbBridgeAugmentationBuilder.setDatapathType(DatapathTypeNetdev.class);
+ }
bridgeNodeBuilder.addAugmentation(OvsdbBridgeAugmentation.class, ovsdbBridgeAugmentationBuilder.build());
result = mdsalUtils.put(LogicalDatastoreType.CONFIGURATION, bridgeIid, bridgeNodeBuilder.build());
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);
}
/*
- * Copyright (C) 2013 Red Hat, Inc. and others...
+ * 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
- *
- * Authors : Madhu Venugopal, Brent Salisbury, Dave Tucker
*/
+
package org.opendaylight.ovsdb.openstack.netvirt.impl;
import com.google.common.base.Preconditions;
import org.slf4j.LoggerFactory;
public class TenantNetworkManagerImpl implements ConfigInterface, TenantNetworkManager {
- static final Logger logger = LoggerFactory.getLogger(TenantNetworkManagerImpl.class);
+ private static final Logger LOG = LoggerFactory.getLogger(TenantNetworkManagerImpl.class);
private INeutronNetworkCRUD neutronNetworkCache;
private INeutronPortCRUD neutronPortCache;
private VlanConfigurationCache vlanConfigurationCache;
public void reclaimInternalVlan(Node node, NeutronNetwork network) {
int vlan = vlanConfigurationCache.reclaimInternalVlan(node, network.getID());
if (vlan <= 0) {
- logger.debug("Unable to get an internalVlan for Network {}", network);
+ LOG.debug("Unable to get an internalVlan for Network {}", network);
return;
}
- logger.debug("Removed Vlan {} on {}", vlan);
+ LOG.debug("Removed Vlan {} on {}", vlan);
}
@Override
public void programInternalVlan(Node node, OvsdbTerminationPointAugmentation tp, NeutronNetwork network) {
int vlan = vlanConfigurationCache.getInternalVlan(node, network.getID());
- logger.debug("Programming Vlan {} on {}", vlan, tp);
+ LOG.debug("Programming Vlan {} on {}", vlan, tp);
if (vlan <= 0) {
- logger.debug("Unable to get an internalVlan for Network {}", network);
+ LOG.debug("Unable to get an internalVlan for Network {}", network);
return;
}
public boolean isTenantNetworkPresentInNode(Node node, String segmentationId) {
String networkId = this.getNetworkId(segmentationId);
if (networkId == null) {
- logger.debug("Tenant Network not found with Segmenation-id {}",segmentationId);
+ LOG.debug("Tenant Network not found with Segmenation-id {}", segmentationId);
return false;
}
for (OvsdbTerminationPointAugmentation port : ports) {
String ifaceId = southbound.getInterfaceExternalIdsValue(port, Constants.EXTERNAL_ID_INTERFACE_ID);
if (ifaceId != null && isInterfacePresentInTenantNetwork(ifaceId, networkId)) {
- logger.debug("Tenant Network {} with Segmentation-id {} is present in Node {} / Interface {}",
+ LOG.debug("Tenant Network {} with Segmentation-id {} is present in Node {} / Interface {}",
networkId, segmentationId, node, port);
return true;
}
}
} catch (Exception e) {
- logger.error("Error while trying to determine if network is present on node", e);
+ LOG.error("Error while trying to determine if network is present on node", e);
return false;
}
- logger.debug("Tenant Network {} with Segmenation-id {} is NOT present in Node {}",
+ LOG.debug("Tenant Network {} with Segmenation-id {} is NOT present in Node {}",
networkId, segmentationId, node);
return false;
Preconditions.checkNotNull(neutronPortCache);
NeutronNetwork neutronNetwork = null;
- logger.debug("getTenantNetwork for {}", terminationPointAugmentation);
+ LOG.debug("getTenantNetwork for {}", terminationPointAugmentation);
String neutronPortId = southbound.getInterfaceExternalIdsValue(terminationPointAugmentation,
Constants.EXTERNAL_ID_INTERFACE_ID);
if (neutronPortId != null) {
if (neutronPort != null) {
neutronNetwork = neutronNetworkCache.getNetwork(neutronPort.getNetworkUUID());
if (neutronNetwork != null) {
- logger.debug("mapped to {}", neutronNetwork);
+ LOG.debug("mapped to {}", neutronNetwork);
} else {
- logger.debug("getTenantNetwork: did not find neutronNetwork in cache from neutronPort {}",
+ LOG.debug("getTenantNetwork: did not find neutronNetwork in cache from neutronPort {}",
neutronPortId);
}
} else {
- logger.info("getTenantNetwork did not find neutronPort {} from termination point {}",
+ LOG.info("getTenantNetwork did not find neutronPort {} from termination point {}",
neutronPortId, terminationPointAugmentation.getName());
}
} else {
- logger.debug("getTenantNetwork: did not find {} in external_ids", Constants.EXTERNAL_ID_INTERFACE_ID);
+ LOG.debug("getTenantNetwork: did not find {} in external_ids", Constants.EXTERNAL_ID_INTERFACE_ID);
}
return neutronNetwork;
}
Preconditions.checkNotNull(neutronPortCache);
NeutronPort neutronPort = null;
- logger.trace("getTenantPort for {}", terminationPointAugmentation.getName());
+ LOG.trace("getTenantPort for {}", terminationPointAugmentation.getName());
String neutronPortId = southbound.getInterfaceExternalIdsValue(terminationPointAugmentation,
Constants.EXTERNAL_ID_INTERFACE_ID);
if (neutronPortId != null) {
neutronPort = neutronPortCache.getPort(neutronPortId);
}
if (neutronPort != null) {
- logger.debug("mapped to {}", neutronPort);
+ LOG.debug("mapped to {}", neutronPort);
} else {
- logger.warn("getTenantPort did not find port for {}", terminationPointAugmentation.getName());
+ LOG.warn("getTenantPort did not find port for {}", terminationPointAugmentation.getName());
}
return neutronPort;
/*
- * Copyright (c) 2013 Hewlett-Packard Development Company, L.P. and others
+ * Copyright (c) 2013, 2015 Hewlett-Packard Development Company, L.P. and others. All rights reserved.
*
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
-*/
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
package org.opendaylight.ovsdb.openstack.netvirt.impl;
import org.opendaylight.ovsdb.openstack.netvirt.ConfigInterface;
* @author Sam Hague
*/
public class VlanConfigurationCacheImpl implements ConfigInterface, VlanConfigurationCache {
- static final Logger logger = LoggerFactory.getLogger(VlanConfigurationCacheImpl.class);
+ private static final Logger LOG = LoggerFactory.getLogger(VlanConfigurationCacheImpl.class);
private Map<String, NodeConfiguration> configurationCache = Maps.newConcurrentMap();
private volatile TenantNetworkManager tenantNetworkManager;
private volatile Southbound southbound;
private void initializeNodeConfiguration(Node node, String nodeUuid) {
NodeConfiguration nodeConfiguration = new NodeConfiguration();
- Integer vlan = 0;
- String networkId = null;
List<OvsdbTerminationPointAugmentation> ports = southbound.getTerminationPointsOfBridge(node);
for (OvsdbTerminationPointAugmentation port : ports) {
- vlan = port.getVlanTag().getValue();
- networkId = tenantNetworkManager.getTenantNetwork(port).getNetworkUUID();
+ 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 {
- logger.debug("Node: {} initialized without a vlan", node);
+ LOG.debug("Node: {} initialized without a vlan", node);
}
}
configurationCache.put(nodeUuid, nodeConfiguration);
when(neutronLBPoolMember.getPoolMemberAdminStateIsUp()).thenReturn(true);
when(neutronLBPoolMember.getPoolMemberSubnetID()).thenReturn("subnetID");
- when(neutronLBPoolMember.getPoolMemberID()).thenReturn("pool_memberID");
+ when(neutronLBPoolMember.getID()).thenReturn("pool_memberID");
when(neutronLBPoolMember.getPoolMemberAddress()).thenReturn("pool_member_address");
when(neutronLBPoolMember.getPoolMemberProtoPort()).thenReturn(1);
members.add(neutronLBPoolMember);
NeutronLoadBalancerPoolMember neutronLBPoolMember = mock(NeutronLoadBalancerPoolMember.class);
when(neutronLBPoolMember.getPoolMemberAdminStateIsUp()).thenReturn(true);
when(neutronLBPoolMember.getPoolMemberSubnetID()).thenReturn("subnetID");
- when(neutronLBPoolMember.getPoolMemberID()).thenReturn("pool_memberID");
+ when(neutronLBPoolMember.getID()).thenReturn("pool_memberID");
when(neutronLBPoolMember.getPoolMemberAddress()).thenReturn("pool_member_address");
when(neutronLBPoolMember.getPoolMemberProtoPort()).thenReturn(1);
members.add(neutronLBPoolMember);
@Before
public void setUp() {
neutronLBMember = mock(NeutronLoadBalancerPoolMember.class);
- when(neutronLBMember.getPoolMemberID()).thenReturn("pool_memberID");
+ when(neutronLBMember.getID()).thenReturn("pool_memberID");
when(neutronLBMember.getPoolMemberAddress()).thenReturn("pool_member_address");
when(neutronLBMember.getPoolMemberSubnetID()).thenReturn("pool_member_subnetID");
when(neutronLBMember.getPoolMemberProtoPort()).thenReturn(1);
NeutronLoadBalancerPoolMember neutronLBPoolMember = mock(NeutronLoadBalancerPoolMember.class);
when(neutronLBPoolMember.getPoolMemberAdminStateIsUp()).thenReturn(true);
when(neutronLBPoolMember.getPoolMemberSubnetID()).thenReturn("subnetID");
- when(neutronLBPoolMember.getPoolMemberID()).thenReturn("pool_memberID1");
+ when(neutronLBPoolMember.getID()).thenReturn("pool_memberID1");
when(neutronLBPoolMember.getPoolMemberProtoPort()).thenReturn(1);
members.add(neutronLBPoolMember);
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;
@InjectMocks private NetworkHandler networkHandler;
- @Mock private NeutronNetwork neutronNetwork;
+ @Mock private NeutronNetwork sharedNeutronNetwork;
+ @Mock private NeutronNetwork nonSharedNeutronNetwork;
@Mock private NeutronL3Adapter neutronL3Adapter;
@Mock private TenantNetworkManager tenantNetworkManager;
@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() {
- when(neutronNetwork.isShared())
- .thenReturn(true)
- .thenReturn(false);
- assertEquals("Error, did not return the correct HTTP flag", HttpURLConnection.HTTP_NOT_ACCEPTABLE, networkHandler.canCreateNetwork(neutronNetwork));
- assertEquals("Error, did not return the correct HTTP flag", HttpURLConnection.HTTP_OK, networkHandler.canCreateNetwork(neutronNetwork));
+ assertEquals("Error, did not return the correct HTTP flag", HttpURLConnection.HTTP_NOT_ACCEPTABLE, networkHandler.canCreateNetwork(sharedNeutronNetwork));
+ assertEquals("Error, did not return the correct HTTP flag", HttpURLConnection.HTTP_OK, networkHandler.canCreateNetwork(nonSharedNeutronNetwork));
}
/**
*/
@Test
public void testCanUpdateNetwork() {
- when(neutronNetwork.isShared())
- .thenReturn(true)
- .thenReturn(false);
- assertEquals("Error, did not return the correct HTTP flag", HttpURLConnection.HTTP_NOT_ACCEPTABLE, networkHandler.canUpdateNetwork(neutronNetwork, neutronNetwork));
- assertEquals("Error, did not return the correct HTTP flag", HttpURLConnection.HTTP_OK, networkHandler.canUpdateNetwork(neutronNetwork, neutronNetwork));
+ assertEquals("Error, did not return the correct HTTP flag", HttpURLConnection.HTTP_NOT_ACCEPTABLE, networkHandler.canUpdateNetwork(sharedNeutronNetwork, sharedNeutronNetwork));
+ assertEquals("Error, did not return the correct HTTP flag", HttpURLConnection.HTTP_OK, networkHandler.canUpdateNetwork(nonSharedNeutronNetwork, nonSharedNeutronNetwork));
}
/**
*/
@Test
public void testCanDeleteNetwork() {
- assertEquals("Error, did not return the correct HTTP flag", HttpURLConnection.HTTP_OK, networkHandler.canDeleteNetwork(neutronNetwork));
+ assertEquals("Error, did not return the correct HTTP flag", HttpURLConnection.HTTP_OK, networkHandler.canDeleteNetwork(nonSharedNeutronNetwork));
}
/**
NetworkHandler networkHandlerSpy = Mockito.spy(networkHandler);
NorthboundEvent ev = mock(NorthboundEvent.class);
- when(ev.getNeutronNetwork()).thenReturn(neutronNetwork);
+ when(ev.getNeutronNetwork()).thenReturn(nonSharedNeutronNetwork);
when(ev.getAction()).thenReturn(Action.ADD);
networkHandlerSpy.processEvent(ev);
String portName = "portName";
- List<NeutronNetwork> networks = new ArrayList<NeutronNetwork>();
+ List<NeutronNetwork> networks = new ArrayList<>();
when(neutronNetworkCache.getAllNetworks()).thenReturn(networks);
- List<Node> nodes = new ArrayList<Node>();
+ List<Node> nodes = new ArrayList<>();
nodes.add(mock(Node.class));
when(nodeCacheManager.getNodes()).thenReturn(nodes);
- List<String> phyIfName = new ArrayList<String>();
+ List<String> phyIfName = new ArrayList<>();
phyIfName.add(portName);
when(bridgeConfigurationManager.getAllPhysicalInterfaceNames(any(Node.class))).thenReturn(phyIfName );
- List<OvsdbTerminationPointAugmentation> ports = new ArrayList<OvsdbTerminationPointAugmentation>();
+ 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(southbound.isTunnel(any(OvsdbTerminationPointAugmentation.class))).thenReturn(true, false);
-
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));
package org.opendaylight.ovsdb.openstack.netvirt.impl;
-import static org.junit.Assume.*;
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.when;
+import static org.powermock.api.mockito.PowerMockito.verifyPrivate;
import java.lang.reflect.Field;
import java.util.Random;
* Unit test for {@link EventDispatcherImpl}
*/
@RunWith(PowerMockRunner.class)
-@PrepareForTest(ServiceHelper.class)
+@PrepareForTest({ServiceHelper.class, EventDispatcherImpl.class})
public class EventDispatcherImplTest {
@InjectMocks private EventDispatcherImpl eventDispatcherImpl;
public void setUp() {
Random r = new Random();
- eventDispatcherImpl.start();
-
when(ref.getProperty(org.osgi.framework.Constants.SERVICE_ID)).thenReturn(r.nextLong());
when(ref.getProperty(Constants.EVENT_HANDLER_TYPE_PROPERTY)).thenReturn(handlerTypeObject);
}
assertEquals("Error, did not return the expected size, nothing has been added yet", 0, events.size());
- eventDispatcherImpl.enqueueEvent(mock(AbstractEvent.class));
- eventDispatcherImpl.enqueueEvent(mock(AbstractEvent.class));
- eventDispatcherImpl.enqueueEvent(mock(AbstractEvent.class));
- eventDispatcherImpl.enqueueEvent(mock(AbstractEvent.class));
+ AbstractEvent mockEvent = mock(AbstractEvent.class);
+ when(mockEvent.getHandlerType()).thenReturn(handlerTypeObject);
+ eventDispatcherImpl.enqueueEvent(mockEvent);
+ eventDispatcherImpl.enqueueEvent(mockEvent);
+ eventDispatcherImpl.enqueueEvent(mockEvent);
+ eventDispatcherImpl.enqueueEvent(mockEvent);
- assumeTrue("Error, did not return the expected size", 4 == events.size());
+ verifyPrivate(eventDispatcherImpl, times(4)).invoke("dispatchEvent", mockEvent);
}
private Object getField(String fieldName) throws Exception {
NeutronFloatingIP neutronFloatingIP = mock(NeutronFloatingIP.class);
when(neutronFloatingIP.getFixedIPAddress()).thenReturn(FIXED_IP_ADDRESS);
when(neutronFloatingIP.getFloatingIPAddress()).thenReturn(FLOATING_IP_ADDRESS);
- when(neutronFloatingIP.getFloatingIPUUID()).thenReturn(UUID);
+ when(neutronFloatingIP.getID()).thenReturn(UUID);
// Suppress the called to these functions
MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "programFlowsForFloatingIPArpAdd", NeutronFloatingIP.class));
@SuppressWarnings("unchecked")
@Test
public void testProgramOutboundIpRewriteStage1() throws Exception{
- HashSet<String> outboundIpRewriteCache = new HashSet<String>();
+ Set<String> outboundIpRewriteCache = new HashSet<String>();
MemberModifier.suppress(MemberMatcher.method(NeutronL3Adapter.class, "programOutboundIpRewriteStage2", floatingIpClass, Action.class));
import java.lang.reflect.Field;
import java.util.HashMap;
+import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
@Mock private OvsdbInventoryService ovsdbInventoryService;
- @Spy private HashMap<Node, NetworkingProvider> nodeToProviderMapping = Maps.newHashMap();
+ @Spy private Map<Node, NetworkingProvider> nodeToProviderMapping = Maps.newHashMap();
/**
* Test method {@link ProviderNetworkManagerImpl#getProvider(Node)}
*/
@Test
public void testProviderAddedAndRemoved() throws Exception {
- HashMap<?, ?> map = (HashMap<?, ?>) getField("providers");
+ Map<?, ?> map = (HashMap<?, ?>) getField("providers");
ServiceReference<?> ref = mock(ServiceReference.class);
when(ref.getProperty(org.osgi.framework.Constants.SERVICE_ID)).thenReturn(Long.valueOf(1));
NeutronNetwork neutronNetwork = mock(NeutronNetwork.class);
when(neutronNetwork.getProviderSegmentationID()).thenReturn(SEG_ID);
when(neutronNetwork.getNetworkUUID()).thenReturn(NETWORK_ID);
- ArrayList<NeutronNetwork> listNeutronNetwork = new ArrayList<NeutronNetwork>();
+ List<NeutronNetwork> listNeutronNetwork = new ArrayList<NeutronNetwork>();
listNeutronNetwork.add(neutronNetwork);
when(neutronNetworkCache.getAllNetworks()).thenReturn(listNeutronNetwork);
@Test
public void testGetNetworkId() {
NeutronNetwork neutronNetwork = mock(NeutronNetwork.class);
- ArrayList<NeutronNetwork> listNeutronNetwork = new ArrayList<NeutronNetwork>();
+ List<NeutronNetwork> listNeutronNetwork = new ArrayList<NeutronNetwork>();
listNeutronNetwork.add(neutronNetwork);
when(neutronNetwork.getProviderSegmentationID()).thenReturn("segId");
/*
-* Copyright (C) 2014 Red Hat, Inc.
-*
-* This program and the accompanying materials are made available under the
-* terms of the Eclipse Public License v1.0 which accompanies this distribution,
-* and is available at http://www.eclipse.org/legal/epl-v10.html
-*
-* Authors : Sam Hague
-*/
+ * 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.ovsdb.ovssfc;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
/*
-* Copyright (C) 2014 Red Hat, Inc.
-*
-* This program and the accompanying materials are made available under the
-* terms of the Eclipse Public License v1.0 which accompanies this distribution,
-* and is available at http://www.eclipse.org/legal/epl-v10.html
-*
-* Authors : Sam Hague
-*/
+ * 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.ovsdb.ovssfc;
//import com.google.common.base.Optional;
/*
-* Copyright (C) 2014 Red Hat, Inc.
-*
-* This program and the accompanying materials are made available under the
-* terms of the Eclipse Public License v1.0 which accompanies this distribution,
-* and is available at http://www.eclipse.org/legal/epl-v10.html
-*
-* Authors : Sam Hague
-*/
+ * 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.ovsdb.ovssfc;
import java.util.concurrent.BlockingQueue;
/*
+ * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
*
- * Copyright (C) 2014 Red Hat, Inc.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- *
- * Authors : Sam Hague
- * /
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.ovsdb.ovssfc;
/*
-* Copyright (C) 2014 Red Hat, Inc.
-*
-* This program and the accompanying materials are made available under the
-* terms of the Eclipse Public License v1.0 which accompanies this distribution,
-* and is available at http://www.eclipse.org/legal/epl-v10.html
-*
-* Authors : Sam Hague
-*/
+ * 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.ovsdb.ovssfc;
import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sf.rev140701.ServiceFunctions;
/*
-* Copyright (C) 2014 Red Hat, Inc.
-*
-* This program and the accompanying materials are made available under the
-* terms of the Eclipse Public License v1.0 which accompanies this distribution,
-* and is available at http://www.eclipse.org/legal/epl-v10.html
-*
-* Authors : Sam Hague
-*/
+ * 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.ovsdb.ovssfc;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
/*
-* Copyright (C) 2014 Red Hat, Inc.
-*
-* This program and the accompanying materials are made available under the
-* terms of the Eclipse Public License v1.0 which accompanies this distribution,
-* and is available at http://www.eclipse.org/legal/epl-v10.html
-*
-* Authors : Sam Hague
-*/
+ * 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.ovsdb.ovssfc;
import com.google.common.base.Preconditions;
/*
-* Copyright (C) 2014 Red Hat, Inc.
-*
-* This program and the accompanying materials are made available under the
-* terms of the Eclipse Public License v1.0 which accompanies this distribution,
-* and is available at http://www.eclipse.org/legal/epl-v10.html
-*
-* Authors : Sam Hague
-*/
+ * 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.ovsdb.ovssfc;
import com.google.common.base.Optional;
/*
-* Copyright (C) 2014 Red Hat, Inc.
-*
-* This program and the accompanying materials are made available under the
-* terms of the Eclipse Public License v1.0 which accompanies this distribution,
-* and is available at http://www.eclipse.org/legal/epl-v10.html
-*
-* Authors : Sam Hague
-*/
+ * 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.ovsdb.ovssfc;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
/*
-* Copyright (C) 2014 Red Hat, Inc.
-*
-* This program and the accompanying materials are made available under the
-* terms of the Eclipse Public License v1.0 which accompanies this distribution,
-* and is available at http://www.eclipse.org/legal/epl-v10.html
-*
-* Authors : Sam Hague
-*/
+ * 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.ovsdb.ovssfc;
import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfp.rev140701.ServiceFunctionPaths;
/*
-* Copyright (C) 2014 Red Hat, Inc.
-*
-* This program and the accompanying materials are made available under the
-* terms of the Eclipse Public License v1.0 which accompanies this distribution,
-* and is available at http://www.eclipse.org/legal/epl-v10.html
-*
-* Authors : Sam Hague
-*/
+ * 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.ovsdb.ovssfc;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
/*
-* Copyright (C) 2014 Red Hat, Inc.
-*
-* This program and the accompanying materials are made available under the
-* terms of the Eclipse Public License v1.0 which accompanies this distribution,
-* and is available at http://www.eclipse.org/legal/epl-v10.html
-*
-* Authors : Sam Hague
-*/
+ * 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.ovsdb.ovssfc;
import com.google.common.base.Optional;
/*
-* Copyright (C) 2014 Red Hat, Inc.
-*
-* This program and the accompanying materials are made available under the
-* terms of the Eclipse Public License v1.0 which accompanies this distribution,
-* and is available at http://www.eclipse.org/legal/epl-v10.html
-*
-* Authors : Sam Hague
-*/
+ * 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.ovsdb.ovssfc;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
/*
-* Copyright (C) 2014 Red Hat, Inc.
-*
-* This program and the accompanying materials are made available under the
-* terms of the Eclipse Public License v1.0 which accompanies this distribution,
-* and is available at http://www.eclipse.org/legal/epl-v10.html
-*
-* Authors : Sam Hague
-*/
+ * 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.ovsdb.ovssfc;
import org.opendaylight.controller.sal.core.Node;
</scm>
<dependencies>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
- </dependency>
- <dependency>
- <groupId>commons-collections</groupId>
- <artifactId>commons-collections</artifactId>
- </dependency>
- <dependency>
- <groupId>equinoxSDK381</groupId>
- <artifactId>org.eclipse.osgi</artifactId>
- </dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<groupId>org.opendaylight.ovsdb</groupId>
<artifactId>plugin</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.ovsdb</groupId>
+ <artifactId>library</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller.model</groupId>
+ <artifactId>model-inventory</artifactId>
+ </dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-simple</artifactId>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
</dependency>
<dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-module-junit4</artifactId>
- <version>1.5.4</version>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-simple</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
/*
- * Copyright (C) 2015 Red Hat, Inc.
+ * 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
- *
- * Authors : Sam Hague
*/
+
package org.opendaylight.ovsdb.compatibility.plugin.api;
import java.util.ArrayList;
import org.slf4j.LoggerFactory;
public class NodeUtils {
- protected static final Logger LOG = LoggerFactory.getLogger(NodeUtils.class);
+ private static final Logger LOG = LoggerFactory.getLogger(NodeUtils.class);
public static String getId (String identifier) {
String id = identifier;
/*
- * Copyright (C) 2013 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal, Brent Salisbury
*/
+
package org.opendaylight.ovsdb.compatibility.plugin.api;
import java.util.List;
* @return UUID of the inserted Row
*/
@Deprecated
- public StatusWithUuid insertRow(Node node, String tableName, String parentUuid, Row<GenericTableSchema> row);
+ StatusWithUuid insertRow(Node node, String tableName, String parentUuid, Row<GenericTableSchema> row);
/**
* insert a Row in a Table of a specified Database Schema. This is a convenience method on top of
* @throws OvsdbPluginException Any failure during the insert transaction will result in a specific exception.
* @return UUID of the inserted Row
*/
- public UUID insertRow(Node node, String databaseName, String tableName, UUID parentRowUuid,
- Row<GenericTableSchema> row) throws OvsdbPluginException;
+ UUID insertRow(Node node, String databaseName, String tableName, UUID parentRowUuid,
+ Row<GenericTableSchema> row) throws OvsdbPluginException;
/**
* insert a Row in a Table of a specified Database Schema.
* @throws OvsdbPluginException Any failure during the insert transaction will result in a specific exception.
* @return UUID of the inserted Row
*/
- public UUID insertRow(Node node, String databaseName, String tableName, String parentTable, UUID parentRowUuid,
- String parentColumn, Row<GenericTableSchema> row) throws OvsdbPluginException;
+ UUID insertRow(Node node, String databaseName, String tableName, String parentTable, UUID parentRowUuid,
+ String parentColumn, Row<GenericTableSchema> row) throws OvsdbPluginException;
/**
* inserts a Tree of Rows in multiple Tables that has parent-child relationships referenced through the OVSDB schema's refTable construct.
* @throws OvsdbPluginException Any failure during the insert transaction will result in a specific exception.
* @return Returns the row tree with the UUID of every inserted Row populated in the _uuid column of every row in the tree
*/
- public Row<GenericTableSchema> insertTree(Node node, String databaseName, String tableName, UUID parentRowUuid,
- Row<GenericTableSchema> row) throws OvsdbPluginException;
+ Row<GenericTableSchema> insertTree(Node node, String databaseName, String tableName, UUID parentRowUuid,
+ Row<GenericTableSchema> row) throws OvsdbPluginException;
/**
* inserts a Tree of Rows in multiple Tables that has parent-child relationships referenced through the OVSDB schema's refTable construct
* @throws OvsdbPluginException Any failure during the insert transaction will result in a specific exception.
* @return Returns the row tree with the UUID of every inserted Row populated in the _uuid column of every row in the tree
*/
- public Row<GenericTableSchema> insertTree(Node node, String databaseName, String tableName, String parentTable, UUID parentRowUuid,
- String parentColumn, Row<GenericTableSchema> row) throws OvsdbPluginException;
+ Row<GenericTableSchema> insertTree(Node node, String databaseName, String tableName, String parentTable, UUID parentRowUuid,
+ String parentColumn, Row<GenericTableSchema> row) throws OvsdbPluginException;
/**
* @deprecated This version of updateRow is a short-term replacement for the older and now deprecated method of the same name.
* @param row Row of table Content to be Updated. Include just those columns that needs to be updated.
*/
@Deprecated
- public Status updateRow (Node node, String tableName, String parentUuid, String rowUuid, Row row);
+ Status updateRow(Node node, String tableName, String parentUuid, String rowUuid, Row row);
/**
* update or mutate a Row in a Table of a specified Database Schema.
* @throws OvsdbPluginException Any failure during the update operation will result in a specific exception.
* @return Returns the entire Row after the update operation.
*/
- public Row<GenericTableSchema> updateRow(Node node, String databaseName, String tableName, UUID rowUuid,
- Row<GenericTableSchema> row, boolean overwrite) throws OvsdbPluginException;
+ Row<GenericTableSchema> updateRow(Node node, String databaseName, String tableName, UUID rowUuid,
+ Row<GenericTableSchema> row, boolean overwrite) throws OvsdbPluginException;
/**
* @deprecated This version of deleteRow is a short-term replacement for the older and now deprecated method of the same name.
* @param rowUuid UUID of the row that is being deleted
*/
@Deprecated
- public Status deleteRow (Node node, String tableName, String rowUuid);
+ Status deleteRow(Node node, String tableName, String rowUuid);
/**
* update or mutate a Row in a Table of a specified Database Schema.
* @throws OvsdbPluginException Any failure during the delete operation will result in a specific exception.
*/
- public void deleteRow (Node node, String databaseName, String tableName, UUID rowUuid) throws OvsdbPluginException;
+ void deleteRow(Node node, String databaseName, String tableName, UUID rowUuid) throws OvsdbPluginException;
/**
* update or mutate a Row in a Table of a specified Database Schema.
* @throws OvsdbPluginException Any failure during the delete operation will result in a specific exception.
*/
- public void deleteRow (Node node, String databaseName, String tableName, String parentTable,
- UUID parentRowUuid, String parentColumn, UUID rowUuid) throws OvsdbPluginException;
+ void deleteRow(Node node, String databaseName, String tableName, String parentTable,
+ UUID parentRowUuid, String parentColumn, UUID rowUuid) throws OvsdbPluginException;
/**
* @deprecated This version of getRow is a short-term replacement for the older and now deprecated method of the same name.
* @return a row with a list of Column data that corresponds to an unique Row-identifier called uuid in a given table.
*/
@Deprecated
- public Row getRow(Node node, String tableName, String uuid);
+ Row getRow(Node node, String tableName, String uuid);
/**
* Returns a Row from a table for the specified uuid.
* @throws OvsdbPluginException Any failure during the get operation will result in a specific exception.
* @return a row with a list of Column data that corresponds to an unique Row-identifier called uuid in a given table.
*/
- public Row<GenericTableSchema> getRow(Node node, String databaseName, String tableName, UUID uuid) throws OvsdbPluginException;
+ Row<GenericTableSchema> getRow(Node node, String databaseName, String tableName, UUID uuid) throws OvsdbPluginException;
/**
* @deprecated This version of getRows is a short-term replacement for the older and now deprecated method of the same name.
* @return List of rows that makes the entire Table.
*/
@Deprecated
- public ConcurrentMap<String, Row> getRows(Node node, String tableName);
+ ConcurrentMap<String, Row> getRows(Node node, String tableName);
/**
* Returns all rows of a table.
* @throws OvsdbPluginException Any failure during the get operation will result in a specific exception.
* @return Map of rows to its UUID that makes the entire Table.
*/
- public ConcurrentMap<UUID, Row<GenericTableSchema>> getRows(Node node, String databaseName, String tableName) throws OvsdbPluginException;
+ ConcurrentMap<UUID, Row<GenericTableSchema>> getRows(Node node, String databaseName, String tableName) throws OvsdbPluginException;
/**
* Returns all rows of a table filtered by query string.
* @throws OvsdbPluginException Any failure during the get operation will result in a specific exception.
* @return Map of rows to its UUID that makes the entire Table.
*/
- public ConcurrentMap<UUID, Row<GenericTableSchema>> getRows(Node node, String databaseName, String tableName, String fiqlQuery) throws OvsdbPluginException;
+ ConcurrentMap<UUID, Row<GenericTableSchema>> getRows(Node node, String databaseName, String tableName, String fiqlQuery) throws OvsdbPluginException;
/**
* @deprecated Returns all the Tables in a given Ndoe.
* @return List of Table Names that make up Open_vSwitch schema.
*/
@Deprecated
- public List<String> getTables(Node node);
+ List<String> getTables(Node node);
/**
* Returns all the Tables in a given Node.
* @throws OvsdbPluginException Any failure during the get operation will result in a specific exception.
* @return List of Table Names that make up the schema represented by the databaseName
*/
- public List<String> getTables(Node node, String databaseName) throws OvsdbPluginException;
+ List<String> getTables(Node node, String databaseName) throws OvsdbPluginException;
/**
* setOFController is a convenience method used by existing applications to setup Openflow Controller on
* @throws InterruptedException
* @throws ExecutionException
*/
- public Boolean setOFController(Node node, String bridgeUUID) throws InterruptedException, ExecutionException;
+ Boolean setOFController(Node node, String bridgeUUID) throws InterruptedException, ExecutionException;
- public <T extends TypedBaseTable<?>> String getTableName(Node node, Class<T> typedClass);
- public <T extends TypedBaseTable<?>> T getTypedRow(Node node, Class<T> typedClass, Row row);
- public <T extends TypedBaseTable<?>> T createTypedRow(Node node, Class<T> typedClass);
+ <T extends TypedBaseTable<?>> String getTableName(Node node, Class<T> typedClass);
+ <T extends TypedBaseTable<?>> T getTypedRow(Node node, Class<T> typedClass, Row row);
+ <T extends TypedBaseTable<?>> T createTypedRow(Node node, Class<T> typedClass);
}
/*
- * Copyright (C) 2013 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal, Brent Salisbury
*/
+
package org.opendaylight.ovsdb.compatibility.plugin.api;
import java.util.List;
import org.opendaylight.ovsdb.plugin.api.ConnectionConstants;
public interface OvsdbConnectionService {
- public Connection getConnection(Node node);
- public List<Node> getNodes();
- public Node getNode(String identifier);
- public Node connect(String identifier, Map<ConnectionConstants, String> params);
+ Connection getConnection(Node node);
+ List<Node> getNodes();
+ Node getNode(String identifier);
+ Node connect(String identifier, Map<ConnectionConstants, String> params);
}
/*
- * Copyright (C) 2013 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal, Brent Salisbury
*/
+
package org.opendaylight.ovsdb.compatibility.plugin.api;
import org.opendaylight.controller.sal.core.Node;
import java.net.InetAddress;
public interface OvsdbInventoryListener {
- public void nodeAdded(Node node, InetAddress address, int port );
- public void nodeRemoved(Node node);
- public void rowAdded(Node node, String tableName, String uuid, Row row);
- public void rowUpdated(Node node, String tableName, String uuid, Row old, Row row);
- public void rowRemoved(Node node, String tableName, String uuid, Row row, Object context);
+ void nodeAdded(Node node, InetAddress address, int port);
+ void nodeRemoved(Node node);
+ void rowAdded(Node node, String tableName, String uuid, Row row);
+ void rowUpdated(Node node, String tableName, String uuid, Row old, Row row);
+ void rowRemoved(Node node, String tableName, String uuid, Row row, Object context);
}
/*
- * Copyright (C) 2013 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal, Brent Salisbury
*/
+
package org.opendaylight.ovsdb.compatibility.plugin.api;
import java.net.InetAddress;
import org.opendaylight.ovsdb.lib.notation.Row;
public interface OvsdbInventoryService{
- public ConcurrentMap<String, ConcurrentMap<String, Row>> getCache(Node n, String databaseName);
- public ConcurrentMap<String, Row> getTableCache(Node n, String databaseName, String tableName);
- public Row getRow (Node n, String databaseName, String tableName, String uuid);
- public void updateRow(Node n, String databaseName, String tableName, String uuid, Row row);
- public void removeRow(Node n, String databaseName, String tableName, String uuid);
- public void processTableUpdates(Node n, String databaseName,TableUpdates tableUpdates);
- public void printCache(Node n);
- public void addNode(Node n, Set<Property> props);
- public void notifyNodeAdded(Node n, InetAddress address, int port);
- public void removeNode(Node n);
- public void addNodeProperty(Node node, UpdateType type, Set<Property> props);
+ ConcurrentMap<String, ConcurrentMap<String, Row>> getCache(Node n, String databaseName);
+ ConcurrentMap<String, Row> getTableCache(Node n, String databaseName, String tableName);
+ Row getRow(Node n, String databaseName, String tableName, String uuid);
+ void updateRow(Node n, String databaseName, String tableName, String uuid, Row row);
+ void removeRow(Node n, String databaseName, String tableName, String uuid);
+ void processTableUpdates(Node n, String databaseName, TableUpdates tableUpdates);
+ void printCache(Node n);
+ void addNode(Node n, Set<Property> props);
+ void notifyNodeAdded(Node n, InetAddress address, int port);
+ void removeNode(Node n);
+ void addNodeProperty(Node node, UpdateType type, Set<Property> props);
}
\ No newline at end of file
/*
- * [[ Authors will Fill in the Copyright header ]]
+ * 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
- *
- * Authors : Hugo Trippaers
*/
+
package org.opendaylight.ovsdb.compatibility.plugin.api;
import org.opendaylight.controller.sal.utils.Status;
+/*
+ * 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.ovsdb.compatibility.plugin.error;
public class OvsdbPluginException extends RuntimeException {
}
public void unsetOvsdbConfigurationService(org.opendaylight.ovsdb.plugin.api.OvsdbConfigurationService pluginOvsdbConfigurationService){
- if(this.pluginOvsdbConfigurationService != null)
- this.pluginOvsdbConfigurationService = null;
+ this.pluginOvsdbConfigurationService = null;
}
import org.opendaylight.ovsdb.compatibility.plugin.api.OvsdbConnectionService;
import org.opendaylight.ovsdb.plugin.api.Connection;
import org.opendaylight.ovsdb.plugin.api.ConnectionConstants;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
/**
* This is a proxy class for ovsdb plugin's OvsdbConnectionService class
*
*/
public class ConnectionServiceImpl implements OvsdbConnectionService{
- protected static final Logger logger = LoggerFactory.getLogger(ConnectionServiceImpl.class);
private volatile org.opendaylight.ovsdb.plugin.api.OvsdbConnectionService pluginOvsdbConnectionService;
}
public void unsetOvsdbConnectionService(org.opendaylight.ovsdb.plugin.api.OvsdbConnectionService pluginOvsdbConnectionService){
- if(this.pluginOvsdbConnectionService != null)
- this.pluginOvsdbConnectionService = null;
+ this.pluginOvsdbConnectionService = null;
}
+
@Override
public Connection getConnection(Node node) {
return pluginOvsdbConnectionService.getConnection(NodeUtils.getMdsalNode(node));
}
public void removeOvsdbInventoryListener(OvsdbInventoryListener pluginOvsdbInventoryListener){
- if(this.ovsdbInventoryListeners.contains(ovsdbInventoryListeners))
+ if(this.ovsdbInventoryListeners.contains(ovsdbInventoryListeners)) {
this.ovsdbInventoryListeners.remove(ovsdbInventoryListeners);
+ }
}
@Override
@Override
public void nodeAdded(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node node,
InetAddress address, int port) {
- for(OvsdbInventoryListener listener : this.ovsdbInventoryListeners)
+ for(OvsdbInventoryListener listener : this.ovsdbInventoryListeners) {
listener.nodeAdded(NodeUtils.getSalNode(node), address, port);
+ }
}
@Override
public void nodeRemoved(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node node) {
- for(OvsdbInventoryListener listener : this.ovsdbInventoryListeners)
+ for(OvsdbInventoryListener listener : this.ovsdbInventoryListeners) {
listener.nodeRemoved(NodeUtils.getSalNode(node));
+ }
}
@Override
public void rowAdded(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node node,
String tableName, String uuid, Row row) {
- for(OvsdbInventoryListener listener : this.ovsdbInventoryListeners)
+ for(OvsdbInventoryListener listener : this.ovsdbInventoryListeners) {
listener.rowAdded(NodeUtils.getSalNode(node), tableName, uuid, row);
+ }
}
public void rowUpdated(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node node,
String tableName, String uuid, Row old,
Row row) {
- for(OvsdbInventoryListener listener : this.ovsdbInventoryListeners)
+ for(OvsdbInventoryListener listener : this.ovsdbInventoryListeners) {
listener.rowUpdated(NodeUtils.getSalNode(node), tableName, uuid, old, row);
+ }
}
public void rowRemoved(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node node,
String tableName, String uuid, Row row,
Object context) {
- for(OvsdbInventoryListener listener : this.ovsdbInventoryListeners)
+ for(OvsdbInventoryListener listener : this.ovsdbInventoryListeners) {
listener.rowRemoved(NodeUtils.getSalNode(node), tableName, uuid, row, context);
+ }
}
}
import org.opendaylight.ovsdb.compatibility.plugin.impl.ConfigurationServiceImpl;
import org.opendaylight.ovsdb.compatibility.plugin.impl.ConnectionServiceImpl;
import org.opendaylight.ovsdb.compatibility.plugin.impl.InventoryServiceImpl;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
/**
* Activator for ovsdb plugin compatibility layer
*
*/
public class Activator extends ComponentActivatorAbstractBase {
- protected static final Logger logger = LoggerFactory
- .getLogger(Activator.class);
/**
* Function called when the activator starts just after some initializations
}
@Override
public Object[] getGlobalImplementations() {
- Object[] res = { ConnectionServiceImpl.class, ConfigurationServiceImpl.class, InventoryServiceImpl.class };
- return res;
+ return new Object[]{ ConnectionServiceImpl.class, ConfigurationServiceImpl.class, InventoryServiceImpl.class };
}
@Override
public void configureGlobalInstance(Component c, Object imp){
if (imp.equals(ConfigurationServiceImpl.class)) {
// export the service to be used by SAL
- Dictionary<String, Object> props = new Hashtable<String, Object>();
+ Dictionary<String, Object> props = new Hashtable<>();
c.setInterface(new String[] { OvsdbConfigurationService.class.getName()}, props);
c.add(createServiceDependency()
.setService(org.opendaylight.ovsdb.plugin.api.OvsdbConfigurationService.class)
if (imp.equals(ConnectionServiceImpl.class)) {
// export the service to be used by SAL
- Dictionary<String, Object> props = new Hashtable<String, Object>();
+ Dictionary<String, Object> props = new Hashtable<>();
c.setInterface(
new String[] {OvsdbConnectionService.class.getName()}, props);
c.add(createServiceDependency()
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.6</version>
<executions>
<execution>
<id>unpack-loader-resources</id>
/*
- * Copyright (C) 2013 Red Hat, Inc.
+ * 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
- *
- * Authors : Dave Tucker
*/
package org.opendaylight.ovsdb.plugin.md;
+/*
+ * 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.ovsdb.plugin.md;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+/*
+ * 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.ovsdb.plugin.md;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+/*
+ * 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.ovsdb.plugin.md;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+/*
+ * 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.ovsdb.plugin.md;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-core</artifactId>
- <scope>test</scope>
+ <groupId>org.opendaylight.ovsdb</groupId>
+ <artifactId>library</artifactId>
</dependency>
<dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-api-mockito</artifactId>
- <scope>test</scope>
+ <groupId>org.opendaylight.ovsdb</groupId>
+ <artifactId>plugin</artifactId>
</dependency>
<dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-core</artifactId>
- <scope>test</scope>
+ <groupId>org.opendaylight.controller.model</groupId>
+ <artifactId>model-inventory</artifactId>
</dependency>
<dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-module-junit4</artifactId>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-simple</artifactId>
<scope>test</scope>
</dependency>
- <dependency>
- <groupId>org.opendaylight.ovsdb</groupId>
- <artifactId>library</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.ovsdb</groupId>
- <artifactId>plugin</artifactId>
- </dependency>
</dependencies>
<build>
-/**
- * Copyright (C) 2013 Red Hat, Inc.
+/*
+ * 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
- *
- * Authors : Madhu Venugopal
*/
+
package org.opendaylight.ovsdb.plugin.shell;
import org.apache.karaf.shell.commands.Argument;
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
+ <scope>test</scope>
</dependency>
</dependencies>
/*
- * Copyright (C) 2013 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal, Brent Salisbury
*/
+
package org.opendaylight.ovsdb.plugin.api;
import org.opendaylight.ovsdb.lib.OvsdbClient;
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.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
public class Connection {
private Node node;
private String identifier;
private Long idCounter;
- private static final Logger logger = LoggerFactory.getLogger(Connection.class);
-
public Connection(String identifier, OvsdbClient client) {
super();
@Override
public boolean equals(Object obj) {
- if (this == obj) return true;
- if (obj == null) return false;
- if (getClass() != obj.getClass()) return false;
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
Connection other = (Connection) obj;
if (identifier == null) {
- if (other.identifier != null) return false;
- } else if (!identifier.equals(other.identifier)) return false;
+ if (other.identifier != null) {
+ return false;
+ }
+ } else if (!identifier.equals(other.identifier)) {
+ return false;
+ }
return true;
}
}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * 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,
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal
*/
package org.opendaylight.ovsdb.plugin.api;
}
public static boolean shouldConfigureController (String databaseName, String tableName) {
- if (autoConfigureController && databaseName.equals(DATABASE_NAME) && tableName.equals("Bridge")) return true;
- return false;
+ return autoConfigureController && databaseName.equals(DATABASE_NAME) && tableName.equals("Bridge");
}
public enum PortType {
/*
- * Copyright (C) 2013 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal, Brent Salisbury
*/
+
package org.opendaylight.ovsdb.plugin.api;
import java.util.List;
* @return UUID of the inserted Row
*/
@Deprecated
- public StatusWithUuid insertRow(Node node, String tableName, String parentUuid, Row<GenericTableSchema> row);
+ StatusWithUuid insertRow(Node node, String tableName, String parentUuid, Row<GenericTableSchema> row);
/**
* insert a Row in a Table of a specified Database Schema. This is a convenience method on top of
* @throws OvsdbPluginException Any failure during the insert transaction will result in a specific exception.
* @return UUID of the inserted Row
*/
- public UUID insertRow(Node node, String databaseName, String tableName, UUID parentRowUuid,
- Row<GenericTableSchema> row) throws OvsdbPluginException;
+ UUID insertRow(Node node, String databaseName, String tableName, UUID parentRowUuid,
+ Row<GenericTableSchema> row) throws OvsdbPluginException;
/**
* insert a Row in a Table of a specified Database Schema.
* @throws OvsdbPluginException Any failure during the insert transaction will result in a specific exception.
* @return UUID of the inserted Row
*/
- public UUID insertRow(Node node, String databaseName, String tableName, String parentTable, UUID parentRowUuid,
- String parentColumn, Row<GenericTableSchema> row) throws OvsdbPluginException;
+ UUID insertRow(Node node, String databaseName, String tableName, String parentTable, UUID parentRowUuid,
+ String parentColumn, Row<GenericTableSchema> row) throws OvsdbPluginException;
/**
* inserts a Tree of Rows in multiple Tables that has parent-child relationships referenced through the OVSDB schema's refTable construct.
* @throws OvsdbPluginException Any failure during the insert transaction will result in a specific exception.
* @return Returns the row tree with the UUID of every inserted Row populated in the _uuid column of every row in the tree
*/
- public Row<GenericTableSchema> insertTree(Node node, String databaseName, String tableName, UUID parentRowUuid,
- Row<GenericTableSchema> row) throws OvsdbPluginException;
+ Row<GenericTableSchema> insertTree(Node node, String databaseName, String tableName, UUID parentRowUuid,
+ Row<GenericTableSchema> row) throws OvsdbPluginException;
/**
* inserts a Tree of Rows in multiple Tables that has parent-child relationships referenced through the OVSDB schema's refTable construct
* @throws OvsdbPluginException Any failure during the insert transaction will result in a specific exception.
* @return Returns the row tree with the UUID of every inserted Row populated in the _uuid column of every row in the tree
*/
- public Row<GenericTableSchema> insertTree(Node node, String databaseName, String tableName, String parentTable, UUID parentRowUuid,
- String parentColumn, Row<GenericTableSchema> row) throws OvsdbPluginException;
+ Row<GenericTableSchema> insertTree(Node node, String databaseName, String tableName, String parentTable, UUID parentRowUuid,
+ String parentColumn, Row<GenericTableSchema> row) throws OvsdbPluginException;
/**
* @deprecated This version of updateRow is a short-term replacement for the older and now deprecated method of the same name.
* @param row Row of table Content to be Updated. Include just those columns that needs to be updated.
*/
@Deprecated
- public Status updateRow (Node node, String tableName, String parentUuid, String rowUuid, Row row);
+ Status updateRow(Node node, String tableName, String parentUuid, String rowUuid, Row row);
/**
* update or mutate a Row in a Table of a specified Database Schema.
* @throws OvsdbPluginException Any failure during the update operation will result in a specific exception.
* @return Returns the entire Row after the update operation.
*/
- public Row<GenericTableSchema> updateRow(Node node, String databaseName, String tableName, UUID rowUuid,
- Row<GenericTableSchema> row, boolean overwrite) throws OvsdbPluginException;
+ Row<GenericTableSchema> updateRow(Node node, String databaseName, String tableName, UUID rowUuid,
+ Row<GenericTableSchema> row, boolean overwrite) throws OvsdbPluginException;
/**
* @deprecated This version of deleteRow is a short-term replacement for the older and now deprecated method of the same name.
* @param rowUuid UUID of the row that is being deleted
*/
@Deprecated
- public Status deleteRow (Node node, String tableName, String rowUuid);
+ Status deleteRow(Node node, String tableName, String rowUuid);
/**
* update or mutate a Row in a Table of a specified Database Schema.
* @throws OvsdbPluginException Any failure during the delete operation will result in a specific exception.
*/
- public void deleteRow (Node node, String databaseName, String tableName, UUID rowUuid) throws OvsdbPluginException;
+ void deleteRow(Node node, String databaseName, String tableName, UUID rowUuid) throws OvsdbPluginException;
/**
* update or mutate a Row in a Table of a specified Database Schema.
* @throws OvsdbPluginException Any failure during the delete operation will result in a specific exception.
*/
- public void deleteRow (Node node, String databaseName, String tableName, String parentTable,
- UUID parentRowUuid, String parentColumn, UUID rowUuid) throws OvsdbPluginException;
+ void deleteRow(Node node, String databaseName, String tableName, String parentTable,
+ UUID parentRowUuid, String parentColumn, UUID rowUuid) throws OvsdbPluginException;
/**
* @deprecated This version of getRow is a short-term replacement for the older and now deprecated method of the same name.
* @return a row with a list of Column data that corresponds to an unique Row-identifier called uuid in a given table.
*/
@Deprecated
- public Row getRow(Node node, String tableName, String uuid);
+ Row getRow(Node node, String tableName, String uuid);
/**
* Returns a Row from a table for the specified uuid.
* @throws OvsdbPluginException Any failure during the get operation will result in a specific exception.
* @return a row with a list of Column data that corresponds to an unique Row-identifier called uuid in a given table.
*/
- public Row<GenericTableSchema> getRow(Node node, String databaseName, String tableName, UUID uuid) throws OvsdbPluginException;
+ Row<GenericTableSchema> getRow(Node node, String databaseName, String tableName, UUID uuid) throws OvsdbPluginException;
/**
* @deprecated This version of getRows is a short-term replacement for the older and now deprecated method of the same name.
* @return List of rows that makes the entire Table.
*/
@Deprecated
- public ConcurrentMap<String, Row> getRows(Node node, String tableName);
+ ConcurrentMap<String, Row> getRows(Node node, String tableName);
/**
* Returns all rows of a table.
* @throws OvsdbPluginException Any failure during the get operation will result in a specific exception.
* @return Map of rows to its UUID that makes the entire Table.
*/
- public ConcurrentMap<UUID, Row<GenericTableSchema>> getRows(Node node, String databaseName, String tableName) throws OvsdbPluginException;
+ ConcurrentMap<UUID, Row<GenericTableSchema>> getRows(Node node, String databaseName, String tableName) throws OvsdbPluginException;
/**
* Returns all rows of a table filtered by query string.
* @throws OvsdbPluginException Any failure during the get operation will result in a specific exception.
* @return Map of rows to its UUID that makes the entire Table.
*/
- public ConcurrentMap<UUID, Row<GenericTableSchema>> getRows(Node node, String databaseName, String tableName, String fiqlQuery) throws OvsdbPluginException;
+ ConcurrentMap<UUID, Row<GenericTableSchema>> getRows(Node node, String databaseName, String tableName, String fiqlQuery) throws OvsdbPluginException;
/**
* @deprecated Returns all the Tables in a given Ndoe.
* @return List of Table Names that make up Open_vSwitch schema.
*/
@Deprecated
- public List<String> getTables(Node node);
+ List<String> getTables(Node node);
/**
* Returns all the Tables in a given Node.
* @throws OvsdbPluginException Any failure during the get operation will result in a specific exception.
* @return List of Table Names that make up the schema represented by the databaseName
*/
- public List<String> getTables(Node node, String databaseName) throws OvsdbPluginException;
+ List<String> getTables(Node node, String databaseName) throws OvsdbPluginException;
/**
* setOFController is a convenience method used by existing applications to setup Openflow Controller on
* @throws InterruptedException
* @throws ExecutionException
*/
- public Boolean setOFController(Node node, String bridgeUUID) throws InterruptedException, ExecutionException;
+ Boolean setOFController(Node node, String bridgeUUID) throws InterruptedException, ExecutionException;
- public <T extends TypedBaseTable<?>> String getTableName(Node node, Class<T> typedClass);
- public <T extends TypedBaseTable<?>> T getTypedRow(Node node, Class<T> typedClass, Row row);
- public <T extends TypedBaseTable<?>> T createTypedRow(Node node, Class<T> typedClass);
+ <T extends TypedBaseTable<?>> String getTableName(Node node, Class<T> typedClass);
+ <T extends TypedBaseTable<?>> T getTypedRow(Node node, Class<T> typedClass, Row row);
+ <T extends TypedBaseTable<?>> T createTypedRow(Node node, Class<T> typedClass);
}
/*
- * Copyright (C) 2013 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal, Brent Salisbury
*/
+
package org.opendaylight.ovsdb.plugin.api;
import java.util.List;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
public interface OvsdbConnectionService {
- public Connection getConnection(Node node);
- public List<Node> getNodes();
- public Node getNode(String identifier);
- public Node connect(String identifier, Map<ConnectionConstants, String> params);
+ Connection getConnection(Node node);
+ List<Node> getNodes();
+ Node getNode(String identifier);
+ Node connect(String identifier, Map<ConnectionConstants, String> params);
}
/*
- * Copyright (C) 2013 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal, Brent Salisbury
*/
+
package org.opendaylight.ovsdb.plugin.api;
import org.opendaylight.ovsdb.lib.notation.Row;
import java.net.InetAddress;
public interface OvsdbInventoryListener {
- public void nodeAdded(Node node, InetAddress address, int port );
- public void nodeRemoved(Node node);
- public void rowAdded(Node node, String tableName, String uuid, Row row);
- public void rowUpdated(Node node, String tableName, String uuid, Row old, Row row);
- public void rowRemoved(Node node, String tableName, String uuid, Row row, Object context);
+ void nodeAdded(Node node, InetAddress address, int port);
+ void nodeRemoved(Node node);
+ void rowAdded(Node node, String tableName, String uuid, Row row);
+ void rowUpdated(Node node, String tableName, String uuid, Row old, Row row);
+ void rowRemoved(Node node, String tableName, String uuid, Row row, Object context);
}
/*
- * Copyright (C) 2013 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal, Brent Salisbury
*/
+
package org.opendaylight.ovsdb.plugin.api;
import java.net.InetAddress;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
public interface OvsdbInventoryService {
- public ConcurrentMap<String, ConcurrentMap<String, Row>> getCache(Node n, String databaseName);
- public ConcurrentMap<String, Row> getTableCache(Node n, String databaseName, String tableName);
- public Row getRow (Node n, String databaseName, String tableName, String uuid);
- public void updateRow(Node n, String databaseName, String tableName, String uuid, Row row);
- public void removeRow(Node n, String databaseName, String tableName, String uuid);
- public void processTableUpdates(Node n, String databaseName,TableUpdates tableUpdates);
- public void printCache(Node n);
- public void notifyNodeAdded(Node n, InetAddress address, int port);
- public void removeNode(Node n);
+ ConcurrentMap<String, ConcurrentMap<String, Row>> getCache(Node n, String databaseName);
+ ConcurrentMap<String, Row> getTableCache(Node n, String databaseName, String tableName);
+ Row getRow(Node n, String databaseName, String tableName, String uuid);
+ void updateRow(Node n, String databaseName, String tableName, String uuid, Row row);
+ void removeRow(Node n, String databaseName, String tableName, String uuid);
+ void processTableUpdates(Node n, String databaseName, TableUpdates tableUpdates);
+ void printCache(Node n);
+ void notifyNodeAdded(Node n, InetAddress address, int port);
+ void removeNode(Node n);
}
\ No newline at end of file
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * 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,
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * 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,
/*
- * [[ Authors will Fill in the Copyright header ]]
+ * 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
- *
- * Authors : Hugo Trippaers
*/
+
package org.opendaylight.ovsdb.plugin.api;
import org.opendaylight.ovsdb.plugin.api.Status;
+/*
+ * 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.ovsdb.plugin.error;
public class OvsdbPluginException extends RuntimeException {
/*
- * Copyright (C) 2013 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal, Brent Salisbury, Keith Burns
*/
+
package org.opendaylight.ovsdb.plugin.impl;
import static org.opendaylight.ovsdb.lib.operations.Operations.op;
public class ConfigurationServiceImpl implements OvsdbConfigurationService
{
- private static final Logger LOGGER = LoggerFactory
- .getLogger(ConfigurationServiceImpl.class);
+ private static final Logger LOG = LoggerFactory.getLogger(ConfigurationServiceImpl.class);
OvsdbConnectionService connectionService;
OvsdbInventoryService ovsdbInventoryService;
if (myParentUuid == null) {
myParentUuid = this.getSpecialCaseParentUUID(node, OvsVswitchdSchemaConstants.DATABASE_NAME, tableName);
}
- LOGGER.debug("insertRow Connection : {} Table : {} ParentTable : {} Parent Column: {} Parent UUID : {} Row : {}",
+ LOG.debug("insertRow Connection : {} Table : {} ParentTable : {} Parent Column: {} Parent UUID : {} Row : {}",
client.getConnectionInfo(), tableName, parentColumn[0], parentColumn[1], myParentUuid, row);
DatabaseSchema dbSchema = client.getDatabaseSchema(OvsVswitchdSchemaConstants.DATABASE_NAME);
@Deprecated
public Status updateRow (Node node, String tableName, String parentUUID, String rowUUID, Row row) {
String databaseName = OvsVswitchdSchemaConstants.DATABASE_NAME;
- Row<GenericTableSchema> updatedRow = this.updateRow(node, databaseName, tableName, new UUID(rowUUID), row, true);
+ this.updateRow(node, databaseName, tableName, new UUID(rowUUID), row, true);
return new StatusWithUuid(StatusCode.SUCCESS);
}
parentColumn = new String[]{null, null};
}
- LOGGER.debug("deleteRow : Connection : {} databaseName : {} tableName : {} Uuid : {} ParentTable : {} ParentColumn : {}",
+ LOG.debug("deleteRow : Connection : {} databaseName : {} tableName : {} Uuid : {} ParentTable : {} ParentColumn : {}",
client.getConnectionInfo(), databaseName, tableName, uuid, parentColumn[0], parentColumn[1]);
DatabaseSchema dbSchema = client.getDatabaseSchema(databaseName);
}
}
} catch (InterruptedException | ExecutionException e) {
- LOGGER.error("Error in deleteRow() {} {}", node, tableName, e);
+ LOG.error("Error in deleteRow() {} {}", node, tableName, e);
}
return new Status(StatusCode.SUCCESS);
@Override
@Deprecated
public ConcurrentMap<String, Row> getRows(Node node, String tableName) {
- ConcurrentMap<String, Row> ovsTable = ovsdbInventoryService.getTableCache(node, OvsVswitchdSchemaConstants.DATABASE_NAME, tableName);
- return ovsTable;
+ return ovsdbInventoryService.getTableCache(node, OvsVswitchdSchemaConstants.DATABASE_NAME, tableName);
}
@Override
return controllerIP;
}
} catch (UnknownHostException e) {
- LOGGER.error("Host {} is invalid", addressString);
+ LOG.error("Host {} is invalid", addressString);
}
}
return controllerIP;
}
} catch (UnknownHostException e) {
- LOGGER.error("Host {} is invalid", addressString);
+ LOG.error("Host {} is invalid", addressString);
}
}
controllerIP = connection.getClient().getConnectionInfo().getLocalAddress();
return controllerIP;
} catch (Exception e) {
- LOGGER.debug("Invalid connection provided to getControllerIPAddresses", e);
+ LOG.debug("Invalid connection provided to getControllerIPAddresses", e);
}
return controllerIP;
}
private short getControllerOFPort() {
- Short defaultOpenFlowPort = 6633;
- Short openFlowPort = defaultOpenFlowPort;
+ short openFlowPort = (short) 6633;
String portString = ConfigProperties.getProperty(this.getClass(), "of.listenPort");
if (portString != null) {
try {
- openFlowPort = Short.decode(portString).shortValue();
+ openFlowPort = Short.parseShort(portString);
} catch (NumberFormatException e) {
- LOGGER.warn("Invalid port:{}, use default({})", portString,
+ LOG.warn("Invalid port:{}, use default({})", portString,
openFlowPort);
}
}
bridge.setProtocols(protocols);
updateOperationStatus = this.updateRow(node, bridge.getSchema().getName(),
null, bridgeUUID, bridge.getRow());
- LOGGER.debug("Bridge {} updated to {} with Status {}", bridgeUUID,
+ LOG.debug("Bridge {} updated to {} with Status {}", bridgeUUID,
protocols.toArray()[0], updateOperationStatus);
} catch (SchemaVersionMismatchException e){
- LOGGER.debug(e.toString());
+ LOG.debug(e.toString());
}
// If we fail to update the protocols
return updateOperationStatus.isSuccess();
}
- Status status = null;
- UUID currControllerUuid = null;
+ Status status;
+ UUID currControllerUuid;
InetAddress ofControllerAddr = this.getControllerIPAddress(connection);
short ofControllerPort = getControllerOFPort();
String newControllerTarget = "tcp:"+ofControllerAddr.getHostAddress()+":"+ofControllerPort;
status = this.insertRow(node, controllerTableName, bridgeUUID, newController.getRow());
}
- if (status != null) {
- return status.isSuccess();
- }
+ return status != null && status.isSuccess();
- return false;
}
public Boolean setBridgeOFController(Node node, String bridgeIdentifier) {
if (connectionService == null) {
- LOGGER.error("Couldn't refer to the ConnectionService");
+ LOG.error("Couldn't refer to the ConnectionService");
return false;
}
}
}
} catch(Exception e) {
- LOGGER.error("Error in setBridgeOFController()", e);
+ LOG.error("Error in setBridgeOFController()", e);
}
return false;
}
@Override
public <T extends TypedBaseTable<?>> String getTableName(Node node, Class<T> typedClass) {
Connection connection = connectionService.getConnection(node);
- if (connection == null) return null;
+ if (connection == null) {
+ return null;
+ }
OvsdbClient client = connection.getClient();
TypedBaseTable<?> typedTable = client.getTypedRowWrapper(typedClass, null);
- if (typedTable == null) return null;
+ if (typedTable == null) {
+ return null;
+ }
return typedTable.getSchema().getName();
}
@Override
public <T extends TypedBaseTable<?>> T getTypedRow(Node node, Class<T> typedClass, Row row) {
Connection connection = connectionService.getConnection(node);
- if (connection == null) return null;
+ if (connection == null) {
+ return null;
+ }
OvsdbClient client = connection.getClient();
return (T)client.getTypedRowWrapper(typedClass, row);
}
@Override
public <T extends TypedBaseTable<?>> T createTypedRow(Node node, Class<T> typedClass) {
Connection connection = connectionService.getConnection(node);
- if (connection == null) return null;
+ if (connection == null) {
+ return null;
+ }
OvsdbClient client = connection.getClient();
return client.createTypedRowWrapper(typedClass);
}
private String getTableNameForRowUuid(Node node, String databaseName, UUID rowUuid) {
ConcurrentMap<String, ConcurrentMap<String, Row>> cache = ovsdbInventoryService.getCache(node, databaseName);
- if (cache == null) return null;
+ if (cache == null) {
+ return null;
+ }
for (String tableName : cache.keySet()) {
ConcurrentMap<String, Row> rows = cache.get(tableName);
if (rows.get(rowUuid.toString()) != null) {
parentColumn = this.getReferencingColumn(parentTableSchema, tableName);
}
- LOGGER.debug("insertTree Connection : {} Table : {} ParentTable : {} Parent Column: {} Parent UUID : {} Row : {}",
+ LOG.debug("insertTree Connection : {} Table : {} ParentTable : {} Parent Column: {} Parent UUID : {} Row : {}",
client.getConnectionInfo(), tableName, parentTable, parentColumn, parentUuid, row);
Map<UUID, Map.Entry<String, Row<GenericTableSchema>>> referencedRows = Maps.newConcurrentMap();
}
for (OperationResult result : operationResults) {
if (result.getError() != null) {
- throw new OvsdbPluginException("Insert Operation Failed with Error : "+result.getError().toString());
+ throw new OvsdbPluginException("Insert Operation Failed with Error : " + result.getError());
}
}
return getNormalizedRow(dbSchema, tableName, row, referencedRows, operationResults, referencedRowsInsertIndex);
DatabaseSchema dbSchema = client.getSchema(dbName).get();
GenericTableSchema schema = dbSchema.table(refRowObject.getRefTable(), GenericTableSchema.class);
Row<GenericTableSchema> refRow = schema.createRow((ObjectNode)refRowObject.getJsonNode());
- referencedRows.put(refUuid, new AbstractMap.SimpleEntry<String, Row<GenericTableSchema>>(refRowObject.getRefTable(), refRow));
+ referencedRows.put(refUuid, new AbstractMap.SimpleEntry<>(refRowObject.getRefTable(), refRow));
extractReferencedRows(node, dbName, refRow, referencedRows, namedUuidSuffix);
} catch (InterruptedException | ExecutionException e) {
- LOGGER.error("Exception while extracting multi-level Row references " + e.getLocalizedMessage());
+ LOG.error("Exception while extracting multi-level Row references " + e.getLocalizedMessage());
}
} else if (column.getData() instanceof OvsdbSet) {
OvsdbSet<Object> setObject = (OvsdbSet<Object>)column.getData();
- OvsdbSet<Object> modifiedSet = new OvsdbSet<Object>();
+ OvsdbSet<Object> modifiedSet = new OvsdbSet<>();
for (Object obj : setObject) {
if (obj instanceof ReferencedRow) {
ReferencedRow refRowObject = (ReferencedRow)obj;
DatabaseSchema dbSchema = client.getSchema(dbName).get();
GenericTableSchema schema = dbSchema.table(refRowObject.getRefTable(), GenericTableSchema.class);
Row<GenericTableSchema> refRow = schema.createRow((ObjectNode)refRowObject.getJsonNode());
- referencedRows.put(refUuid, new AbstractMap.SimpleEntry<String, Row<GenericTableSchema>>(refRowObject.getRefTable(), refRow));
+ referencedRows.put(refUuid, new AbstractMap.SimpleEntry<>(refRowObject.getRefTable(), refRow));
extractReferencedRows(node, dbName, refRow, referencedRows, namedUuidSuffix);
} catch (InterruptedException | ExecutionException e) {
- LOGGER.error("Exception while extracting multi-level Row references " + e.getLocalizedMessage());
+ LOG.error("Exception while extracting multi-level Row references " + e.getLocalizedMessage());
}
} else {
modifiedSet.add(obj);
TableSchema<GenericTableSchema> primaryRowTableSchema = dbSchema.table(tableName, GenericTableSchema.class);
ColumnSchema<GenericTableSchema, UUID> uuid = primaryRowTableSchema.column("_uuid", UUID.class);
if (uuid != null) {
- Column<GenericTableSchema, UUID> uuidColumn = new Column<GenericTableSchema, UUID>(uuid, primaryRowUuid);
+ Column<GenericTableSchema, UUID> uuidColumn = new Column<>(uuid, primaryRowUuid);
row.addColumn("_uuid", uuidColumn);
}
if (referencedRows != null) {
Collection<Column<GenericTableSchema, ?>> columns = row.getColumns();
- if (referencedRows != null) {
- for (int idx=0; idx < referencedRows.keySet().size(); idx++) {
- UUID refUuid = (UUID) referencedRows.keySet().toArray()[idx];
- for (Column column : columns) {
- if (column.getData() != null) {
- if ((column.getData() instanceof UUID) && column.getData().equals(refUuid)) {
- column.setData(operationResults.get(referencedRowsInsertIndex + idx).getUuid());
- } else if ((column.getData() instanceof OvsdbSet) && ((OvsdbSet)column.getData()).contains(refUuid)) {
- OvsdbSet<UUID> refSet = (OvsdbSet<UUID>)column.getData();
- refSet.remove(refUuid);
- refSet.add(operationResults.get(referencedRowsInsertIndex + idx).getUuid());
- }
+ Object[] rowKeys = referencedRows.keySet().toArray();
+ for (int idx = 0; idx < rowKeys.length; idx++) {
+ UUID refUuid = (UUID) rowKeys[idx];
+ for (Column column : columns) {
+ if (column.getData() != null) {
+ if ((column.getData() instanceof UUID) && column.getData().equals(refUuid)) {
+ column.setData(operationResults.get(referencedRowsInsertIndex + idx).getUuid());
+ } else if ((column.getData() instanceof OvsdbSet) && ((OvsdbSet)column.getData()).contains(refUuid)) {
+ OvsdbSet<UUID> refSet = (OvsdbSet<UUID>)column.getData();
+ refSet.remove(refUuid);
+ refSet.add(operationResults.get(referencedRowsInsertIndex + idx).getUuid());
}
}
}
Connection connection = connectionService.getConnection(node);
OvsdbClient client = connection.getClient();
- LOGGER.debug("updateRow : Connection : {} databaseName : {} tableName : {} rowUUID : {} row : {}",
+ LOG.debug("updateRow : Connection : {} databaseName : {} tableName : {} rowUUID : {} row : {}",
client.getConnectionInfo(), databaseName, tableName, rowUuid, row.toString());
try{
DatabaseSchema dbSchema = client.getDatabaseSchema(databaseName);
myParentColumn = this.getReferencingColumn(parentTableSchema, tableName);
}
- LOGGER.debug("deleteRow : Connection : {} databaseName : {} tableName : {} Uuid : {} ParentTable : {} ParentColumn : {}",
+ LOG.debug("deleteRow : Connection : {} databaseName : {} tableName : {} Uuid : {} ParentTable : {} ParentColumn : {}",
client.getConnectionInfo(), databaseName, tableName, rowUuid, parentTable, myParentColumn);
DatabaseSchema dbSchema = client.getDatabaseSchema(databaseName);
}
for (OperationResult result : operationResults) {
if (result.getError() != null) {
- throw new OvsdbPluginException("Delete Operation Failed with Error : "+result.getError().toString());
+ throw new OvsdbPluginException("Delete Operation Failed with Error : " + result.getError());
}
}
} catch (InterruptedException | ExecutionException e) {
- LOGGER.error("Error in deleteRow() {} {} {} {}", node, databaseName, tableName, parentTable, e);
+ LOG.error("Error in deleteRow() {} {} {} {}", node, databaseName, tableName, parentTable, e);
}
}
if (cache == null) {
return null;
} else {
- return new ArrayList<String>(cache.keySet());
+ return new ArrayList<>(cache.keySet());
}
}
}
/*
- * Copyright (C) 2013 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal, Brent Salisbury, Evan Zeller
*/
+
package org.opendaylight.ovsdb.plugin.impl;
import io.netty.channel.ChannelHandler;
*/
public class ConnectionServiceImpl implements OvsdbConnectionService,
OvsdbConnectionListener {
- protected static final Logger logger = LoggerFactory.getLogger(ConnectionServiceImpl.class);
+ private static final Logger LOG = LoggerFactory.getLogger(ConnectionServiceImpl.class);
// Properties that can be set in config.ini
private static final Integer DEFAULT_OVSDB_PORT = 6640;
String portString = ConfigProperties.getProperty(OvsdbConnectionService.class, OVSDB_LISTENPORT);
int ovsdbListenPort = DEFAULT_OVSDB_PORT;
if (portString != null) {
- ovsdbListenPort = Integer.decode(portString).intValue();
+ ovsdbListenPort = Integer.parseInt(portString);
}
if (!connectionLib.startOvsdbManager(ovsdbListenPort)) {
- logger.warn("Start OVSDB manager call from ConnectionService was not necessary");
+ LOG.warn("Start OVSDB manager call from ConnectionService was not necessary");
}
/* Then get connection clients */
Collection<OvsdbClient> connections = connectionLib.getConnections();
for (OvsdbClient client : connections) {
- logger.info("CONNECT start connected clients client = {}", client);
+ LOG.info("CONNECT start connected clients client = {}", client);
this.connected(client);
}
}
try {
address = InetAddress.getByName(params.get(ConnectionConstants.ADDRESS));
} catch (Exception e) {
- logger.error("Unable to resolve " + params.get(ConnectionConstants.ADDRESS), e);
+ LOG.error("Unable to resolve {}", params.get(ConnectionConstants.ADDRESS), e);
return null;
}
try {
port = Integer.parseInt(params.get(ConnectionConstants.PORT));
- if (port == 0) port = DEFAULT_OVSDB_PORT;
+ if (port == 0) {
+ port = DEFAULT_OVSDB_PORT;
+ }
} catch (Exception e) {
port = DEFAULT_OVSDB_PORT;
}
OvsdbClient client = connectionLib.connect(address, port);
return handleNewConnection(identifier, client);
} catch (InterruptedException e) {
- logger.error("Thread was interrupted during connect", e);
+ LOG.error("Thread was interrupted during connect", e);
} catch (ExecutionException e) {
- logger.error("ExecutionException in handleNewConnection for identifier " + identifier, e);
+ LOG.error("ExecutionException in handleNewConnection for identifier " + identifier, e);
}
return null;
}
@Override
public List<Node> getNodes() {
- List<Node> nodes = new ArrayList<Node>();
+ List<Node> nodes = new ArrayList<>();
for (Connection connection : ovsdbConnections.values()) {
nodes.add(connection.getNode());
}
@Override
public void run() {
try {
- logger.info("Initialize inventory for {}", connection.toString());
+ LOG.info("Initialize inventory for {}", connection.toString());
initializeInventoryForNewNode(connection);
} catch (InterruptedException | ExecutionException | IOException e) {
- logger.error("Failed to initialize inventory for node with identifier " + identifier, e);
+ LOG.error("Failed to initialize inventory for node with identifier {}", identifier, e);
ovsdbConnections.remove(identifier);
}
}
}
public void channelClosed(Node node) throws Exception {
- logger.info("Connection to Node : {} closed", node);
+ LOG.info("Connection to Node : {} closed", node);
disconnect(node);
ovsdbInventoryService.removeNode(node);
}
List<String> databases = client.getDatabases().get();
if (databases == null) {
- logger.error("Unable to get Databases for the ovsdb connection : {}", client.getConnectionInfo());
+ LOG.error("Unable to get Databases for the ovsdb connection : {}", client.getConnectionInfo());
return;
}
for (String database : databases) {
TableUpdates updates = this.monitorTables(connection.getNode(), dbSchema);
ovsdbInventoryService.processTableUpdates(connection.getNode(), dbSchema.getName(), updates);
}
- logger.info("Notifying Inventory Listeners for Node Added: {}", connection.getNode().toString());
+ LOG.info("Notifying Inventory Listeners for Node Added: {}", connection.getNode().toString());
ovsdbInventoryService.notifyNodeAdded(connection.getNode(), address, port);
}
Connection connection = getConnection(node);
OvsdbClient client = connection.getClient();
if (dbSchema == null) {
- logger.error("Unable to get Database Schema for the ovsdb connection : {}", client.getConnectionInfo());
+ LOG.error("Unable to get Database Schema for the ovsdb connection : {}", client.getConnectionInfo());
return null;
}
Set<String> tables = dbSchema.getTables();
if (tables == null) {
- logger.warn("Database {} without any tables. Strange !", dbSchema.getName());
+ LOG.warn("Database {} without any tables. Strange !", dbSchema.getName());
return null;
}
List<MonitorRequest<GenericTableSchema>> monitorRequests = Lists.newArrayList();
@Override
public void disconnected(OvsdbClient client) {
Connection connection = ovsdbConnections.get(this.getConnectionIdentifier(client));
- if (connection == null) return;
+ if (connection == null) {
+ return;
+ }
this.disconnect(connection.getNode());
}
}
/*
- * Copyright (C) 2013 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal, Brent Salisbury
*/
+
package org.opendaylight.ovsdb.plugin.impl;
import java.net.InetAddress;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
import com.google.common.collect.Sets;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import com.google.common.collect.Maps;
*
*/
public class InventoryServiceImpl implements OvsdbInventoryService {
- private static final Logger logger = LoggerFactory
- .getLogger(InventoryServiceImpl.class);
private ConcurrentMap<Node, NodeDatabase> dbCache = Maps.newConcurrentMap();
private ScheduledExecutorService executor;
private OvsdbConfigurationService ovsdbConfigurationService;
@Override
public ConcurrentMap<String, ConcurrentMap<String, Row>> getCache(Node n, String databaseName) {
NodeDatabase db = dbCache.get(n);
- if (db == null) return null;
+ if (db == null) {
+ return null;
+ }
return db.getDatabase(databaseName);
}
@Override
public ConcurrentMap<String, Row> getTableCache(Node n, String databaseName, String tableName) {
NodeDatabase db = dbCache.get(n);
- if (db == null) return null;
+ if (db == null) {
+ return null;
+ }
return db.getTableCache(databaseName, tableName);
}
@Override
public Row getRow(Node n, String databaseName, String tableName, String uuid) {
NodeDatabase db = dbCache.get(n);
- if (db == null) return null;
+ if (db == null) {
+ return null;
+ }
return db.getRow(databaseName, tableName, uuid);
}
@Override
public void removeRow(Node n, String databaseName, String tableName, String uuid) {
NodeDatabase db = dbCache.get(n);
- if (db != null) db.removeRow(databaseName, tableName, uuid);
+ if (db != null) {
+ db.removeRow(databaseName, tableName, uuid);
+ }
}
@Override
for (UUID uuid : (Set<UUID>)update.getRows().keySet()) {
if (update.getNew(uuid) != null) {
- boolean isNewRow = (tCache == null || tCache.get(uuid.toString()) == null) ? true : false;
+ boolean isNewRow = (tCache == null || tCache.get(uuid.toString()) == null);
db.updateRow(databaseName, tableName, uuid.toString(), update.getNew(uuid));
if (isNewRow) {
this.handleOpenVSwitchSpecialCase(n, databaseName, tableName, uuid);
@Override
public void run() {
try {
- if (ovsdbConfigurationService != null) ovsdbConfigurationService.setOFController(node, uuid.toString());
+ if (ovsdbConfigurationService != null) {
+ ovsdbConfigurationService.setOFController(node, uuid.toString());
+ }
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
/*
- * Copyright (C) 2013 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal, Brent Salisbury
*/
+
package org.opendaylight.ovsdb.plugin.internal;
import org.apache.felix.dm.DependencyActivatorBase;
/*
- * [[ Authors will Fill in the Copyright header ]]
+ * 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
- *
- * Authors : Brent Salisbury, Evan Zeller
*/
+
package org.opendaylight.ovsdb.plugin.internal;
public enum Encapsulation {
/*
- * Copyright (C) 2013 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal, Brent Salisbury
*/
+
package org.opendaylight.ovsdb.plugin.internal;
import java.util.Collection;
prtLn('aliasMap:', 0)
resultMap = {}
for bridge in state.bridgeNodes.values():
- resultMap[ bridge.alias ] = bridge.getOpenflowName()
+ resultMap[ bridge.alias ] = '{0: <25} {1: <7} {2}'.format(bridge.getOpenflowName(), bridge.name, bridge.dpId)
- resultMapKeys = resultMap.keys()
- resultMapKeys.sort()
-
- for resultMapKey in resultMapKeys:
- prtLn('{0}{1: <10} -> {2}'.format(spc, resultMapKey, resultMap[resultMapKey]), 0)
+ for resultMapKey in sorted(resultMap):
+ prtLn('{0}{1: <10} -> {2}'.format(spc, resultMapKey, resultMap[resultMapKey]), 0)
prtLn('', 0)
# --
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Flavio Fernandes, Sam Hague, Srini Seetharaman
*/
package org.opendaylight.ovsdb.utils.config;
/*
- * Copyright (C) 2015 Red Hat, Inc.
+ * 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
- *
- * Authors : Sam Hague
*/
+
package org.opendaylight.ovsdb.utils.mdsal.node;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
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.slf4j.Logger;
-import org.slf4j.LoggerFactory;
public class NodeUtils {
- protected static final Logger LOG = LoggerFactory.getLogger(NodeUtils.class);
public static String getId (String identifier) {
String id = identifier;
public static Node getOpenFlowNode (String identifier) {
NodeId nodeId = new NodeId(identifier);
NodeKey nodeKey = new NodeKey(nodeId);
- Node node = new NodeBuilder()
+
+ return new NodeBuilder()
.setId(nodeId)
.setKey(nodeKey)
.build();
-
- return node;
}
}
/*
- * Copyright (C) 2014 Red Hat, Inc.
+ * 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
- *
- * Authors : Madhu Venugopal, Brent Salisbury, Srini Seetharaman
*/
+
package org.opendaylight.ovsdb.utils.mdsal.openflow;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Uri;
final String HEXES = "0123456789ABCDEF";
byte[] address = new byte[6];
String[] macBytes = macAddress.split(":");
- if (macBytes.length != 6)
+ 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()
/*
- * Copyright (C) 2013 Red Hat, Inc.
+ * 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.ovsdb.utils.mdsal.openflow;
import java.util.List;
public class InstructionUtils {
- private static final Logger logger = LoggerFactory.getLogger(InstructionUtils.class);
+ private static final Logger LOG = LoggerFactory.getLogger(InstructionUtils.class);
private static final int IPV4 = 0x8100;
private static final int MAX_LENGTH = 0xffff;
public static InstructionBuilder createOutputPortInstructions(InstructionBuilder ib, Long dpidLong, Long port) {
NodeConnectorId ncid = new NodeConnectorId("openflow:" + dpidLong + ":" + port);
- logger.debug("createOutputPortInstructions() Node Connector ID is - Type=openflow: DPID={} inPort={} ",
+ LOG.debug("createOutputPortInstructions() Node Connector ID is - Type=openflow: DPID={} inPort={} ",
dpidLong, port);
List<Action> actionList = Lists.newArrayList();
Long dpidLong, Long port,
List<Instruction> instructions) {
NodeConnectorId ncid = new NodeConnectorId("openflow:" + dpidLong + ":" + port);
- logger.debug(
+ LOG.debug(
"addOutputPortInstructions() Node Connector ID is - Type=openflow: DPID={} port={} existingInstructions={}",
dpidLong, port, instructions);
final NodeConnectorId ncid = new NodeConnectorId("openflow:" + dpidLong + ":" + port);
final Uri ncidUri = new Uri(ncid);
- logger.debug(
+ LOG.debug(
"removeOutputPortFromInstructions() Node Connector ID is - Type=openflow: DPID={} port={} existingInstructions={}",
dpidLong, port, instructions);
} else if (action.getOrder() == removedActionOrder) {
// Sanity: implementation assumes no two actions have the same order
//
- logger.error("Found action with same order as the action removed for {}, order {} index {}: {}",
+ LOG.error("Found action with same order as the action removed for {}, order {} index {}: {}",
ncid, removedActionOrder, i, action);
}
// 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 (int i = 0; i < actionList.size(); i++) {
- if (actionList.get(i).getAction() instanceof OutputActionCase) {
+ for (Action action : actionList) {
+ if (action.getAction() instanceof OutputActionCase) {
removeFlow = false;
break;
}
ApplyActionsBuilder aab = new ApplyActionsBuilder();
aab.setAction(actionList);
ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
- logger.debug("removeOutputPortFromInstructions() : applyAction {}", aab.build());
+ LOG.debug("removeOutputPortFromInstructions() : applyAction {}", aab.build());
return false;
} else {
/* if all output ports are removed. Return true to indicate flow remove */
return ib;
}
- public static ArrayList<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action>
- actionList (org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action... actions) {
+ public static List<Action>
+ actionList(org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action... actions) {
ArrayList<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action> alist
= new ArrayList<>();
}
public static Instructions getInstructions(org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.Instruction... instructions) {
- ArrayList<org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction> ins
+ List<Instruction> ins
= new ArrayList<>();
int order = 0;
for (org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.Instruction i : instructions) {
*/
public static List<Instruction> getInstructionList(
org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.Instruction... instructions) {
- ArrayList<org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction> ins
+ List<Instruction> ins
= new ArrayList<>();
int order = 0;
for (org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.Instruction i : instructions) {
/*
- * Copyright (C) 2013 Red Hat, Inc.
+ * 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.ovsdb.utils.mdsal.openflow;
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._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 com.google.common.collect.Lists;
public class MatchUtils {
- private static final Logger logger = LoggerFactory.getLogger(MatchUtils.class);
+ 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 MatchBuilder createInPortMatch(MatchBuilder matchBuilder, Long dpidLong, Long inPort) {
NodeConnectorId ncid = new NodeConnectorId("openflow:" + dpidLong + ":" + inPort);
- logger.debug("createInPortMatch() Node Connector ID is - Type=openflow: DPID={} inPort={} ", 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;
}
+ /**
+ * Create a DHCP match with pot 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;
+
+ }
+
+ /**
+ * 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;
+
+ }
+
+ /**
+ * @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(new Ipv4Prefix(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;
+
+ }
+
public static class RegMatch {
final Class<? extends NxmNxReg> reg;
final Long value;
public static void addNxRegMatch(MatchBuilder match,
RegMatch... matches) {
- ArrayList<ExtensionList> extensions = new ArrayList<>();
+ List<ExtensionList> extensions = new ArrayList<>();
for (RegMatch rm : matches) {
Class<? extends ExtensionKey> key;
if (NxmNxReg0.class.equals(rm.reg)) {
MacAddress dstMac,
Long etherType) {
EthernetMatchBuilder emb = new EthernetMatchBuilder();
- if (srcMac != null)
+ if (srcMac != null) {
emb.setEthernetSource(new EthernetSourceBuilder()
.setAddress(srcMac)
.build());
- if (dstMac != null)
+ }
+ if (dstMac != null) {
emb.setEthernetDestination(new EthernetDestinationBuilder()
.setAddress(dstMac)
.build());
- if (etherType != null)
+ }
+ if (etherType != null) {
emb.setEthernetType(new EthernetTypeBuilder()
.setType(new EtherType(etherType))
.build());
+ }
return emb.build();
}
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-simple</artifactId>
- <scope>test</scope>
- </dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.2.1</version>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-simple</artifactId>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<build>
<plugins>
package org.opendaylight.ovsdb.utils.servicehelper;
+import org.osgi.framework.Bundle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.osgi.framework.BundleContext;
public static Object getGlobalInstance(Class<?> clazz, Object bundle,
String serviceFilter) {
Object[] instances = getGlobalInstances(clazz, bundle, serviceFilter);
- if (instances != null) {
+ if (instances != null && instances.length > 0) {
return instances[0];
}
return null;
String serviceFilter) {
Object instances[] = null;
try {
- BundleContext bCtx = FrameworkUtil.getBundle(bundle.getClass())
- .getBundleContext();
+ Bundle ourBundle = FrameworkUtil.getBundle(bundle.getClass());
+ if (ourBundle != null) {
+ BundleContext bCtx = ourBundle.getBundleContext();
- ServiceReference<?>[] services = bCtx.getServiceReferences(clazz
- .getName(), serviceFilter);
+ 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]);
+ 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("Instance reference is NULL");
+ LOG.error("Error retrieving global instances of {} from caller {} with filter {}",
+ clazz, bundle, serviceFilter, e);
}
return instances;
}
Bundle bundle = new MockBundle();
PowerMockito.mockStatic(FrameworkUtil.class);
- PowerMockito.when(FrameworkUtil.getBundle(any(Class.class)))
- .thenReturn(null)
- .thenReturn(bundle);
+ 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);
}