import org.opendaylight.ovsdb.hwvtepsouthbound.HwvtepSouthboundConstants;
import org.opendaylight.ovsdb.hwvtepsouthbound.HwvtepSouthboundMapper;
-import org.opendaylight.ovsdb.utils.mdsal.utils.MdsalUtils;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class HwvtepSouthboundUtils {
+public final class HwvtepSouthboundUtils {
private static final Logger LOG = LoggerFactory.getLogger(HwvtepSouthboundUtils.class);
- private static final int HWVTEP_UPDATE_TIMEOUT = 1000;
- private final MdsalUtils mdsalUtils;
- public HwvtepSouthboundUtils(MdsalUtils mdsalUtils) {
- this.mdsalUtils = mdsalUtils;
+ private HwvtepSouthboundUtils() {
}
public static NodeId createNodeId(IpAddress ip, PortNumber port) {
@Override
public String toString() {
- return "MdsalObject{" +
- "dataObject=" + dataObject +
- ", iid=" + iid +
- '}';
+ return "MdsalObject{" + "dataObject=" + dataObject + ", iid=" + iid + '}';
}
}
public class MdsalUtils {
private static final Logger LOG = LoggerFactory.getLogger(MdsalUtils.class);
- private DataBroker databroker = null;
private static int MDSAL_MAX_READ_TRIALS = Integer.getInteger("mdsalutil.max.tries", 30);
private static int MDSAL_READ_SLEEP_INTERVAL_MS = Integer.getInteger("mdsalutil.sleep.between.mdsal.reads", 1000);
+
+ private final DataBroker databroker;
+
/**
* Class constructor setting the data broker.
*
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.MoreExecutors;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
}
@Override
- public void onFailure(final Throwable t) {
+ public void onFailure(final Throwable ex) {
transaction.close();
}
};
* @param operationDesc
* A description of the transaction to commit.
*/
- void assignDefaultCallback(final CheckedFuture<Void, TransactionCommitFailedException> transactionFuture, final String operationDesc) {
+ void assignDefaultCallback(final CheckedFuture<Void, TransactionCommitFailedException> transactionFuture,
+ final String operationDesc) {
Futures.addCallback(transactionFuture, new FutureCallback<Void>() {
@Override
public void onSuccess(final Void result) {
}
@Override
- public void onFailure(final Throwable t) {
- LOG.error("Transaction({}) {} FAILED!", operationDesc, t);
- throw new IllegalStateException(" Transaction(" + operationDesc + ") not committed correctly", t);
+ public void onFailure(final Throwable ex) {
+ LOG.error("Transaction({}) {} FAILED!", operationDesc, ex);
+ throw new IllegalStateException(" Transaction(" + operationDesc + ") not committed correctly", ex);
}
- });
+ }, MoreExecutors.directExecutor());
}
}
package org.opendaylight.ovsdb.utils.mdsal.utils;
import java.util.Collection;
-import java.util.HashSet;
import java.util.List;
import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
import org.opendaylight.controller.md.sal.binding.api.DataTreeChangeListener;
*/
public class NotifyingDataChangeListener implements AutoCloseable, DataTreeChangeListener<DataObject> {
private static final Logger LOG = LoggerFactory.getLogger(NotifyingDataChangeListener.class);
- private LogicalDatastoreType type;
- private final Set<InstanceIdentifier<?>> createdIids = new HashSet<>();
- private final Set<InstanceIdentifier<?>> removedIids = new HashSet<>();
- private final Set<InstanceIdentifier<?>> updatedIids = new HashSet<>();
- private InstanceIdentifier<?> iid;
- private final static int RETRY_WAIT = 100;
- private final static int MDSAL_TIMEOUT_OPERATIONAL = 10000;
- private final static int MDSAL_TIMEOUT_CONFIG = 1000;
- private ListenerRegistration<?> listenerRegistration;
- private List<NotifyingDataChangeListener> waitList = null;
- private int mdsalTimeout = MDSAL_TIMEOUT_OPERATIONAL;
- private Boolean listen;
+ private static final int RETRY_WAIT = 100;
+ private static final int MDSAL_TIMEOUT_OPERATIONAL = 10000;
+ private static final int MDSAL_TIMEOUT_CONFIG = 1000;
+
public static final int BIT_CREATE = 1;
public static final int BIT_UPDATE = 2;
public static final int BIT_DELETE = 4;
public static final int BIT_ALL = 7;
- private int mask;
+
+ private final Set<InstanceIdentifier<?>> createdIids = ConcurrentHashMap.newKeySet();
+ private final Set<InstanceIdentifier<?>> removedIids = ConcurrentHashMap.newKeySet();
+ private final Set<InstanceIdentifier<?>> updatedIids = ConcurrentHashMap.newKeySet();
+ private final List<NotifyingDataChangeListener> waitList;
+ private ListenerRegistration<?> listenerRegistration;
+ private int mdsalTimeout = MDSAL_TIMEOUT_OPERATIONAL;
+ private volatile InstanceIdentifier<?> iid;
+ private volatile LogicalDatastoreType type;
+ private volatile boolean listen;
+ private volatile int mask;
public NotifyingDataChangeListener(LogicalDatastoreType type, int mask,
InstanceIdentifier<?> iid, List<NotifyingDataChangeListener> waitList) {
}
/**
- * Create a new NotifyingDataChangeListener
+ * Create a new NotifyingDataChangeListener.
+ *
* @param type DataStore type
* @param iid of the md-sal object we're waiting for
* @param waitList for tracking outstanding changes
/**
* Completely reset the state of this NotifyingDataChangeListener.
- * @param type DataStore type
- * @param iid of the md-sal object we're waiting for
- * @throws Exception
+ *
+ * @param newType DataStore type
+ * @param newIid of the md-sal object we're waiting for
+ * @throws Exception on failure
*/
- public void modify(LogicalDatastoreType type, InstanceIdentifier<?> iid) throws Exception {
+ public void modify(LogicalDatastoreType newType, InstanceIdentifier<?> newIid) throws Exception {
this.close();
this.clear();
- this.type = type;
- this.iid = iid;
+ this.type = newType;
+ this.iid = newIid;
}
- public void setlisten(Boolean listen) {
- this.listen = listen;
+ public void setlisten(boolean value) {
+ this.listen = value;
}
public void setMask(int mask) {
}
}
- public boolean isCreated(InstanceIdentifier<?> iid) {
- return createdIids.remove(iid);
+ public boolean isCreated(InstanceIdentifier<?> path) {
+ return createdIids.remove(path);
}
- public boolean isUpdated(InstanceIdentifier<?> iid) {
- return updatedIids.remove(iid);
+ public boolean isUpdated(InstanceIdentifier<?> path) {
+ return updatedIids.remove(path);
}
- public boolean isRemoved(InstanceIdentifier<?> iid) {
- return removedIids.remove(iid);
+ public boolean isRemoved(InstanceIdentifier<?> path) {
+ return removedIids.remove(path);
}
public void clear() {
public void waitForCreation(long timeout) throws InterruptedException {
synchronized (this) {
- long _start = System.currentTimeMillis();
+ long start = System.currentTimeMillis();
LOG.info("Waiting for {} DataChanged creation on {}", type, iid);
- while (!isCreated(iid) && System.currentTimeMillis() - _start < timeout) {
+ while (!isCreated(iid) && System.currentTimeMillis() - start < timeout) {
wait(RETRY_WAIT);
}
- LOG.info("Woke up, waited {}ms for creation of {}", System.currentTimeMillis() - _start, iid);
+ LOG.info("Woke up, waited {}ms for creation of {}", System.currentTimeMillis() - start, iid);
}
}
public void waitForUpdate(long timeout) throws InterruptedException {
synchronized (this) {
- long _start = System.currentTimeMillis();
+ long start = System.currentTimeMillis();
LOG.info("Waiting for {} DataChanged update on {}", type, iid);
- while (!isUpdated(iid) && System.currentTimeMillis() - _start < timeout) {
+ while (!isUpdated(iid) && System.currentTimeMillis() - start < timeout) {
wait(RETRY_WAIT);
}
- LOG.info("Woke up, waited {}ms for update of {}", System.currentTimeMillis() - _start, iid);
+ LOG.info("Woke up, waited {}ms for update of {}", System.currentTimeMillis() - start, iid);
}
}
public void waitForDeletion(long timeout) throws InterruptedException {
synchronized (this) {
- long _start = System.currentTimeMillis();
+ long start = System.currentTimeMillis();
LOG.info("Waiting for {} DataChanged deletion on {}", type, iid);
- while (!isRemoved(iid) && System.currentTimeMillis() - _start < timeout) {
+ while (!isRemoved(iid) && System.currentTimeMillis() - start < timeout) {
wait(RETRY_WAIT);
}
- LOG.info("Woke up, waited {}ms for deletion of {}", System.currentTimeMillis() - _start, iid);
+ LOG.info("Woke up, waited {}ms for deletion of {}", System.currentTimeMillis() - start, iid);
}
}
@Override
- public void close() throws Exception {
+ public void close() {
if (listenerRegistration != null) {
- try {
- listenerRegistration.close();
- } catch (final Exception ex) {
- LOG.warn("Failed to close registration {}, iid {}", listenerRegistration, iid, ex);
- }
+ listenerRegistration.close();
}
+
if (waitList != null) {
waitList.remove(this);
}
+
listenerRegistration = null;
}
}
package org.opendaylight.ovsdb.utils.mdsal.utils;
public class TransactionElement {
- private long date;
- private TransactionType transactionType;
- private Object data;
+ private final long date;
+ private final TransactionType transactionType;
+ private final Object data;
public TransactionElement(TransactionType transactionType, Object data) {
this.data = data;
@Override
public String toString() {
- return "TransactionElement{" +
- "date=" + date +
- ", transactionType=" + transactionType +
- ", data=" + data +
- '}';
+ return "TransactionElement{" + "date=" + date + ", transactionType=" + transactionType + ", data=" + data + '}';
}
}
package org.opendaylight.ovsdb.utils.mdsal.utils;
+import java.util.ArrayList;
import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.ArrayList;
public class TransactionHistory extends ArrayList<TransactionElement> {
+ private static final long serialVersionUID = 1L;
private final int capacity;
private final int watermark;
package org.opendaylight.ovsdb.utils.mdsal.utils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.ArrayList;
-
public enum TransactionType {
ADD,
UPDATE,
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
-import java.util.Arrays;
+import com.google.common.util.concurrent.MoreExecutors;
import java.util.Collections;
import java.util.concurrent.ExecutionException;
import org.junit.Before;
private static final NodeId NODE_ID = new NodeId("test");
private static final NodeKey NODE_KEY = new NodeKey(NODE_ID);
- private static final Node data = new NodeBuilder().setKey(NODE_KEY).setNodeId(NODE_ID).build();
+ private static final Node DATA = new NodeBuilder().setKey(NODE_KEY).setNodeId(NODE_ID).build();
private static final InstanceIdentifier<Node> TEST_IID = InstanceIdentifier
.create(NetworkTopology.class)
@Test
public void testDelete() {
- final CheckedFuture<Void, TransactionCommitFailedException> fut = mdsalUtilsAsync.put(LogicalDatastoreType.CONFIGURATION, TEST_IID, data);
+ final CheckedFuture<Void, TransactionCommitFailedException> fut = mdsalUtilsAsync.put(
+ LogicalDatastoreType.CONFIGURATION, TEST_IID, DATA);
Futures.addCallback(fut, new FutureCallback<Void>() {
@Override
public void onSuccess(final Void result) {
- final CheckedFuture<Void, TransactionCommitFailedException> future = mdsalUtilsAsync.delete(LogicalDatastoreType.CONFIGURATION, TEST_IID);
+ final CheckedFuture<Void, TransactionCommitFailedException> future =
+ mdsalUtilsAsync.delete(LogicalDatastoreType.CONFIGURATION, TEST_IID);
Futures.addCallback(future, new FutureCallback<Void>() {
@Override
}
@Override
- public void onFailure(final Throwable t) {
- fail(t.getMessage());
+ public void onFailure(final Throwable ex) {
+ fail(ex.getMessage());
}
- });
+ }, MoreExecutors.directExecutor());
}
+
@Override
- public void onFailure(final Throwable t) {
- fail(t.getMessage());
+ public void onFailure(final Throwable ex) {
+ fail(ex.getMessage());
}
- });
+ }, MoreExecutors.directExecutor());
}
@Test
public void testPutWithoutCallback() {
final String operationDesc = "testPut";
- final SupportingNode supportingNodeBuilder1 = new SupportingNodeBuilder().setKey(new SupportingNodeKey(new NodeId("id1"), TOPOLOGY_TEST)).build();
- final SupportingNode supportingNodeBuilder2 = new SupportingNodeBuilder().setKey(new SupportingNodeKey(new NodeId("id2"), TOPOLOGY_TEST)).build();
+ final SupportingNode supportingNodeBuilder1 = new SupportingNodeBuilder().setKey(
+ new SupportingNodeKey(new NodeId("id1"), TOPOLOGY_TEST)).build();
+ final SupportingNode supportingNodeBuilder2 = new SupportingNodeBuilder().setKey(
+ new SupportingNodeKey(new NodeId("id2"), TOPOLOGY_TEST)).build();
- final Node data1 = new NodeBuilder(data).setSupportingNode(Collections.singletonList(supportingNodeBuilder1)).build();
- final Node data2 = new NodeBuilder(data).setSupportingNode(Collections.singletonList(supportingNodeBuilder2)).build();
+ final Node data1 = new NodeBuilder(DATA).setSupportingNode(
+ Collections.singletonList(supportingNodeBuilder1)).build();
+ final Node data2 = new NodeBuilder(DATA).setSupportingNode(
+ Collections.singletonList(supportingNodeBuilder2)).build();
mdsalUtilsAsync.put(LogicalDatastoreType.CONFIGURATION, TEST_IID, data1, operationDesc);
assertEquals(data1, readDS());
- final CheckedFuture<Void, TransactionCommitFailedException> future = mdsalUtilsAsync.put(LogicalDatastoreType.CONFIGURATION, TEST_IID, data2);
+ final CheckedFuture<Void, TransactionCommitFailedException> future = mdsalUtilsAsync.put(
+ LogicalDatastoreType.CONFIGURATION, TEST_IID, data2);
Futures.addCallback(future, new FutureCallback<Void>() {
@Override
}
@Override
- public void onFailure(final Throwable t) {
- fail(t.getMessage());
+ public void onFailure(final Throwable ex) {
+ fail(ex.getMessage());
}
- });
+ }, MoreExecutors.directExecutor());
}
@Test
public void testMerge() {
final String operationDesc = "testMerge";
- final SupportingNode supportingNodeBuilder1 = new SupportingNodeBuilder().setKey(new SupportingNodeKey(new NodeId("id1"), TOPOLOGY_TEST)).build();
- final SupportingNode supportingNodeBuilder2 = new SupportingNodeBuilder().setKey(new SupportingNodeKey(new NodeId("id2"), TOPOLOGY_TEST)).build();
+ final SupportingNode supportingNodeBuilder1 = new SupportingNodeBuilder().setKey(
+ new SupportingNodeKey(new NodeId("id1"), TOPOLOGY_TEST)).build();
+ final SupportingNode supportingNodeBuilder2 = new SupportingNodeBuilder().setKey(
+ new SupportingNodeKey(new NodeId("id2"), TOPOLOGY_TEST)).build();
- final Node data1 = new NodeBuilder(data).setSupportingNode(Collections.singletonList(supportingNodeBuilder1)).build();
- final Node data2 = new NodeBuilder(data).setSupportingNode(Collections.singletonList(supportingNodeBuilder2)).build();
+ final Node data1 = new NodeBuilder(DATA).setSupportingNode(
+ Collections.singletonList(supportingNodeBuilder1)).build();
+ final Node data2 = new NodeBuilder(DATA).setSupportingNode(
+ Collections.singletonList(supportingNodeBuilder2)).build();
mdsalUtilsAsync.merge(LogicalDatastoreType.CONFIGURATION, TEST_IID, data1, operationDesc, true);
assertEquals(data1, readDS());
- final CheckedFuture<Void, TransactionCommitFailedException> future = mdsalUtilsAsync.merge(LogicalDatastoreType.CONFIGURATION, TEST_IID, data2, true);
+ final CheckedFuture<Void, TransactionCommitFailedException> future =
+ mdsalUtilsAsync.merge(LogicalDatastoreType.CONFIGURATION, TEST_IID, data2, true);
Futures.addCallback(future, new FutureCallback<Void>() {
@Override
}
@Override
- public void onFailure(final Throwable t) {
- fail(t.getMessage());
+ public void onFailure(final Throwable ex) {
+ fail(ex.getMessage());
}
- });
+ }, MoreExecutors.directExecutor());
}
@Test
public void testRead() {
- final CheckedFuture<Void, TransactionCommitFailedException> fut = mdsalUtilsAsync.put(LogicalDatastoreType.CONFIGURATION, TEST_IID, data);
+ final CheckedFuture<Void, TransactionCommitFailedException> fut =
+ mdsalUtilsAsync.put(LogicalDatastoreType.CONFIGURATION, TEST_IID, DATA);
Futures.addCallback(fut, new FutureCallback<Void>() {
-
@Override
public void onSuccess(final Void result) {
- final CheckedFuture<Optional<Node>, ReadFailedException> future = mdsalUtilsAsync.read(LogicalDatastoreType.CONFIGURATION, TEST_IID);
+ final CheckedFuture<Optional<Node>, ReadFailedException> future =
+ mdsalUtilsAsync.read(LogicalDatastoreType.CONFIGURATION, TEST_IID);
Optional<Node> optNode;
try {
optNode = future.get();
if (optNode.isPresent()) {
- assertEquals(data, optNode.get());
+ assertEquals(DATA, optNode.get());
} else {
fail("Couldn't read node");
}
}
@Override
- public void onFailure(final Throwable t) {
- fail(t.getMessage());
+ public void onFailure(final Throwable ex) {
+ fail(ex.getMessage());
}
- });
+ }, MoreExecutors.directExecutor());
}
private Node readDS() {
try {
- final Optional<Node> result = databroker.newReadOnlyTransaction().read(LogicalDatastoreType.CONFIGURATION, TEST_IID).get();
+ final Optional<Node> result = databroker.newReadOnlyTransaction().read(
+ LogicalDatastoreType.CONFIGURATION, TEST_IID).get();
if (result.isPresent()) {
return result.get();
}
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import com.google.common.base.Optional;
+import com.google.common.util.concurrent.CheckedFuture;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import com.google.common.base.Optional;
-import com.google.common.util.concurrent.CheckedFuture;
-
/**
- * Unit test for class {@link MdsalUtils}
- *
+ * Unit test for class {@link MdsalUtils}.
*/
@RunWith(MockitoJUnitRunner.class)
@SuppressWarnings({ "unchecked", "rawtypes" })
WriteTransaction writeTransaction = mock(WriteTransaction.class);
when(databroker.newWriteOnlyTransaction()).thenReturn(writeTransaction);
CheckedFuture<Void, TransactionCommitFailedException> future = mock(CheckedFuture.class);
- when(writeTransaction.submit()).thenReturn(future );
+ when(writeTransaction.submit()).thenReturn(future);
boolean result = mdsalUtils.delete(LogicalDatastoreType.CONFIGURATION, mock(InstanceIdentifier.class));
WriteTransaction writeTransaction = mock(WriteTransaction.class);
when(databroker.newWriteOnlyTransaction()).thenReturn(writeTransaction);
CheckedFuture<Void, TransactionCommitFailedException> future = mock(CheckedFuture.class);
- when(writeTransaction.submit()).thenReturn(future );
+ when(writeTransaction.submit()).thenReturn(future);
- boolean result = mdsalUtils.merge(LogicalDatastoreType.CONFIGURATION, mock(InstanceIdentifier.class), mock(DataObject.class));
+ boolean result = mdsalUtils.merge(LogicalDatastoreType.CONFIGURATION,
+ mock(InstanceIdentifier.class), mock(DataObject.class));
- verify(writeTransaction, times(1)).merge(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(DataObject.class), anyBoolean());
+ verify(writeTransaction, times(1)).merge(any(LogicalDatastoreType.class),
+ any(InstanceIdentifier.class), any(DataObject.class), anyBoolean());
verify(writeTransaction, times(1)).submit();
assertTrue("Error, the merge transaction failed", result);
WriteTransaction writeTransaction = mock(WriteTransaction.class);
when(databroker.newWriteOnlyTransaction()).thenReturn(writeTransaction);
CheckedFuture<Void, TransactionCommitFailedException> future = mock(CheckedFuture.class);
- when(writeTransaction.submit()).thenReturn(future );
+ when(writeTransaction.submit()).thenReturn(future);
- boolean result = mdsalUtils.put(LogicalDatastoreType.CONFIGURATION, mock(InstanceIdentifier.class), mock(DataObject.class));
+ boolean result = mdsalUtils.put(LogicalDatastoreType.CONFIGURATION,
+ mock(InstanceIdentifier.class), mock(DataObject.class));
- verify(writeTransaction, times(1)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(DataObject.class), anyBoolean());
+ verify(writeTransaction, times(1)).put(any(LogicalDatastoreType.class),
+ any(InstanceIdentifier.class), any(DataObject.class), anyBoolean());
verify(writeTransaction, times(1)).submit();
assertTrue("Error, the put transaction failed", result);
DataObject obj = mock(DataObject.class);
Optional opt = Optional.of(obj);
when(future.checkedGet()).thenReturn(opt);
- when(readOnlyTransaction.read(any(LogicalDatastoreType.class), any(InstanceIdentifier.class))).thenReturn(future);
+ when(readOnlyTransaction.read(any(LogicalDatastoreType.class),
+ any(InstanceIdentifier.class))).thenReturn(future);
DataObject result = mdsalUtils.read(LogicalDatastoreType.CONFIGURATION, mock(InstanceIdentifier.class));
package org.opendaylight.ovsdb.utils.ovsdb.it.utils;
+import static org.ops4j.pax.exam.CoreOptions.propagateSystemProperties;
+
+import com.esotericsoftware.yamlbeans.YamlException;
+import com.esotericsoftware.yamlbeans.YamlReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
-import java.io.InputStreamReader;
import java.io.IOException;
+import java.io.InputStreamReader;
import java.io.Reader;
import java.net.InetSocketAddress;
import java.net.URL;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
-
-import com.esotericsoftware.yamlbeans.YamlException;
-import com.esotericsoftware.yamlbeans.YamlReader;
import org.junit.Assert;
import org.ops4j.pax.exam.Option;
import org.osgi.framework.Bundle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import static org.ops4j.pax.exam.CoreOptions.propagateSystemProperties;
-
/**
* Run OVS(s) using docker-compose for use in integration tests.
* For example,
* to accept OVSDB connections.
* Any docker-compose file must have a port mapping.
*
+ * <p>
* The following explains how system properties are used to configure DockerOvs
* <pre>
* private static String ENV_USAGE =
* "-Ddocker.run - explicitly configure whether or not DockerOvs should run docker-compose\n" +
* "-Dovsdbserver.ipaddress - specify IP address of ovsdb server - implies -Ddocker.run=false\n" +
* "-Dovsdbserver.port - specify the port of the ovsdb server - required with -Dovsdbserver.ipaddress\n" +
- * "-Ddocker.compose.file - docker compose file in META-INF/docker-compose-files/. If not specified, default file is used\n" +
+ * "-Ddocker.compose.file - docker compose file in META-INF/docker-compose-files/.
+ * If not specified, default file is used\n" +
* "-Dovsdb.userspace.enabled - true when Ovs is running in user space (usually the case with docker)\n" +
* "-Dovsdb.controller.address - IP address of the controller (usually the docker0 interface with docker)\n" +
* "To auto-run Ovs and connect actively:\n" +
* " -Dovsdb.controller.address=x.x.x.x -Dovsdb.userspace.enabled=yes [-Ddocker.compose.file=ffff]\n" +
* "To auto-run Ovs and connect passively:\n" +
- * " -Dovsdbserver.connection=passive -Dovsdb.controller.address=x.x.x.x -Dovsdb.userspace.enabled=yes [-Ddocker.compose.file=ffff]\n" +
+ * " -Dovsdbserver.connection=passive -Dovsdb.controller.address=x.x.x.x
+ * -Dovsdb.userspace.enabled=yes [-Ddocker.compose.file=ffff]\n" +
* "To actively connect to a running Ovs:\n" +
* " -Dovsdbserver.ipaddress=x.x.x.x -Dovsdbserver.port=6641 -Dovsdb.controller.address=y.y.y.y\n" +
* "To passively connect to a running Ovs:\n" +
* the system properties.
*/
public class DockerOvs implements AutoCloseable {
- private static String ENV_USAGE = "Usage:\n" +
- "-Ddocker.run - explicitly configure whether or not DockerOvs should run docker-compose\n" +
- "-Dovsdbserver.ipaddress - specify IP address of ovsdb server - implies -Ddocker.run=false\n" +
- "-Dovsdbserver.port - specify the port of the ovsdb server - required with -Dovsdbserver.ipaddress\n" +
- "-Ddocker.compose.file - docker compose file in META-INF/docker-compose-files/. If not specified, default file is used\n" +
- "-Dovsdb.userspace.enabled - true when Ovs is running in user space (usually the case with docker)\n" +
- "-Dovsdb.controller.address - IP address of the controller (usually the docker0 interface with docker)\n" +
- "To auto-run Ovs and connect actively:\n" +
- " -Dovsdb.controller.address=x.x.x.x -Dovsdb.userspace.enabled=yes <-Ddocker.compose.file=ffff>\n" +
- "To auto-run Ovs and connect passively:\n" +
- " -Dovsdbserver.connection=passive -Dovsdb.controller.address=x.x.x.x -Dovsdb.userspace.enabled=yes <-Ddocker.compose.file=ffff>\n" +
- "To actively connect to a running Ovs:\n" +
- " -Dovsdbserver.ipaddress=x.x.x.x -Dovsdbserver.port=6641 -Dovsdb.controller.address=y.y.y.y\n" +
- "To passively connect to a running Ovs:\n" +
- " -Dovsdbserver.connection=passive -Ddocker.run=false\n";
+ private static String ENV_USAGE = "Usage:\n"
+ + "-Ddocker.run - explicitly configure whether or not DockerOvs should run docker-compose\n"
+ + "-Dovsdbserver.ipaddress - specify IP address of ovsdb server - implies -Ddocker.run=false\n"
+ + "-Dovsdbserver.port - specify the port of the ovsdb server - required with -Dovsdbserver.ipaddress\n"
+ + "-Ddocker.compose.file - docker compose file in META-INF/docker-compose-files/. "
+ + "If not specified, default file is used\n"
+ + "-Dovsdb.userspace.enabled - true when Ovs is running in user space (usually the case with docker)\n"
+ + "-Dovsdb.controller.address - IP address of the controller (usually the docker0 interface with docker)\n"
+ + "To auto-run Ovs and connect actively:\n"
+ + " -Dovsdb.controller.address=x.x.x.x -Dovsdb.userspace.enabled=yes <-Ddocker.compose.file=ffff>\n"
+ + "To auto-run Ovs and connect passively:\n"
+ + " -Dovsdbserver.connection=passive -Dovsdb.controller.address=x.x.x.x -Dovsdb.userspace.enabled=yes "
+ + "<-Ddocker.compose.file=ffff>\n"
+ + "To actively connect to a running Ovs:\n"
+ + " -Dovsdbserver.ipaddress=x.x.x.x -Dovsdbserver.port=6641 -Dovsdb.controller.address=y.y.y.y\n"
+ + "To passively connect to a running Ovs:\n" + " -Dovsdbserver.connection=passive -Ddocker.run=false\n";
private static final Logger LOG = LoggerFactory.getLogger(DockerOvs.class);
private static final String DEFAULT_DOCKER_FILE = "ovs-2.5.0-hwvtep.yml";
private String[] downCmd = {"sudo", "docker-compose", "-f", null, "stop"};
private String[] execCmd = {"sudo", "docker-compose", "-f", null, "exec", null};
- private String[] dockerPsCmdNoSudo = {"docker", "ps"};
- private String[] dockerPsCmd = {"sudo", "docker", "ps"};
+ private final String[] dockerPsCmdNoSudo = {"docker", "ps"};
+ private final String[] dockerPsCmd = {"sudo", "docker", "ps"};
private String[] netInspectCmd = {"sudo", "docker", "network", "inspect", "odl"};
private String[] netCreateCmd = {"sudo", "docker", "network", "create",
- "--subnet=172.99.0.0/16", "--gateway=172.99.0.254", "odl"};
+ "--subnet=172.99.0.0/16", "--gateway=172.99.0.254", "odl"};
private File tmpDockerComposeFile;
boolean isRunning;
private String envDockerComposeFile;
private String envDockerWaitForPing;
private boolean runDocker;
- private boolean runVenv;
private boolean createOdlNetwork;
class DockerComposeServiceInfo {
public String name;
public String port;
}
- private Map<String, DockerComposeServiceInfo> dockerComposeServices = new HashMap<>();
+
+ private final Map<String, DockerComposeServiceInfo> dockerComposeServices = new HashMap<>();
/**
* Get the array of system properties as pax exam Option objects for use in pax exam
private void setupEnvForDockerCompose(String venvWs) {
String dockerCompose = venvWs + "/venv/bin/docker-compose";
- String[] psCmdVenv = {"sudo", dockerCompose, "-f", null, "ps"};
- String[] psCmdNoSudoVenv = {dockerCompose, "-f", null, "ps"};
- String[] upCmdVenv = {"sudo", dockerCompose, "-f", null, "up", "-d", "--force-recreate"};
- String[] downCmdVenv = {"sudo", dockerCompose, "-f", null, "stop"};
- String[] execCmdVenv = {"sudo", dockerCompose, "-f", null, "exec", null};
-
- psCmd = psCmdVenv;
- psCmdNoSudo = psCmdNoSudoVenv;
- upCmd = upCmdVenv;
- downCmd = downCmdVenv;
- execCmd = execCmdVenv;
+
+ psCmd = new String[]{"sudo", dockerCompose, "-f", null, "ps"};
+ psCmdNoSudo = new String[]{dockerCompose, "-f", null, "ps"};
+ upCmd = new String[]{"sudo", dockerCompose, "-f", null, "up", "-d", "--force-recreate"};
+ downCmd = new String[]{"sudo", dockerCompose, "-f", null, "stop"};
+ execCmd = new String[]{"sudo", dockerCompose, "-f", null, "exec", null};
}
/**
envDockerWaitForPing = env.getProperty(ItConstants.DOCKER_WAIT_FOR_PING_SECS, "10");
createOdlNetwork = env.getProperty(ItConstants.CONTROLLER_IPADDRESS) == null;
String envRunDocker = env.getProperty(ItConstants.DOCKER_RUN);
- String connType = env.getProperty(ItConstants.CONNECTION_TYPE, ItConstants.CONNECTION_TYPE_ACTIVE);
String dockerFile = env.getProperty(ItConstants.DOCKER_COMPOSE_FILE_NAME);
String venvWs = env.getProperty(ItConstants.DOCKER_VENV_WS);
envDockerComposeFile = DOCKER_FILE_PATH + (null == dockerFile ? DEFAULT_DOCKER_FILE : dockerFile);
//Are we running docker? If we specified docker.run, that's the answer. Otherwise, if there is a server
//address we assume docker is already running
- runDocker = (envRunDocker != null) ? Boolean.parseBoolean(envRunDocker) : envServerAddress == null;
+ runDocker = envRunDocker != null ? Boolean.parseBoolean(envRunDocker) : envServerAddress == null;
//Should we run in a virtual environment? Needed for jenkins and docker-compose
- if ((venvWs != null) && (!venvWs.isEmpty())) {
+ if (venvWs != null && !venvWs.isEmpty()) {
LOG.info("Setting up virtual environment for docker compose");
setupEnvForDockerCompose(venvWs);
}
- if(runDocker) {
+ if (runDocker) {
return;
}
+ String connType = env.getProperty(ItConstants.CONNECTION_TYPE, ItConstants.CONNECTION_TYPE_ACTIVE);
if (connType.equals(ItConstants.CONNECTION_TYPE_PASSIVE)) {
return;
}
}
/**
- * Are we using some other OVS, not a docker we spin up?
+ * Are we using some other OVS, not a docker we spin up?.
+ *
* @return true if we are *not* running a docker image to test against
*/
public boolean usingExternalDocker() {
return "ovs" + numOvs;
}
}
+
public String[] getExecCmdPrefix(int numOvs) {
String[] res = new String[execCmd.length];
System.arraycopy(execCmd, 0, res, 0, execCmd.length);
/**
* Shut everything down.
- * @throws Exception but not really
*/
@Override
- public void close() throws Exception {
+ public void close() throws IOException, InterruptedException {
if (isRunning) {
ProcUtils.runProcess(10000, downCmd);
isRunning = false;
}
- try {
- tmpDockerComposeFile.delete();
- } catch (Exception ignored) {
- //No reason to fail the test, we're just being polite here.
- }
+ tmpDockerComposeFile.delete();
}
/**
* checked to make sure the Open_Vswitch DB is present. Note that this thread will
* run until it succeeds unless its interrupt() method is called.
*/
- class OvsdbPing extends Thread {
+ private class OvsdbPing extends Thread {
private final String host;
private final int port;
* @param ovsNumber which OVS is this?
* @param result an AtomicInteger that is incremented upon a successful "ping"
*/
- public OvsdbPing(int ovsNumber, AtomicInteger result) {
+ OvsdbPing(int ovsNumber, AtomicInteger result) {
this.host = getOvsdbAddress(ovsNumber);
this.port = Integer.parseInt(getOvsdbPort(ovsNumber));
this.result = result;
LOG.warn("OvsdbPing interrupted", e);
//return true here because we're done, ne'er to return again.
return true;
- } catch (Exception e) {
- LOG.info("OvsdbPing exception while attempting connect {}", e.toString());
+ } catch (IOException e) {
+ LOG.info("OvsdbPing exception while attempting connect", e);
}
return false;
}
pingers[0].start();
} else {
for (int i = 0; i < numOvs; i++) {
- pingers[i] = new OvsdbPing(i+1, numRunningOvs);
+ pingers[i] = new OvsdbPing(i + 1, numRunningOvs);
pingers[i].start();
}
}
long startTime = System.currentTimeMillis();
- while ( (System.currentTimeMillis() - startTime) < waitFor) {
+ while (System.currentTimeMillis() - startTime < waitFor) {
if (numRunningOvs.get() >= numOvs) {
LOG.info("DockerOvs.waitForOvsdbServers all OVS instances running");
break;
/**
* Constants for SouthboundIT.
*/
-public final class ItConstants {
- private ItConstants() {
- throw new AssertionError("This class should not be instantiated.");
- }
-
- public static final String ORG_OPS4J_PAX_LOGGING_CFG = "etc/org.ops4j.pax.logging.cfg";
- public static final String CUSTOM_PROPERTIES = "etc/custom.properties";
- public static final String SERVER_IPADDRESS = "ovsdbserver.ipaddress";
- public static final String SERVER_PORT = "ovsdbserver.port";
- public static final String CONTROLLER_IPADDRESS = "ovsdb.controller.address";
- public static final String USERSPACE_ENABLED = "ovsdb.userspace.enabled";
- public static final String SERVER_EXTRAS = "ovsdbserver.extras";
- public static final String CONNECTION_TYPE = "ovsdbserver.connection";
- public static final String CONNECTION_TYPE_ACTIVE = "active";
- public static final String CONNECTION_TYPE_PASSIVE = "passive";
- public static final int CONNECTION_INIT_TIMEOUT = 10000;
- public static final String DEFAULT_SERVER_IPADDRESS = "127.0.0.1";
- public static final String DEFAULT_SERVER_PORT = "6640";
- public static final String DEFAULT_OPENFLOW_PORT = "6653";
- public static final String DEFAULT_SERVER_EXTRAS = "false";
- public static final String BRIDGE_NAME = "brtest";
- public static final String PORT_NAME = "porttest";
- public static final String INTEGRATION_BRIDGE_NAME = "br-int";
- public static final String OPENFLOW_CONNECTION_PROTOCOL = "tcp";
- public static final String NETVIRT_TOPOLOGY_ID = "netvirt:1";
- public static final String DOCKER_COMPOSE_FILE_NAME="docker.compose.file";
- public static final String DOCKER_RUN="docker.run";
- public static final String DOCKER_VENV_WS="docker.vEnvWs";
- public static final String DOCKER_WAIT_FOR_PING_SECS = "docker.ping.wait.secs";
+public interface ItConstants {
+ String ORG_OPS4J_PAX_LOGGING_CFG = "etc/org.ops4j.pax.logging.cfg";
+ String CUSTOM_PROPERTIES = "etc/custom.properties";
+ String SERVER_IPADDRESS = "ovsdbserver.ipaddress";
+ String SERVER_PORT = "ovsdbserver.port";
+ String CONTROLLER_IPADDRESS = "ovsdb.controller.address";
+ String USERSPACE_ENABLED = "ovsdb.userspace.enabled";
+ String SERVER_EXTRAS = "ovsdbserver.extras";
+ String CONNECTION_TYPE = "ovsdbserver.connection";
+ String CONNECTION_TYPE_ACTIVE = "active";
+ String CONNECTION_TYPE_PASSIVE = "passive";
+ int CONNECTION_INIT_TIMEOUT = 10000;
+ String DEFAULT_SERVER_IPADDRESS = "127.0.0.1";
+ String DEFAULT_SERVER_PORT = "6640";
+ String DEFAULT_OPENFLOW_PORT = "6653";
+ String DEFAULT_SERVER_EXTRAS = "false";
+ String BRIDGE_NAME = "brtest";
+ String PORT_NAME = "porttest";
+ String INTEGRATION_BRIDGE_NAME = "br-int";
+ String OPENFLOW_CONNECTION_PROTOCOL = "tcp";
+ String NETVIRT_TOPOLOGY_ID = "netvirt:1";
+ String DOCKER_COMPOSE_FILE_NAME = "docker.compose.file";
+ String DOCKER_RUN = "docker.run";
+ String DOCKER_VENV_WS = "docker.vEnvWs";
+ String DOCKER_WAIT_FOR_PING_SECS = "docker.ping.wait.secs";
}
import static org.junit.Assert.assertTrue;
import java.util.List;
-
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.ovsdb.utils.mdsal.utils.NotifyingDataChangeListener;
import org.opendaylight.ovsdb.utils.southbound.utils.SouthboundUtils;
private static final Logger LOG = LoggerFactory.getLogger(NodeInfo.class);
public static final String INTEGRATION_BRIDGE_NAME = "br-int";
- private ConnectionInfo connectionInfo;
- private InstanceIdentifier<Node> ovsdbIid;
- InstanceIdentifier<Node> bridgeIid;
+ private final ConnectionInfo connectionInfo;
+ private final InstanceIdentifier<Node> ovsdbIid;
+ private final InstanceIdentifier<Node> bridgeIid;
public long datapathId;
public Node ovsdbNode;
public Node bridgeNode;
- NotifyingDataChangeListener ovsdbWaiter;
- NotifyingDataChangeListener bridgeWaiter;
- List<NotifyingDataChangeListener> waitList;
- OvsdbItUtils itUtils;
+ private NotifyingDataChangeListener ovsdbWaiter;
+ private NotifyingDataChangeListener bridgeWaiter;
+ private final List<NotifyingDataChangeListener> waitList;
+ private final OvsdbItUtils itUtils;
/**
* Create a new NodeInfo object.
bridgeWaiter.setMask(NotifyingDataChangeListener.BIT_DELETE);
assertTrue(itUtils.southboundUtils.deleteBridge(connectionInfo, INTEGRATION_BRIDGE_NAME, 0));
bridgeWaiter.waitForDeletion();
- Node bridgeNode = itUtils.mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, bridgeIid);
- assertNull("Bridge should not be found", bridgeNode);
+ assertNull("Bridge should not be found", itUtils.mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, bridgeIid));
assertTrue(itUtils.southboundUtils.disconnectOvsdbNode(connectionInfo, 0));
ovsdbWaiter.waitForDeletion();
- Node ovsdbNode = itUtils.mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, ovsdbIid);
- assertNull("Ovsdb node should not be found", ovsdbNode);
+ assertNull("Ovsdb node should not be found",
+ itUtils.mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, ovsdbIid));
closeWaiters();
}
-
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
-
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Run subprocesses and log or return their output.
*/
-public class ProcUtils {
+public final class ProcUtils {
private static final Logger LOG = LoggerFactory.getLogger(ProcUtils.class);
+ private ProcUtils() {
+ }
+
/**
* Run a process and assert the exit code is 0.
* @param waitFor How long to wait for the command to execute
logText != null ? logText : "", stderr.readLine());
}
- StringBuilder stdoutStringBuilder = (capturedStdout != null) ? capturedStdout : new StringBuilder();
+ StringBuilder stdoutStringBuilder = capturedStdout != null ? capturedStdout : new StringBuilder();
int read;
char[] buf = new char[1024];
while (-1 != (read = stdout.read(buf))) {
exitValue = proc.exitValue();
break;
} catch (IllegalThreadStateException e) {
- if ((System.currentTimeMillis() - startTime) < waitFor) {
+ if (System.currentTimeMillis() - startTime < waitFor) {
Thread.sleep(200);
} else {
LOG.warn("ProcUtils.waitForExitValue: timed out while waiting for command to complete", e);
import java.util.HashMap;
import java.util.Map;
-
import org.osgi.framework.Bundle;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
+import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
- * The class helps to register and retrieve OSGi service registry
+ * The class helps to register and retrieve OSGi service registry.
*/
public final class ServiceHelper {
private static final Logger LOG = LoggerFactory.getLogger(ServiceHelper.class);
private static final Map<Class<?>, Object> OVERRIDES = new HashMap<>();
+ private ServiceHelper() {
+ }
+
/**
* Override a global instance. This should generally only be used for testing.
*
/**
* Retrieve all the Instances of a Service, optionally
* filtered via serviceFilter if non-null else all the results are
- * returned if null
+ * returned if null.
*
* @param clazz The target class
* @param bundle The caller
*/
private static Object[] getGlobalInstances(Class<?> clazz, Object bundle,
String serviceFilter) {
- Object instances[] = null;
+ Object[] instances = null;
try {
Bundle ourBundle = FrameworkUtil.getBundle(bundle.getClass());
if (ourBundle != null) {
- BundleContext bCtx = ourBundle.getBundleContext();
+ BundleContext bundleContext = ourBundle.getBundleContext();
- ServiceReference<?>[] services = bCtx.getServiceReferences(clazz
+ ServiceReference<?>[] services = bundleContext.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]);
+ instances[i] = bundleContext.getService(services[i]);
}
}
}
- } catch (Exception e) {
+ } catch (IllegalStateException | InvalidSyntaxException e) {
LOG.error("Error retrieving global instances of {} from caller {} with filter {}",
clazz, bundle, serviceFilter, e);
}
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.osgi.framework.Bundle;
import org.osgi.framework.FrameworkUtil;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
* Test method for
* {@link ServiceHelper#getGlobalInstance(Class, Object)}
*/
- public void getGlobalInstanceTest () {
- Bundle bundle = new MockBundle();
-
+ public void getGlobalInstanceTest() {
PowerMockito.mockStatic(FrameworkUtil.class);
PowerMockito.when(FrameworkUtil.getBundle(any(Class.class)))
assertNull("Service should be null", object);
PowerMockito.when(FrameworkUtil.getBundle(any(Class.class)))
- .thenReturn(bundle);
+ .thenReturn(new MockBundle());
object = ServiceHelper.getGlobalInstance(Test.class, this);
assertNotNull("Service should not be null", object);
}
package org.opendaylight.ovsdb.utils.southbound.utils;
+import com.google.common.collect.ImmutableBiMap;
import java.math.BigInteger;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
+import java.net.SocketException;
import java.net.UnknownHostException;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.common.collect.ImmutableBiMap;
-
public class SouthboundUtils {
private static final Logger LOG = LoggerFactory.getLogger(SouthboundUtils.class);
private static final int OVSDB_UPDATE_TIMEOUT = 1000;
return createInstanceIdentifier(createManagedNodeId(ovsdbNodeKey.getNodeId(), bridgeName));
}
- public static NodeId createManagedNodeId(NodeId ovsdbNodeId, String bridgeName) {
- return new NodeId(ovsdbNodeId.getValue()
- + "/" + BRIDGE_URI_PREFIX + "/" + bridgeName);
- }
-
public static InstanceIdentifier<Node> createInstanceIdentifier(ConnectionInfo key) {
return createInstanceIdentifier(key.getRemoteIp(), key.getRemotePort());
}
return path;
}
- public static InstanceIdentifier<Node> createInstanceIdentifier(ConnectionInfo key,OvsdbBridgeName bridgeName) {
+ public static InstanceIdentifier<Node> createInstanceIdentifier(ConnectionInfo key, OvsdbBridgeName bridgeName) {
return createInstanceIdentifier(createManagedNodeId(key, bridgeName));
}
return createInstanceIdentifier(key, new OvsdbBridgeName(bridgeName));
}
- public InstanceIdentifier<TerminationPoint> createTerminationPointInstanceIdentifier(Node node, String portName){
+ public InstanceIdentifier<TerminationPoint> createTerminationPointInstanceIdentifier(Node node, String portName) {
InstanceIdentifier<TerminationPoint> terminationPointPath = InstanceIdentifier
.create(NetworkTopology.class)
return new NodeKey(createNodeId(ip, port));
}
+ public static NodeId createManagedNodeId(NodeId ovsdbNodeId, String bridgeName) {
+ return new NodeId(ovsdbNodeId.getValue()
+ + "/" + BRIDGE_URI_PREFIX + "/" + bridgeName);
+ }
+
public static NodeId createManagedNodeId(ConnectionInfo key, OvsdbBridgeName bridgeName) {
return createManagedNodeId(key.getRemoteIp(), key.getRemotePort(), bridgeName);
}
return nodeKey.getNodeId();
}
- public ConnectionInfo getConnectionInfo(Node ovsdbNode) {
- ConnectionInfo connectionInfo = null;
- OvsdbNodeAugmentation ovsdbNodeAugmentation = extractOvsdbNode(ovsdbNode);
- if (ovsdbNodeAugmentation != null) {
- connectionInfo = ovsdbNodeAugmentation.getConnectionInfo();
- }
- return connectionInfo;
- }
-
public OvsdbNodeAugmentation extractOvsdbNode(Node node) {
return node.getAugmentation(OvsdbNodeAugmentation.class);
}
return new IpAddress(ipv6);
}
+ public ConnectionInfo getConnectionInfo(Node ovsdbNode) {
+ ConnectionInfo connectionInfo = null;
+ OvsdbNodeAugmentation ovsdbNodeAugmentation = extractOvsdbNode(ovsdbNode);
+ if (ovsdbNodeAugmentation != null) {
+ connectionInfo = ovsdbNodeAugmentation.getConnectionInfo();
+ }
+ return connectionInfo;
+ }
+
public static ConnectionInfo getConnectionInfo(final String addressStr, final String portStr) {
InetAddress inetAddress = null;
try {
}
/**
- * extract the <code>LogicalDataStoreType.OPERATIONAL</code> type data store contents for the particular bridge
- * identified by <code>bridgeName</code>
+ * Extract the <code>LogicalDataStoreType.OPERATIONAL</code> type data store contents for the particular bridge
+ * identified by <code>bridgeName</code>.
*
* @param connectionInfo address for the node
* @param bridgeName name of the bridge
InstanceIdentifier<Node> ovsdbNodeIid =
(InstanceIdentifier<Node>) bridgeAugmentation.getManagedBy().getValue();
ovsdbNode = mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, ovsdbNodeIid);
- }else{
+ } else {
LOG.debug("readOvsdbNode: Provided node is not a bridge node : {}",bridgeNode);
}
return ovsdbNode;
return result;
}
- /**
- * Set the controllers of an existing bridge node
- * @param ovsdbNode where the bridge is
- * @param bridgeName Name of the bridge
- * @param controllers controller strings
- * @return success if the write to md-sal was successful
- */
- public boolean setBridgeController(Node ovsdbNode, String bridgeName, List<String> controllers) {
- return setBridgeController(ovsdbNode, bridgeName, controllers, null, null);
- }
- /**
- * Set the controllers of an existing bridge node
- * @param ovsdbNode where the bridge is
- * @param bridgeName Name of the bridge
- * @param controllers controller strings
- * @param maxBackoff Max backoff in milliseconds
- * @param inactivityProbe inactivity probe in milliseconds
- * @return success if the write to md-sal was successful
- */
- public boolean setBridgeController(Node ovsdbNode, String bridgeName, List<String> controllers,
- Long maxBackoff, Long inactivityProbe) {
- LOG.debug("setBridgeController: ovsdbNode: {}, bridgeNode: {}, controller(s): {}",
- ovsdbNode, bridgeName, controllers);
-
- InstanceIdentifier<Node> bridgeNodeIid = createInstanceIdentifier(ovsdbNode.getKey(), bridgeName);
- Node bridgeNode = mdsalUtils.read(LogicalDatastoreType.CONFIGURATION, bridgeNodeIid);
- if (bridgeNode == null) {
- LOG.info("setBridgeController could not find bridge in configuration {}", bridgeNodeIid);
- return false;
- }
-
- OvsdbBridgeAugmentation bridgeAug = extractBridgeAugmentation(bridgeNode);
-
- //Only add controller entries that do not already exist on this bridge
- List<ControllerEntry> existingControllerEntries = bridgeAug.getControllerEntry();
- List<ControllerEntry> newControllerEntries = new ArrayList<>();
- if(existingControllerEntries != null) {
- NEW_ENTRY_LOOP:
- for (ControllerEntry newEntry : createControllerEntries(controllers, maxBackoff, inactivityProbe)) {
- for (ControllerEntry existingEntry : existingControllerEntries) {
- if (newEntry.getTarget().equals(existingEntry.getTarget())) {
- continue NEW_ENTRY_LOOP;
- }
- }
- newControllerEntries.add(newEntry);
- }
- } else {
- newControllerEntries = createControllerEntries(controllers,maxBackoff, inactivityProbe);
- }
-
- if(newControllerEntries.isEmpty()) {
- return true;
- }
-
- NodeBuilder nodeBuilder = new NodeBuilder(bridgeNode);
- OvsdbBridgeAugmentationBuilder augBuilder = new OvsdbBridgeAugmentationBuilder(bridgeAug);
-
- augBuilder.setControllerEntry(newControllerEntries);
- nodeBuilder.addAugmentation(OvsdbBridgeAugmentation.class, augBuilder.build());
- InstanceIdentifier<Node> bridgeIid = createInstanceIdentifier(ovsdbNode.getKey(), bridgeName);
- return mdsalUtils.merge(LogicalDatastoreType.CONFIGURATION, bridgeIid, nodeBuilder.build());
- }
-
public boolean addBridge(Node ovsdbNode, String bridgeName, List<String> controllersStr,
final Class<? extends DatapathTypeBase> dpType, String mac) {
return addBridge(ovsdbNode, bridgeName, controllersStr, dpType, mac, null, null);
}
public boolean addBridge(Node ovsdbNode, String bridgeName, List<String> controllersStr,
- final Class<? extends DatapathTypeBase> dpType,
- List<BridgeOtherConfigs> otherConfigs,
- Long maxBackoff, Long inactivityProbe) {
+ final Class<? extends DatapathTypeBase> dpType,
+ List<BridgeOtherConfigs> otherConfigs,
+ Long maxBackoff, Long inactivityProbe) {
boolean result;
LOG.info("addBridge: node: {}, bridgeName: {}, controller(s): {}", ovsdbNode, bridgeName, controllersStr);
controllersStr, maxBackoff, inactivityProbe));
ovsdbBridgeAugmentationBuilder.setBridgeName(new OvsdbBridgeName(bridgeName));
ovsdbBridgeAugmentationBuilder.setProtocolEntry(createMdsalProtocols());
- ovsdbBridgeAugmentationBuilder.setFailMode( OVSDB_FAIL_MODE_MAP.inverse().get("secure"));
+ ovsdbBridgeAugmentationBuilder.setFailMode(OVSDB_FAIL_MODE_MAP.inverse().get("secure"));
// TODO: Currently netvirt relies on this function to set disabled-in-band=true. However,
// TODO (cont): a better design would be to have netvirt pass that in. That way this function
// TODO (cont): can take a null otherConfigs to erase other_configs.
return result;
}
+ /**
+ * Set the controllers of an existing bridge node.
+ *
+ * @param ovsdbNode where the bridge is
+ * @param bridgeName Name of the bridge
+ * @param controllers controller strings
+ * @return success if the write to md-sal was successful
+ */
+ public boolean setBridgeController(Node ovsdbNode, String bridgeName, List<String> controllers) {
+ return setBridgeController(ovsdbNode, bridgeName, controllers, null, null);
+ }
+
+ /**
+ * Set the controllers of an existing bridge node.
+ *
+ * @param ovsdbNode where the bridge is
+ * @param bridgeName Name of the bridge
+ * @param controllers controller strings
+ * @param maxBackoff Max backoff in milliseconds
+ * @param inactivityProbe inactivity probe in milliseconds
+ * @return success if the write to md-sal was successful
+ */
+ public boolean setBridgeController(Node ovsdbNode, String bridgeName, List<String> controllers,
+ Long maxBackoff, Long inactivityProbe) {
+ LOG.debug("setBridgeController: ovsdbNode: {}, bridgeNode: {}, controller(s): {}",
+ ovsdbNode, bridgeName, controllers);
+
+ InstanceIdentifier<Node> bridgeNodeIid = createInstanceIdentifier(ovsdbNode.getKey(), bridgeName);
+ Node bridgeNode = mdsalUtils.read(LogicalDatastoreType.CONFIGURATION, bridgeNodeIid);
+ if (bridgeNode == null) {
+ LOG.info("setBridgeController could not find bridge in configuration {}", bridgeNodeIid);
+ return false;
+ }
+
+ OvsdbBridgeAugmentation bridgeAug = extractBridgeAugmentation(bridgeNode);
+
+ //Only add controller entries that do not already exist on this bridge
+ List<ControllerEntry> existingControllerEntries = bridgeAug.getControllerEntry();
+ List<ControllerEntry> newControllerEntries = new ArrayList<>();
+ if (existingControllerEntries != null) {
+ NEW_ENTRY_LOOP:
+ for (ControllerEntry newEntry : createControllerEntries(controllers, maxBackoff, inactivityProbe)) {
+ for (ControllerEntry existingEntry : existingControllerEntries) {
+ if (newEntry.getTarget().equals(existingEntry.getTarget())) {
+ continue NEW_ENTRY_LOOP;
+ }
+ }
+ newControllerEntries.add(newEntry);
+ }
+ } else {
+ newControllerEntries = createControllerEntries(controllers,maxBackoff, inactivityProbe);
+ }
+
+ if (newControllerEntries.isEmpty()) {
+ return true;
+ }
+
+ NodeBuilder nodeBuilder = new NodeBuilder(bridgeNode);
+ OvsdbBridgeAugmentationBuilder augBuilder = new OvsdbBridgeAugmentationBuilder(bridgeAug);
+
+ augBuilder.setControllerEntry(newControllerEntries);
+ nodeBuilder.addAugmentation(OvsdbBridgeAugmentation.class, augBuilder.build());
+ InstanceIdentifier<Node> bridgeIid = createInstanceIdentifier(ovsdbNode.getKey(), bridgeName);
+ return mdsalUtils.merge(LogicalDatastoreType.CONFIGURATION, bridgeIid, nodeBuilder.build());
+ }
private void setManagedBy(final OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder,
final ConnectionInfo connectionInfo) {
public boolean addTerminationPoint(
Node bridgeNode, String portName, String type, Map<String, String> options, Map<String, String> externalIds,
Long ofPort) {
- InstanceIdentifier<TerminationPoint> tpIid = createTerminationPointInstanceIdentifier(bridgeNode, portName);
OvsdbTerminationPointAugmentationBuilder tpAugmentationBuilder = new OvsdbTerminationPointAugmentationBuilder();
tpAugmentationBuilder.setName(portName);
}
TerminationPointBuilder tpBuilder = new TerminationPointBuilder();
+ InstanceIdentifier<TerminationPoint> tpIid = createTerminationPointInstanceIdentifier(bridgeNode, portName);
tpBuilder.setKey(InstanceIdentifier.keyOf(tpIid));
tpBuilder.addAugmentation(OvsdbTerminationPointAugmentation.class, tpAugmentationBuilder.build());
/* TODO SB_MIGRATION should this be merge or mdsalUtils.put */
public Boolean addTerminationPoint(Node bridgeNode, String bridgeName, String portName,
String type, Map<String, String> options) {
- InstanceIdentifier<TerminationPoint> tpIid = createTerminationPointInstanceIdentifier(
- bridgeNode, portName);
OvsdbTerminationPointAugmentationBuilder tpAugmentationBuilder = new OvsdbTerminationPointAugmentationBuilder();
tpAugmentationBuilder.setName(portName);
tpAugmentationBuilder.setOptions(optionsList);
TerminationPointBuilder tpBuilder = new TerminationPointBuilder();
+ InstanceIdentifier<TerminationPoint> tpIid = createTerminationPointInstanceIdentifier(bridgeNode, portName);
tpBuilder.setKey(InstanceIdentifier.keyOf(tpIid));
tpBuilder.addAugmentation(OvsdbTerminationPointAugmentation.class, tpAugmentationBuilder.build());
/* TODO SB_MIGRATION should this be merge or mdsalUtils.put */
private String getLocalControllerHostIpAddress() {
String ipaddress = null;
- try{
- for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();){
+ try {
+ for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
+ ifaces.hasMoreElements();) {
NetworkInterface iface = ifaces.nextElement();
for (Enumeration<InetAddress> inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
}
}
}
- }catch (Exception e){
+ } catch (SocketException e) {
LOG.warn("Exception while fetching local host ip address ", e);
}
return ipaddress;
return null;
}
- public List<OvsdbTerminationPointAugmentation> extractTerminationPointAugmentations( Node node ) {
+ public List<OvsdbTerminationPointAugmentation> extractTerminationPointAugmentations(Node node) {
List<OvsdbTerminationPointAugmentation> tpAugmentations = new ArrayList<>();
if (node == null) {
LOG.error("extractTerminationPointAugmentations: Node value is null");
return Collections.emptyList();
}
List<TerminationPoint> terminationPoints = node.getTerminationPoint();
- if(terminationPoints != null && !terminationPoints.isEmpty()){
- for(TerminationPoint tp : terminationPoints){
+ if (terminationPoints != null && !terminationPoints.isEmpty()) {
+ for (TerminationPoint tp : terminationPoints) {
OvsdbTerminationPointAugmentation ovsdbTerminationPointAugmentation =
tp.getAugmentation(OvsdbTerminationPointAugmentation.class);
if (ovsdbTerminationPointAugmentation != null) {
/**
* Extract the <code>OvsdbTerminationPointAugmentation</code> for the particular <code>node</code> identified by
* <code>portName</code>.
- *
- * @param node
- * @param portName
- * @return
*/
public OvsdbTerminationPointAugmentation getTerminationPointOfBridge(Node node, String portName) {
OvsdbTerminationPointAugmentation tpAugmentation = extractTerminationPointAugmentation(node,portName);
- if(tpAugmentation == null){
+ if (tpAugmentation == null) {
List<OvsdbTerminationPointAugmentation> tpAugmentations = readTerminationPointAugmentations(node);
- if(tpAugmentations != null){
- for(OvsdbTerminationPointAugmentation ovsdbTpAugmentation : tpAugmentations){
- if(ovsdbTpAugmentation.getName().equals(portName)){
+ if (tpAugmentations != null) {
+ for (OvsdbTerminationPointAugmentation ovsdbTpAugmentation : tpAugmentations) {
+ if (ovsdbTpAugmentation.getName().equals(portName)) {
return ovsdbTpAugmentation;
}
}
}
/**
- * read the list of <code>OvsdbTerminationPointAugmentation</code> for the particular <code>node</code>.
- *
- * @param node
- * @return
+ * Read the list of <code>OvsdbTerminationPointAugmentation</code> for the particular <code>node</code>.
*/
public List<OvsdbTerminationPointAugmentation> readTerminationPointAugmentations(Node node) {
if (node == null) {
final Matcher dbVersionMatcher = PATTERN.matcher(dbVersion);
final Matcher minVersionMatcher = PATTERN.matcher(minVersion);
LOG.debug("dbVersion {}, minVersion {}", dbVersion, minVersion);
- if (!dbVersionMatcher.find()){
+ if (!dbVersionMatcher.find()) {
LOG.error("Invalid DB version format {}", dbVersion);
return false;
}
- if (!minVersionMatcher.find()){
+ if (!minVersionMatcher.find()) {
LOG.error("Invalid Min DB version format {}", minVersion);
return false;
}
if (dbVersion != null && !dbVersion.isEmpty() && minVersion != null
&& !minVersion.isEmpty()) {
- if (Integer.valueOf(dbVersionMatcher.group(1)).equals(Integer.valueOf(minVersionMatcher.group(1))) &&
- Integer.valueOf(dbVersionMatcher.group(2)).equals(Integer.valueOf(minVersionMatcher.group(2))) &&
- Integer.valueOf(dbVersionMatcher.group(3)).equals(Integer.valueOf(minVersionMatcher.group(3)))) {
+ if (Integer.valueOf(dbVersionMatcher.group(1)).equals(Integer.valueOf(minVersionMatcher.group(1)))
+ && Integer.valueOf(dbVersionMatcher.group(2)).equals(Integer.valueOf(minVersionMatcher.group(2)))
+ && Integer.valueOf(dbVersionMatcher.group(3)).equals(Integer.valueOf(minVersionMatcher.group(3)))) {
return true;
}
- if (Integer.valueOf(dbVersionMatcher.group(1)).intValue() > Integer.valueOf(minVersionMatcher.group(1)).intValue()) {
+ if (Integer.valueOf(dbVersionMatcher.group(1)).intValue()
+ > Integer.valueOf(minVersionMatcher.group(1)).intValue()) {
return true;
}
- if (Integer.valueOf(dbVersionMatcher.group(1)).intValue() < Integer.valueOf(minVersionMatcher.group(1)).intValue()) {
+ if (Integer.valueOf(dbVersionMatcher.group(1)).intValue()
+ < Integer.valueOf(minVersionMatcher.group(1)).intValue()) {
return false;
}
// major version is equal
- if (Integer.valueOf(dbVersionMatcher.group(2)).intValue() > Integer.valueOf(minVersionMatcher.group(2)).intValue()) {
+ if (Integer.valueOf(dbVersionMatcher.group(2)).intValue()
+ > Integer.valueOf(minVersionMatcher.group(2)).intValue()) {
return true;
}
- if (Integer.valueOf(dbVersionMatcher.group(2)).intValue() < Integer.valueOf(minVersionMatcher.group(2)).intValue()) {
+
+ if (Integer.valueOf(dbVersionMatcher.group(2)).intValue()
+ < Integer.valueOf(minVersionMatcher.group(2)).intValue()) {
return false;
}
- if (Integer.valueOf(dbVersionMatcher.group(3)).intValue() > Integer.valueOf(minVersionMatcher.group(3)).intValue()) {
+ if (Integer.valueOf(dbVersionMatcher.group(3)).intValue()
+ > Integer.valueOf(minVersionMatcher.group(3)).intValue()) {
return true;
}
}
package org.opendaylight.ovsdb.utils.southbound.utils;
import static org.junit.Assert.assertTrue;
+
import org.junit.Test;
public class SouthboundUtilsTest {